Coverage Report

Created: 2024-11-30 06:06

/rust/registry/src/index.crates.io-6f17d22bba15001f/der-0.7.9/src/bytes_owned.rs
Line
Count
Source (jump to first uncovered line)
1
//! Common handling for types backed by byte allocation with enforcement of a
2
//! library-level length limitation i.e. `Length::max()`.
3
4
use crate::{
5
    referenced::OwnedToRef, BytesRef, DecodeValue, DerOrd, EncodeValue, Error, Header, Length,
6
    Reader, Result, StrRef, Writer,
7
};
8
use alloc::{boxed::Box, vec::Vec};
9
use core::cmp::Ordering;
10
11
/// Byte slice newtype which respects the `Length::max()` limit.
12
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
13
pub(crate) struct BytesOwned {
14
    /// Precomputed `Length` (avoids possible panicking conversions)
15
    length: Length,
16
17
    /// Inner value
18
    inner: Box<[u8]>,
19
}
20
21
impl BytesOwned {
22
    /// Create a new [`BytesOwned`], ensuring that the provided `slice` value
23
    /// is shorter than `Length::max()`.
24
0
    pub fn new(data: impl Into<Box<[u8]>>) -> Result<Self> {
25
0
        let inner: Box<[u8]> = data.into();
26
0
27
0
        Ok(Self {
28
0
            length: Length::try_from(inner.len())?,
29
0
            inner,
30
        })
31
0
    }
Unexecuted instantiation: <der::bytes_owned::BytesOwned>::new::<alloc::vec::Vec<u8>>
Unexecuted instantiation: <der::bytes_owned::BytesOwned>::new::<alloc::boxed::Box<[u8]>>
Unexecuted instantiation: <der::bytes_owned::BytesOwned>::new::<&[u8]>
32
33
    /// Borrow the inner byte slice
34
0
    pub fn as_slice(&self) -> &[u8] {
35
0
        &self.inner
36
0
    }
37
38
    /// Get the [`Length`] of this [`BytesRef`]
39
0
    pub fn len(&self) -> Length {
40
0
        self.length
41
0
    }
42
43
    /// Is this [`BytesOwned`] empty?
44
0
    pub fn is_empty(&self) -> bool {
45
0
        self.len() == Length::ZERO
46
0
    }
47
}
48
49
impl AsRef<[u8]> for BytesOwned {
50
0
    fn as_ref(&self) -> &[u8] {
51
0
        self.as_slice()
52
0
    }
53
}
54
55
impl<'a> DecodeValue<'a> for BytesOwned {
56
0
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
57
0
        reader.read_vec(header.length).and_then(Self::new)
58
0
    }
59
}
60
61
impl EncodeValue for BytesOwned {
62
0
    fn value_len(&self) -> Result<Length> {
63
0
        Ok(self.length)
64
0
    }
65
66
0
    fn encode_value(&self, writer: &mut impl Writer) -> Result<()> {
67
0
        writer.write(self.as_ref())
68
0
    }
69
}
70
71
impl Default for BytesOwned {
72
0
    fn default() -> Self {
73
0
        Self {
74
0
            length: Length::ZERO,
75
0
            inner: Box::new([]),
76
0
        }
77
0
    }
78
}
79
80
impl DerOrd for BytesOwned {
81
0
    fn der_cmp(&self, other: &Self) -> Result<Ordering> {
82
0
        Ok(self.as_slice().cmp(other.as_slice()))
83
0
    }
84
}
85
86
impl From<BytesOwned> for Box<[u8]> {
87
0
    fn from(bytes: BytesOwned) -> Box<[u8]> {
88
0
        bytes.inner
89
0
    }
90
}
91
92
impl From<StrRef<'_>> for BytesOwned {
93
0
    fn from(s: StrRef<'_>) -> BytesOwned {
94
0
        let bytes = s.as_bytes();
95
0
        debug_assert_eq!(bytes.len(), usize::try_from(s.length).expect("overflow"));
96
97
0
        BytesOwned {
98
0
            inner: Box::from(bytes),
99
0
            length: s.length,
100
0
        }
101
0
    }
102
}
103
104
impl OwnedToRef for BytesOwned {
105
    type Borrowed<'a> = BytesRef<'a>;
106
0
    fn owned_to_ref(&self) -> Self::Borrowed<'_> {
107
0
        BytesRef {
108
0
            length: self.length,
109
0
            inner: self.inner.as_ref(),
110
0
        }
111
0
    }
112
}
113
114
impl From<BytesRef<'_>> for BytesOwned {
115
0
    fn from(s: BytesRef<'_>) -> BytesOwned {
116
0
        BytesOwned {
117
0
            length: s.length,
118
0
            inner: Box::from(s.inner),
119
0
        }
120
0
    }
121
}
122
123
impl TryFrom<&[u8]> for BytesOwned {
124
    type Error = Error;
125
126
0
    fn try_from(bytes: &[u8]) -> Result<Self> {
127
0
        Self::new(bytes)
128
0
    }
129
}
130
131
impl TryFrom<Box<[u8]>> for BytesOwned {
132
    type Error = Error;
133
134
0
    fn try_from(bytes: Box<[u8]>) -> Result<Self> {
135
0
        Self::new(bytes)
136
0
    }
137
}
138
139
impl TryFrom<Vec<u8>> for BytesOwned {
140
    type Error = Error;
141
142
0
    fn try_from(bytes: Vec<u8>) -> Result<Self> {
143
0
        Self::new(bytes)
144
0
    }
145
}
146
147
// Implement by hand because the derive would create invalid values.
148
// Make sure the length and the inner.len matches.
149
#[cfg(feature = "arbitrary")]
150
impl<'a> arbitrary::Arbitrary<'a> for BytesOwned {
151
    fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
152
        let length = u.arbitrary()?;
153
        Ok(Self {
154
            length,
155
            inner: Box::from(u.bytes(u32::from(length) as usize)?),
156
        })
157
    }
158
159
    fn size_hint(depth: usize) -> (usize, Option<usize>) {
160
        arbitrary::size_hint::and(Length::size_hint(depth), (0, None))
161
    }
162
}