Skip to main content

urid/
lib.rs

1//! Library for idiomatic URID support.
2//!
3//! In the world of [RDF](https://en.wikipedia.org/wiki/Resource_Description_Framework), resources are described using [URIs](https://en.wikipedia.org/wiki/Uniform_Resource_Identifier). In Rust, this concept can be adapted to describe types with URIs using the [`UriBound`](trait.UriBound.html) trait. Then, other crates might use these URIs to describe relationships between types or values using URIs.
4//!
5//! However, comparing URIs isn't necessarily fast. Therefore, another concept was introduced: The [URID](struct.URID.html). A URID is basically a `u32` which represents a URI. These URIDs are assigned by a [`Map`](trait.Map.html) and can be "dereferenced" by an [`Unmap`](trait.Unmap.html).
6//!
7//! This library also supports connecting URIDs to their `UriBound` via a generics argument. This can be used, for example, to request the URID of a certain bound as a parameter of a function. If someone would try to call this function with the wrong URID, the compiler will raise an error before the code is even compiled.
8//!
9//! This may seem a bit minor to you now, but the audio plugin framework [rust-lv2](https://github.com/RustAudio/rust-lv2) heavily relies on this crate for fast, portable and dynamic data identification and exchange.
10//!
11//! # Example
12//!
13//! ```
14//! use urid::*;
15//!
16//! // Some types with URIs. The attribute implements `UriBound` with the given URI.
17//! #[uri("urn:urid-example:my-struct-a")]
18//! struct MyStructA;
19//!
20//! #[uri("urn:urid-example:my-struct-b")]
21//! struct MyStructB;
22//!
23//! // A collection of URIDs that can be created by a mapper with one method call.
24//! #[derive(URIDCollection)]
25//! struct MyURIDCollection {
26//!     my_struct_a: URID<MyStructA>,
27//!     my_struct_b: URID<MyStructB>,
28//! }
29//!
30//! // A function that checks whether the unmapper behaves correctly.
31//! // Due to the type argument, it can not be misused.
32//! fn test_unmapper<M: Unmap, T: UriBound>(unmap: &M, urid: URID<T>) {
33//!     assert_eq!(T::uri(), unmap.unmap(urid).unwrap());
34//! }
35//!
36//! // Create a simple mapper. The `HashURIDMapper` is thread-safe and can map and unmap all URIs.
37//! let map = HashURIDMapper::new();
38//!
39//! // Get the URIDs of the structs. You can use the collection or retrieve individual URIDs.
40//! let urids: MyURIDCollection = map.populate_collection().unwrap();
41//! let urid_a: URID<MyStructA> = map.map_type().unwrap();
42//!
43//! // You can also retrieve the URID of a single URI without a binding to a type.
44//! let urid_b: URID = map.map_str("https://rustup.rs").unwrap();
45//!
46//! test_unmapper(&map, urids.my_struct_a);
47//! test_unmapper(&map, urids.my_struct_b);
48//! test_unmapper(&map, urid_a);
49//! ```
50use std::cmp::{Ordering, PartialEq, PartialOrd};
51use std::collections::HashMap;
52use std::convert::TryInto;
53use std::fmt;
54use std::hash::{Hash, Hasher};
55use std::marker::PhantomData;
56use std::num::NonZeroU32;
57use std::sync::Mutex;
58
59pub use urid_derive::*;
60
61/// Representation of a borrowed Uri.
62pub type Uri = ::std::ffi::CStr;
63/// Representation of an owned Uri.
64pub type UriBuf = ::std::ffi::CString;
65
66/// A trait for types that can be identified by a URI.
67///
68/// Every type that can be identified by a URI implements this trait. In most cases, you can use the `uri` attribute to implement `UriBound` safely and quickly:
69///
70/// ```
71/// use urid::*;
72///
73/// // Defining the struct
74/// #[uri("urn:urid-example:my-struct")]
75/// pub struct MyStruct {
76///     a: f32,
77/// }
78///
79/// // Retrieving the URI
80/// assert_eq!("urn:urid-example:my-struct", MyStruct::uri().to_str().unwrap());
81/// ```
82///
83/// However, in some cases, you need to implement `UriBound` manually, for example if the URI comes from a generated `sys` crate:
84///
85/// ```
86/// use urid::*;
87///
88/// // This URI is part of a generated `UriBound` crate:
89/// const A_FANCY_URI: &'static [u8] = b"urn:urid-example:fancy-uri\0";
90///
91/// // This struct is part of a safe wrapper crate:
92/// struct FancyStruct {
93///     _fancy_content: f32,
94/// }
95///
96/// unsafe impl UriBound for FancyStruct {
97///     const URI: &'static [u8] = A_FANCY_URI;
98/// }
99///
100/// assert_eq!("urn:urid-example:fancy-uri", FancyStruct::uri().to_str().unwrap())
101/// ```
102///
103/// # Unsafety
104///
105/// The [`URI`](#associatedconstant.URI) constant has to contain a null terminator (The `\0` character at the end), which is used by C programs to determine the end of the string. If you omit it, other parts of your program may violate memory access rules, which is considered undefined behaviour. Since this can not be statically checked by the compiler, this trait is unsafe to implement manually.
106pub unsafe trait UriBound {
107    /// The URI of the type, safed as a byte slice
108    ///
109    /// Currently, there is no way to express a `CStr` in a constant way. Therefore, the URI has to be stored as a null-terminated byte slice.
110    ///
111    /// The slice must be a valid URI and must have the null character, expressed as `\0`, at the end. Otherwise, other code might produce a segmentation fault or read a faulty URI while looking for the null character.
112    const URI: &'static [u8];
113
114    /// Construct a `CStr` reference to the URI.
115    ///
116    /// Assuming that [`URI`](#associatedconstant.URI) is correct, this method constructs a `CStr` reference from the byte slice referenced by `URI`.
117    fn uri() -> &'static Uri {
118        unsafe { Uri::from_bytes_with_nul_unchecked(Self::URI) }
119    }
120}
121
122/// Representation of a URI for fast comparisons.
123///
124/// A URID is basically a number which represents a URI, which makes the identification of other features faster and easier. The mapping of URIs to URIDs is handled by a something that implements the [`Map`](trait.Map.html) trait. A given URID can also be converted back to a URI with an implementation of the [`Unmap`](trait.Unmap.html) trait. However, these implementations should obviously be linked.
125///
126/// This struct has an optional type parameter `T` which defaults to `()`. In this case, the type can represent any URID at all, but if `T` is a `UriBound`, the instance of `URID<T>` can only describe the URID of the given bound. This makes creation easier and also turns it into an atomic [`URIDCollection`](trait.URIDCollection.html), which can be used to build bigger collections.
127#[repr(transparent)]
128pub struct URID<T = ()>(NonZeroU32, PhantomData<T>)
129where
130    T: ?Sized;
131
132/// A store of pre-mapped URIDs
133///
134/// This trait can be used to easily cache URIDs. The usual way of creating such a collection is to define a struct of `URID<T>`s, where `T` implements `UriBound`, and then using the derive macro to implement `URIDCollection` for it. Then, you can populate it with a map and access it any time, even in a real-time-sensitive context.
135///
136/// # Usage example:
137///
138///     # use urid::*;
139///     // Defining all URI bounds.
140///     #[uri("urn:my-type-a")]
141///     struct MyTypeA;
142///     
143///     #[uri("urn:my-type-b")]
144///     struct MyTypeB;
145///
146///     // Defining the collection.
147///     #[derive(URIDCollection)]
148///     struct MyCollection {
149///         my_type_a: URID<MyTypeA>,
150///         my_type_b: URID<MyTypeB>,
151///     }
152///
153///     // Creating a mapper and collecting URIDs.
154///     let map = HashURIDMapper::new();
155///     let collection = MyCollection::from_map(&map).unwrap();
156///
157///     // Asserting.
158///     assert_eq!(1, collection.my_type_a);
159///     assert_eq!(2, collection.my_type_b);
160pub trait URIDCollection: Sized {
161    /// Construct the collection from the mapper.
162    fn from_map<M: Map + ?Sized>(map: &M) -> Option<Self>;
163}
164
165impl URID<()> {
166    /// Creates a new URID from a raw number.
167    ///
168    /// URIDs may never be zero. If the given number is zero, `None` is returned.
169    #[inline]
170    pub fn new(raw_urid: u32) -> Option<Self> {
171        NonZeroU32::new(raw_urid).map(|inner| Self(inner, PhantomData))
172    }
173}
174
175impl<T: ?Sized> URID<T> {
176    /// Create a URID without checking for type or value validity.
177    ///
178    /// This value may only be a URID the mapper actually produced and that is recognised by a compatible unmapper. Therefore, it should only be used by [`Map::map_uri`](trait.Map.html#tymethod.map_uri) or [`Map::map_type`](trait.Map.html#method.map_type).
179    ///
180    /// # Safety
181    ///
182    /// A URID may not be 0 since this value is reserved for the `None` value of `Option<URID<T>>`, which therefore has the same size as a `URID<T>`. If `T` is also a URI bound, the URID may only be the one that is mapped to the bounded URI.
183    ///
184    /// Since these constraints aren't checked by this method, it is unsafe. Using this method is technically sound as long as `raw_urid` is not zero, but might still result in bad behaviour if its the wrong URID for the bound `T`.
185    pub unsafe fn new_unchecked(raw_urid: u32) -> Self {
186        Self(NonZeroU32::new_unchecked(raw_urid), PhantomData)
187    }
188
189    /// Return the raw URID number.
190    pub fn get(self) -> u32 {
191        self.0.get()
192    }
193
194    /// Transform the type-specific URID into a generalized one.
195    pub fn into_general(self) -> URID<()> {
196        unsafe { URID::new_unchecked(self.get()) }
197    }
198}
199
200impl<T: UriBound + ?Sized> URIDCollection for URID<T> {
201    fn from_map<M: Map + ?Sized>(map: &M) -> Option<Self> {
202        map.map_type()
203    }
204}
205
206impl<T: ?Sized> fmt::Debug for URID<T> {
207    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
208        self.0.fmt(f)
209    }
210}
211
212impl<T: ?Sized> Clone for URID<T> {
213    fn clone(&self) -> Self {
214        Self(self.0, PhantomData)
215    }
216}
217
218impl<T: ?Sized> Copy for URID<T> {}
219
220impl<T1: ?Sized, T2: ?Sized> PartialEq<URID<T1>> for URID<T2> {
221    fn eq(&self, other: &URID<T1>) -> bool {
222        self.0 == other.0
223    }
224}
225
226impl<T: ?Sized> PartialEq<u32> for URID<T> {
227    fn eq(&self, other: &u32) -> bool {
228        self.get() == *other
229    }
230}
231
232impl<T: ?Sized> PartialEq<URID<T>> for u32 {
233    fn eq(&self, other: &URID<T>) -> bool {
234        *self == other.get()
235    }
236}
237
238impl<T: ?Sized> Eq for URID<T> {}
239
240impl<T1: ?Sized, T2: ?Sized> PartialOrd<URID<T1>> for URID<T2> {
241    fn partial_cmp(&self, other: &URID<T1>) -> Option<Ordering> {
242        self.0.partial_cmp(&other.0)
243    }
244}
245
246impl<T: ?Sized> PartialOrd<u32> for URID<T> {
247    fn partial_cmp(&self, other: &u32) -> Option<Ordering> {
248        self.get().partial_cmp(other)
249    }
250}
251
252impl<T: ?Sized> PartialOrd<URID<T>> for u32 {
253    fn partial_cmp(&self, other: &URID<T>) -> Option<Ordering> {
254        self.partial_cmp(&other.get())
255    }
256}
257
258impl<T: ?Sized> Ord for URID<T> {
259    fn cmp(&self, other: &Self) -> Ordering {
260        self.0.cmp(&other.0)
261    }
262}
263
264impl<T: ?Sized> Hash for URID<T> {
265    fn hash<H: Hasher>(&self, state: &mut H) {
266        self.0.hash(state)
267    }
268}
269
270impl std::convert::TryFrom<u32> for URID {
271    type Error = ();
272
273    fn try_from(value: u32) -> Result<URID, ()> {
274        if value == 0 {
275            Err(())
276        } else {
277            Ok(unsafe { URID::new_unchecked(value) })
278        }
279    }
280}
281
282#[cfg(test)]
283mod tests {
284    use crate::URID;
285
286    #[test]
287    fn test_urid_size() {
288        use std::mem::size_of;
289
290        let size = size_of::<u32>();
291
292        assert_eq!(size, size_of::<URID>());
293        assert_eq!(size, size_of::<Option<URID>>());
294    }
295}
296
297/// A handle to map URIs to URIDs.
298pub trait Map {
299    /// Maps an URI to a `URID` that corresponds to it.
300    ///
301    /// If the URI has not been mapped before, a new URID will be assigned.
302    ///
303    /// # Errors
304    /// This method may return `None` in the exceptional case that an ID for that URI could not be
305    /// created for whatever reason.
306    /// However, implementations SHOULD NOT return `None` from this function in non-exceptional
307    /// circumstances (i.e. the URI map SHOULD be dynamic).
308    ///
309    /// # Realtime usage
310    /// This action may not be realtime-safe since it may involve locking mutexes or allocating dynamic memory. If you are working in a realtime environment, you should cache mapped URIDs in a [`URIDCollection`](trait.URIDCollection.html) and use it instead.
311    fn map_uri(&self, uri: &Uri) -> Option<URID>;
312
313    /// Map an URI, encoded as a `str` to a `URID` that corresponds to it.
314    ///
315    /// This function copies the string into a vector, adds a null terminator and calls [`map_uri`](#tymethod.map_uri) with it. Therefore, the rules of `map_uri` apply here too.
316    ///
317    /// # Additional Errors
318    /// This method has the same error cases as `map_uri`, but also returns `None` if the string isn't an ASCII string or if the string can not be converted to a `Uri`.
319    fn map_str(&self, uri: &str) -> Option<URID> {
320        if !uri.is_ascii() {
321            return None;
322        }
323        let mut bytes: Vec<u8> = uri.as_bytes().to_owned();
324        bytes.push(0);
325        self.map_uri(Uri::from_bytes_with_nul(bytes.as_ref()).ok()?)
326    }
327
328    /// Retrieve the URI of the bound and map it to a URID.
329    ///
330    /// The rules of [`map_uri`](#tymethod.map_uri) apply here too.
331    fn map_type<T: UriBound + ?Sized>(&self) -> Option<URID<T>> {
332        self.map_uri(T::uri())
333            .map(|urid| unsafe { URID::new_unchecked(urid.get()) })
334    }
335
336    /// Populate a URID collection.
337    ///
338    /// This is basically an alias for [`T::from_map(self)`](trait.URIDCollection.html#tymethod.from_map) that simplifies the derive macro for `URIDCollection`.
339    fn populate_collection<T: URIDCollection>(&self) -> Option<T> {
340        T::from_map(self)
341    }
342}
343
344/// A handle to map URIDs to URIs.
345pub trait Unmap {
346    /// Get the URI of a previously mapped URID.
347    ///
348    /// This method may return `None` if the given `urid` is not mapped to URI yet.
349    ///
350    /// # Realtime usage
351    /// This action may not be realtime-safe since it may involve locking mutexes or allocating dynamic memory. If you are working in a realtime environment, you should cache mapped URIDs in a [`URIDCollection`](trait.URIDCollection.html) and use it instead.
352    fn unmap<T: ?Sized>(&self, urid: URID<T>) -> Option<&Uri>;
353}
354
355/// A simple URI → URID mapper, backed by a standard `HashMap` and a `Mutex` for multi-thread
356/// access.
357#[derive(Default)]
358pub struct HashURIDMapper(Mutex<HashMap<UriBuf, URID>>);
359
360impl Map for HashURIDMapper {
361    fn map_uri(&self, uri: &Uri) -> Option<URID<()>> {
362        let mut map = self.0.lock().ok()?; // Fail if the Mutex got poisoned
363        match map.get(uri) {
364            Some(urid) => Some(*urid),
365            None => {
366                let map_length: u32 = map.len().try_into().ok()?; // Fail if there are more items into the HashMap than an u32 can hold
367                let next_urid = map_length.checked_add(1)?; // Fail on overflow when adding 1 for the next URID
368
369                // This is safe, because we just added 1 to the length and checked for overflow, therefore the number can never be 0.
370                let next_urid = unsafe { URID::new_unchecked(next_urid) };
371                map.insert(uri.into(), next_urid);
372                Some(next_urid)
373            }
374        }
375    }
376}
377
378impl Unmap for HashURIDMapper {
379    fn unmap<T: ?Sized>(&self, urid: URID<T>) -> Option<&Uri> {
380        let map = self.0.lock().ok()?;
381        for (uri, contained_urid) in map.iter() {
382            if *contained_urid == urid {
383                // Here we jump through some hoops to return a reference that bypasses the mutex.
384                // This is safe because the only way this reference might become invalid is if an
385                // entry gets overwritten, which is not something that we allow through this
386                // interface.
387                return Some(unsafe {
388                    let bytes = uri.as_bytes_with_nul();
389                    Uri::from_bytes_with_nul_unchecked(std::slice::from_raw_parts(
390                        bytes.as_ptr(),
391                        bytes.len(),
392                    ))
393                });
394            }
395        }
396
397        None
398    }
399}
400
401impl HashURIDMapper {
402    /// Create a new URID map store.
403    pub fn new() -> Self {
404        Default::default()
405    }
406}