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
use std::{borrow::Borrow, ops::Deref};

use crate::{DIDURLBuf, Fragment, DIDURL};

/// DID URL without fragment.
#[repr(transparent)]
pub struct PrimaryDIDURL([u8]);

impl PrimaryDIDURL {
    /// Creates a new primary DID URL without checking the data.
    ///
    /// # Safety
    ///
    /// The input `data` must be a valid primary DID URL.
    pub unsafe fn new_unchecked(data: &[u8]) -> &Self {
        std::mem::transmute(data)
    }

    pub fn as_did_url(&self) -> &DIDURL {
        unsafe { DIDURL::new_unchecked(&self.0) }
    }
}

impl Deref for PrimaryDIDURL {
    type Target = DIDURL;

    fn deref(&self) -> &Self::Target {
        self.as_did_url()
    }
}

impl ToOwned for PrimaryDIDURL {
    type Owned = PrimaryDIDURLBuf;

    fn to_owned(&self) -> Self::Owned {
        unsafe { PrimaryDIDURLBuf::new_unchecked(self.0.to_vec()) }
    }
}

impl<'a> From<&'a PrimaryDIDURL> for PrimaryDIDURLBuf {
    fn from(value: &'a PrimaryDIDURL) -> Self {
        value.to_owned()
    }
}

/// DID URL without fragment.
pub struct PrimaryDIDURLBuf(Vec<u8>);

impl PrimaryDIDURLBuf {
    /// Creates a new primary DID URL without checking the data.
    ///
    /// # Safety
    ///
    /// The input `data` must be a valid primary DID URL.
    pub unsafe fn new_unchecked(data: Vec<u8>) -> Self {
        Self(data)
    }

    pub fn as_primary_did_url(&self) -> &PrimaryDIDURL {
        unsafe { PrimaryDIDURL::new_unchecked(&self.0) }
    }

    /// Append a [fragment](https://www.w3.org/TR/did-core/#fragment) to construct a DID URL.
    ///
    /// The opposite of [DIDURL::without_fragment].
    pub fn with_fragment(self, fragment: &Fragment) -> DIDURLBuf {
        let mut result = self.0;
        result.push(b'#');
        result.extend(fragment.as_bytes());
        unsafe { DIDURLBuf::new_unchecked(result) }
    }

    pub fn into_did_url(self) -> DIDURLBuf {
        unsafe { DIDURLBuf::new_unchecked(self.0) }
    }
}

impl Deref for PrimaryDIDURLBuf {
    type Target = PrimaryDIDURL;

    fn deref(&self) -> &Self::Target {
        self.as_primary_did_url()
    }
}

impl Borrow<PrimaryDIDURL> for PrimaryDIDURLBuf {
    fn borrow(&self) -> &PrimaryDIDURL {
        self.as_primary_did_url()
    }
}