sophia_api/ns/_namespace.rs
1use super::*;
2
3#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
4/// A custom namespace.
5///
6/// The [`get`](Namespace::get) method can be used to create a new IRI by concatenating a suffix to this namespace's IRI.
7pub struct Namespace<T: Borrow<str>>(IriRef<T>);
8
9impl<T: Borrow<str>> Namespace<T> {
10 /// Build a custom namespace based on the given IRI.
11 ///
12 /// `iri` must be a valid IRI, otherwise this constructor returns an error.
13 pub fn new(iri: T) -> Result<Self, InvalidIri> {
14 IriRef::new(iri).map(Namespace)
15 }
16
17 /// Build a custom namespace based on the given IRI,
18 /// without checking that it is valid.
19 /// If it is not, it may result in undefined behaviour.
20 pub fn new_unchecked(iri: T) -> Self {
21 Namespace(IriRef::new_unchecked(iri))
22 }
23
24 /// Build an IRI by appending `suffix` to this namespace.
25 ///
26 /// Return an error if the concatenation produces an invalid IRI.
27 pub fn get<'s>(&'s self, suffix: &'s str) -> Result<NsTerm<'s>, InvalidIri> {
28 let ns_term = NsTerm {
29 ns: self.0.as_ref(),
30 suffix,
31 };
32 IriRef::new(ns_term.to_string())?;
33 Ok(ns_term)
34 }
35
36 /// Build an IRI by appending `suffix` to this namespace,
37 /// without checking that the resulting IRI is valid.
38 /// If it is not, it may result in undefined behaviour.
39 pub fn get_unchecked<'s>(&'s self, suffix: &'s str) -> NsTerm<'s> {
40 NsTerm {
41 ns: self.0.as_ref(),
42 suffix,
43 }
44 }
45
46 /// Consume this Namespace and return the inner [`IriRef`].
47 pub fn inner(self) -> IriRef<T> {
48 self.0
49 }
50}
51
52impl Namespace<&'static str> {
53 /// `const` constructor for [`Namespace`]
54 ///
55 /// # Precondition
56 /// `iri` must be a valid IRI reference (possibly relative),
57 /// otherwise undefined behaviour may occur.
58 pub const fn new_unchecked_const(iri: &'static str) -> Self {
59 Namespace(IriRef::new_unchecked_const(iri))
60 }
61}
62
63impl<T: Borrow<str>> From<IriRef<T>> for Namespace<T> {
64 fn from(other: IriRef<T>) -> Self {
65 Namespace(other)
66 }
67}
68
69impl<T: Borrow<str>> std::ops::Deref for Namespace<T> {
70 type Target = IriRef<T>;
71
72 fn deref(&self) -> &IriRef<T> {
73 &self.0
74 }
75}