-
Notifications
You must be signed in to change notification settings - Fork 1
/
prefix_map.rs
114 lines (96 loc) · 2.82 KB
/
prefix_map.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use std::fmt;
use indexmap::IndexMap;
use iri_s::*;
use std::str::FromStr;
#[derive(Debug)]
pub struct PrefixMap<'a> {
map: IndexMap<&'a str, &'a IriS>
}
fn split(str: &str) -> Option<(&str, &str)> {
str.rsplit_once(":")
}
impl <'a> PrefixMap<'a> {
pub fn new() -> PrefixMap<'a> {
PrefixMap::default()
}
pub fn insert(&mut self, alias: &'a str, iri: &'a IriS) {
self.map.insert(alias, iri);
}
pub fn find(&self, str: &str) -> Option<&IriS> {
let x = self.map.get(&str);
match x {
Some(&b) => {
let x = Some(b);
x
}
None => None
}
}
pub fn resolve(&self, str: &str) -> Result<Option<IriS>, IriError> {
match split(str) {
Some((alias, local_name)) => {
match self.find(alias) {
Some(iri) => {
let new_iri = iri.extend(local_name)?;
Ok(Some(new_iri))
},
None => {
let iri = IriS::from_str(str)?;
Ok(Some(iri))
}
}
},
None => {
let iri = IriS::from_str(str)?;
Ok(Some(iri))
}
}
}
}
impl <'a> fmt::Display for PrefixMap<'a> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (&alias, &iri) in self.map.iter().clone() {
writeln!(f,"{} {}", &alias, &iri)?
}
Ok(())
}
}
impl <'a> Default for PrefixMap<'a> {
fn default() -> PrefixMap<'a> {
PrefixMap { map: IndexMap::new() }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn split_ex_name() {
assert_eq!(split("ex:name"), Some(("ex", "name")))
}
#[test]
fn prefix_map1() {
let mut pm = PrefixMap::new();
let binding = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &binding);
let resolved = IriS::from_str("http://example.org/name").unwrap();
assert_eq!(pm.resolve("ex:name").unwrap().unwrap(), resolved);
}
#[test]
fn prefix_map_display() {
let mut pm = PrefixMap::new();
let ex_iri = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &ex_iri);
let ex_rdf = IriS::from_str("http://www.w3.org/1999/02/22-rdf-syntax-ns#").unwrap();
pm.insert("rdf", &ex_rdf);
assert_eq!(pm.to_string(),
"ex <http://example.org/>\nrdf <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n");
}
#[test]
fn prefix_map_resolve() {
let mut pm = PrefixMap::new();
let ex_iri = IriS::from_str("http://example.org/").unwrap();
pm.insert("ex", &ex_iri);
assert_eq!(pm.resolve(&"ex:pepe").unwrap(),
Some(IriS::from_str("http://example.org/pepe").unwrap()));
}
}