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
//! Code for dealing with namespaces in RDF files.

use std::slice::Iter;

/// Namespaces object maps prefixes to namespaces.
#[derive(Clone)]
pub struct Namespaces {
    namespaces: Vec<Namespace>,
}

impl Namespaces {
    /// Create a new Namespaces struct.
    pub fn new() -> Namespaces {
        Namespaces {
            namespaces: Vec::new(),
        }
    }
    /// Append a new mapping from prefix to namespace.
    pub fn set(&mut self, prefix: &[u8], namespace: &str) {
        if let Some(ns) = self.namespaces.iter_mut().find(|ns| ns.prefix == prefix) {
            ns.namespace.clear();
            ns.namespace.push_str(namespace);
            return;
        }
        self.namespaces.push(Namespace {
            namespace: String::from(namespace),
            prefix: Vec::from(prefix),
        });
    }
    /// Append a new mapping from prefix to namespace.
    pub fn insert(&mut self, prefix: &[u8], namespace: String) {
        if let Some(ns) = self.namespaces.iter_mut().find(|ns| ns.prefix == prefix) {
            ns.namespace = namespace;
            return;
        }
        self.namespaces.push(Namespace {
            namespace,
            prefix: Vec::from(prefix),
        });
    }
    /// Find the first prefix in this Namespaces that matches the given string.
    ///
    /// The prefix is returned and the remainder of the string is also also returned.
    pub fn find_prefix<'a>(&self, iri: &'a str) -> Option<(&[u8], &'a str)> {
        for ns in &self.namespaces {
            if iri.starts_with(&ns.namespace) {
                return Some((ns.prefix.as_slice(), &iri[ns.namespace.len()..]));
            }
        }
        None
    }
    /// Find the namespace for the given prefix.
    pub fn find_namespace(&self, prefix: &[u8]) -> Option<&str> {
        for ns in &self.namespaces {
            if ns.prefix == prefix {
                return Some(ns.namespace.as_str());
            }
        }
        None
    }
    /// Iterator overall prefixes and namespaces.
    pub fn iter(&self) -> Iter<Namespace> {
        self.namespaces.iter()
    }
}

impl Default for Namespaces {
    fn default() -> Namespaces {
        Namespaces::new()
    }
}

/// An entry in Namespaces.
#[derive(Clone)]
pub struct Namespace {
    namespace: String,
    prefix: Vec<u8>,
}

impl Namespace {
    /// Get the namespace.
    pub fn namespace(&self) -> &String {
        &self.namespace
    }
    /// Get the prefix.
    pub fn prefix(&self) -> &[u8] {
        self.prefix.as_slice()
    }
}