ssi_dids_core/did/url/
primary.rs

1use std::{borrow::Borrow, ops::Deref};
2
3use crate::{DIDURLBuf, Fragment, DIDURL};
4
5/// DID URL without fragment.
6#[repr(transparent)]
7pub struct PrimaryDIDURL([u8]);
8
9impl PrimaryDIDURL {
10    /// Creates a new primary DID URL without checking the data.
11    ///
12    /// # Safety
13    ///
14    /// The input `data` must be a valid primary DID URL.
15    pub unsafe fn new_unchecked(data: &[u8]) -> &Self {
16        std::mem::transmute(data)
17    }
18
19    pub fn as_did_url(&self) -> &DIDURL {
20        unsafe { DIDURL::new_unchecked(&self.0) }
21    }
22}
23
24impl Deref for PrimaryDIDURL {
25    type Target = DIDURL;
26
27    fn deref(&self) -> &Self::Target {
28        self.as_did_url()
29    }
30}
31
32impl ToOwned for PrimaryDIDURL {
33    type Owned = PrimaryDIDURLBuf;
34
35    fn to_owned(&self) -> Self::Owned {
36        unsafe { PrimaryDIDURLBuf::new_unchecked(self.0.to_vec()) }
37    }
38}
39
40impl<'a> From<&'a PrimaryDIDURL> for PrimaryDIDURLBuf {
41    fn from(value: &'a PrimaryDIDURL) -> Self {
42        value.to_owned()
43    }
44}
45
46/// DID URL without fragment.
47pub struct PrimaryDIDURLBuf(Vec<u8>);
48
49impl PrimaryDIDURLBuf {
50    /// Creates a new primary DID URL without checking the data.
51    ///
52    /// # Safety
53    ///
54    /// The input `data` must be a valid primary DID URL.
55    pub unsafe fn new_unchecked(data: Vec<u8>) -> Self {
56        Self(data)
57    }
58
59    pub fn as_primary_did_url(&self) -> &PrimaryDIDURL {
60        unsafe { PrimaryDIDURL::new_unchecked(&self.0) }
61    }
62
63    /// Append a [fragment](https://www.w3.org/TR/did-core/#fragment) to construct a DID URL.
64    ///
65    /// The opposite of [DIDURL::without_fragment].
66    pub fn with_fragment(self, fragment: &Fragment) -> DIDURLBuf {
67        let mut result = self.0;
68        result.push(b'#');
69        result.extend(fragment.as_bytes());
70        unsafe { DIDURLBuf::new_unchecked(result) }
71    }
72
73    pub fn into_did_url(self) -> DIDURLBuf {
74        unsafe { DIDURLBuf::new_unchecked(self.0) }
75    }
76}
77
78impl Deref for PrimaryDIDURLBuf {
79    type Target = PrimaryDIDURL;
80
81    fn deref(&self) -> &Self::Target {
82        self.as_primary_did_url()
83    }
84}
85
86impl Borrow<PrimaryDIDURL> for PrimaryDIDURLBuf {
87    fn borrow(&self) -> &PrimaryDIDURL {
88        self.as_primary_did_url()
89    }
90}