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
use crate::{ByteSlice, DecodeValue, Decoder, EncodeValue, Encoder, Length, Result};
use core::str;
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub(crate) struct StrSlice<'a> {
pub(crate) inner: &'a str,
pub(crate) length: Length,
}
impl<'a> StrSlice<'a> {
pub fn new(s: &'a str) -> Result<Self> {
Ok(Self {
inner: s,
length: Length::try_from(s.as_bytes().len())?,
})
}
pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
Self::new(str::from_utf8(bytes)?)
}
pub fn as_str(&self) -> &'a str {
self.inner
}
pub fn as_bytes(&self) -> &'a [u8] {
self.inner.as_bytes()
}
pub fn len(self) -> Length {
self.length
}
pub fn is_empty(self) -> bool {
self.len() == Length::ZERO
}
}
impl AsRef<str> for StrSlice<'_> {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for StrSlice<'_> {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}
impl<'a> DecodeValue<'a> for StrSlice<'a> {
fn decode_value(decoder: &mut Decoder<'a>, length: Length) -> Result<Self> {
Self::from_bytes(ByteSlice::decode_value(decoder, length)?.as_bytes())
}
}
impl<'a> EncodeValue for StrSlice<'a> {
fn value_len(&self) -> Result<Length> {
Ok(self.length)
}
fn encode_value(&self, encoder: &mut Encoder<'_>) -> Result<()> {
encoder.bytes(self.as_ref())
}
}