Skip to content

Commit

Permalink
Add inline docstrings examples and run fmt
Browse files Browse the repository at this point in the history
  • Loading branch information
vemonet committed Dec 15, 2023
1 parent 87f8cb7 commit 6d1c0f0
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 26 deletions.
14 changes: 1 addition & 13 deletions lib/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,7 @@ use std::error::Error;
use std::fmt;
use std::str::Utf8Error;

// #[derive(Debug)]
// pub struct DuplicateRecordError(pub String);

// impl Error for DuplicateRecordError {}

// impl fmt::Display for DuplicateRecordError {
// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// write!(f, "Curies Duplicate Record: {}", self.0)
// }
// }

// NOTE: In case we need a generic error that contains other errors

/// Enum of errors returned by this library
#[derive(Debug)]
pub enum CuriesError {
NotFound(String),
Expand Down
75 changes: 71 additions & 4 deletions lib/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,31 @@ pub struct Record {

/// A `Converter` is composed of 2 HashMaps (one for prefixes, one for URIs),
/// and a trie search to find the longest URI
/// # Examples
///
/// ```
/// use curies::{Converter, Record};
/// use std::collections::HashSet;
///
/// fn use_converter() -> Result<(), Box<dyn std::error::Error>> {
/// let mut converter = Converter::new();
/// let record1 = Record {
/// prefix: "doid".to_string(),
/// uri_prefix: "http://purl.obolibrary.org/obo/DOID_".to_string(),
/// prefix_synonyms: HashSet::from(["DOID".to_string()]),
/// uri_prefix_synonyms: HashSet::from(["https://identifiers.org/DOID/"].map(String::from)),
/// };
/// converter.add_record(record1)?;
///
/// let uri = converter.expand("doid:1234")?;
/// assert_eq!(uri, "http://purl.obolibrary.org/obo/DOID_1234");
///
/// let curie = converter.compress("http://purl.obolibrary.org/obo/DOID_1234")?;
/// assert_eq!(curie, "doid:1234");
/// Ok(())
/// }
/// use_converter().unwrap();
/// ```
pub struct Converter {
prefix_map: HashMap<String, Arc<Record>>,
uri_map: HashMap<String, Arc<Record>>,
Expand All @@ -34,6 +59,22 @@ pub struct Converter {

impl Converter {
/// Create an empty `Converter`
///
/// # Examples
///
/// ```
/// use curies::{Converter, Record};
/// use std::collections::HashSet;
///
/// let mut converter = Converter::new();
/// let record1 = Record {
/// prefix: "doid".to_string(),
/// uri_prefix: "http://purl.obolibrary.org/obo/DOID_".to_string(),
/// prefix_synonyms: HashSet::from(["DOID".to_string()]),
/// uri_prefix_synonyms: HashSet::from(["https://identifiers.org/DOID/"].map(String::from)),
/// };
/// converter.add_record(record1).unwrap();
/// ```
pub fn new() -> Self {
Converter {
prefix_map: HashMap::new(),
Expand All @@ -44,6 +85,18 @@ impl Converter {
}

/// Create a `Converter` from a prefix `HashMap`
///
/// # Examples
///
/// ```
/// use curies::{Converter, Record};
/// use std::collections::HashMap;
///
/// let mut prefix_map: HashMap<String, String> = HashMap::new();
/// prefix_map.insert("DOID".to_string(), "http://purl.obolibrary.org/obo/DOID_".to_string());
/// prefix_map.insert("OBO".to_string(), "http://purl.obolibrary.org/obo/".to_string());
/// let converter = Converter::from_prefix_map(prefix_map).unwrap();
/// ```
pub fn from_prefix_map(prefix_map: HashMap<String, String>) -> Result<Self, CuriesError> {
let mut converter = Converter::default();
for (prefix, uri_prefix) in prefix_map {
Expand All @@ -58,6 +111,17 @@ impl Converter {
}

/// Create a `Converter` from a JSON-LD file context
///
/// # Examples
///
/// ```
/// use curies::{Converter, Record, error::CuriesError};
///
/// fn test_from_jsonld() -> Result<(), CuriesError> {
/// let converter = Converter::from_jsonld("http://purl.obolibrary.org/meta/obo_context.jsonld");
/// Ok(())
/// }
/// ```
pub async fn from_jsonld<T: DataSource>(data: T) -> Result<Self, CuriesError> {
let prefix_map = data.fetch().await?;
let mut converter = Converter::default();
Expand Down Expand Up @@ -185,7 +249,6 @@ impl Default for Converter {
}
}


/// Trait to provide the data as URL, HashMap, string, or Path to file
#[async_trait]
pub trait DataSource {
Expand Down Expand Up @@ -214,9 +277,13 @@ impl DataSource for &str {
// Making an HTTP request
let res = reqwest::get(self).await?;
if res.status().is_success() {
return Ok(res.json().await?)
return Ok(res.json().await?);
} else {
return Err(CuriesError::Reqwest(format!("{}: {}", res.status(), res.text().await?)))
return Err(CuriesError::Reqwest(format!(
"{}: {}",
res.status(),
res.text().await?
)));
}
} else {
// Directly parsing the provided string as JSON
Expand All @@ -234,7 +301,7 @@ impl DataSource for &Path {
file.read_to_string(&mut contents)?;
Ok(serde_json::from_str(&contents)?)
} else {
return Err(CuriesError::NotFound(format!("{:?}", self.to_str())))
return Err(CuriesError::NotFound(format!("{:?}", self.to_str())));
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions lib/src/sources.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use crate::{Converter, error::CuriesError};

use crate::{error::CuriesError, Converter};

/// Get the latest OBO Foundry context.
pub async fn get_obo_converter() -> Result<Converter, CuriesError> {
Converter::from_jsonld("http://purl.obolibrary.org/meta/obo_context.jsonld").await
}
}
15 changes: 10 additions & 5 deletions lib/tests/curies_test.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use curies::{Converter, Record, sources::get_obo_converter};
use std::collections::{HashSet, HashMap};
use curies::{sources::get_obo_converter, Converter, Record};
use std::collections::{HashMap, HashSet};

#[test]
fn new_empty_converter() -> Result<(), Box<dyn std::error::Error>> {
Expand Down Expand Up @@ -44,12 +44,17 @@ fn new_empty_converter() -> Result<(), Box<dyn std::error::Error>> {
Ok(())
}


#[test]
fn from_prefix_map_converter() -> Result<(), Box<dyn std::error::Error>> {
let mut prefix_map: HashMap<String, String> = HashMap::new();
prefix_map.insert("DOID".to_string(), "http://purl.obolibrary.org/obo/DOID_".to_string());
prefix_map.insert("OBO".to_string(), "http://purl.obolibrary.org/obo/".to_string());
prefix_map.insert(
"DOID".to_string(),
"http://purl.obolibrary.org/obo/DOID_".to_string(),
);
prefix_map.insert(
"OBO".to_string(),
"http://purl.obolibrary.org/obo/".to_string(),
);
let converter = Converter::from_prefix_map(prefix_map)?;

let uri = converter.expand("DOID:1234")?;
Expand Down
2 changes: 1 addition & 1 deletion python/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ pub struct RecordPy {
}

impl RecordPy {
#[allow(clippy::wrong_self_convention)]
fn into_record(&self) -> Record {
Record {
prefix: self.prefix.clone(),
Expand Down Expand Up @@ -95,5 +96,4 @@ impl ConverterPy {
.compress(&uri)
.map_err(|e| PyErr::new::<PyException, _>(format!("Error Checking: {e}")))
}

}

0 comments on commit 6d1c0f0

Please sign in to comment.