Skip to main content

sark_json/
view.rs

1use std::borrow::Cow;
2
3use o3::buffer::Shared;
4
5/// JSON bytes that borrow the request when possible and own only decoded escapes.
6#[repr(transparent)]
7#[derive(Clone)]
8pub struct JsonBytes<'req>(Cow<'req, [u8]>);
9
10impl<'req> JsonBytes<'req> {
11    #[must_use]
12    pub fn borrowed(bytes: &'req [u8]) -> Self {
13        Self(Cow::Borrowed(bytes))
14    }
15
16    #[must_use]
17    pub fn owned(bytes: Vec<u8>) -> Self {
18        Self(Cow::Owned(bytes))
19    }
20
21    pub fn as_slice(&self) -> &[u8] {
22        self.0.as_ref()
23    }
24
25    pub fn len(&self) -> usize {
26        self.as_slice().len()
27    }
28
29    pub fn is_empty(&self) -> bool {
30        self.as_slice().is_empty()
31    }
32
33    #[must_use]
34    pub fn into_shared(self) -> Shared {
35        match self.0 {
36            Cow::Borrowed(bytes) => Shared::copy_from_slice(bytes),
37            Cow::Owned(bytes) => Shared::from(bytes),
38        }
39    }
40}
41
42impl AsRef<[u8]> for JsonBytes<'_> {
43    fn as_ref(&self) -> &[u8] {
44        self.as_slice()
45    }
46}