Coverage Report

Created: 2025-07-18 06:08

/rust/registry/src/index.crates.io-6f17d22bba15001f/der-0.7.10/src/str_ref.rs
Line
Count
Source (jump to first uncovered line)
1
//! Common handling for types backed by `str` slices with enforcement of a
2
//! library-level length limitation i.e. `Length::max()`.
3
4
use crate::{BytesRef, DecodeValue, EncodeValue, Header, Length, Reader, Result, Writer};
5
use core::str;
6
7
/// String slice newtype which respects the [`Length::max`] limit.
8
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
9
pub struct StrRef<'a> {
10
    /// Inner value
11
    pub(crate) inner: &'a str,
12
13
    /// Precomputed `Length` (avoids possible panicking conversions)
14
    pub(crate) length: Length,
15
}
16
17
impl<'a> StrRef<'a> {
18
    /// Create a new [`StrRef`], ensuring that the byte representation of
19
    /// the provided `str` value is shorter than `Length::max()`.
20
0
    pub fn new(s: &'a str) -> Result<Self> {
21
0
        Ok(Self {
22
0
            inner: s,
23
0
            length: Length::try_from(s.as_bytes().len())?,
24
        })
25
0
    }
26
27
    /// Parse a [`StrRef`] from UTF-8 encoded bytes.
28
0
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
29
0
        Self::new(str::from_utf8(bytes)?)
30
0
    }
31
32
    /// Borrow the inner `str`
33
0
    pub fn as_str(&self) -> &'a str {
34
0
        self.inner
35
0
    }
36
37
    /// Borrow the inner byte slice
38
0
    pub fn as_bytes(&self) -> &'a [u8] {
39
0
        self.inner.as_bytes()
40
0
    }
41
42
    /// Get the [`Length`] of this [`StrRef`]
43
0
    pub fn len(self) -> Length {
44
0
        self.length
45
0
    }
46
47
    /// Is this [`StrRef`] empty?
48
0
    pub fn is_empty(self) -> bool {
49
0
        self.len() == Length::ZERO
50
0
    }
51
}
52
53
impl AsRef<str> for StrRef<'_> {
54
0
    fn as_ref(&self) -> &str {
55
0
        self.as_str()
56
0
    }
57
}
58
59
impl AsRef<[u8]> for StrRef<'_> {
60
0
    fn as_ref(&self) -> &[u8] {
61
0
        self.as_bytes()
62
0
    }
63
}
64
65
impl<'a> DecodeValue<'a> for StrRef<'a> {
66
0
    fn decode_value<R: Reader<'a>>(reader: &mut R, header: Header) -> Result<Self> {
67
0
        Self::from_bytes(BytesRef::decode_value(reader, header)?.as_slice())
68
0
    }
69
}
70
71
impl<'a> EncodeValue for StrRef<'a> {
72
0
    fn value_len(&self) -> Result<Length> {
73
0
        Ok(self.length)
74
0
    }
75
76
0
    fn encode_value(&self, writer: &mut impl Writer) -> Result<()> {
77
0
        writer.write(self.as_ref())
78
0
    }
79
}
80
81
#[cfg(feature = "alloc")]
82
mod allocating {
83
    use super::StrRef;
84
    use crate::{referenced::RefToOwned, StrOwned};
85
86
    impl<'a> RefToOwned<'a> for StrRef<'a> {
87
        type Owned = StrOwned;
88
0
        fn ref_to_owned(&self) -> Self::Owned {
89
0
            StrOwned::from(*self)
90
0
        }
91
    }
92
}