1use core::ops;
2
3#[derive(Clone, Debug)]
11pub struct CowBytes<'a>(Imp<'a>);
12
13#[cfg(feature = "alloc")]
17#[derive(Clone, Debug)]
18enum Imp<'a> {
19 Borrowed(&'a [u8]),
20 Owned(alloc::boxed::Box<[u8]>),
21}
22
23#[cfg(not(feature = "alloc"))]
24#[derive(Clone, Debug)]
25struct Imp<'a>(&'a [u8]);
26
27impl<'a> ops::Deref for CowBytes<'a> {
28 type Target = [u8];
29
30 #[inline(always)]
31 fn deref(&self) -> &[u8] {
32 self.as_slice()
33 }
34}
35
36impl<'a> CowBytes<'a> {
37 #[inline(always)]
39 pub(crate) fn new<B: ?Sized + AsRef<[u8]>>(bytes: &'a B) -> CowBytes<'a> {
40 CowBytes(Imp::new(bytes.as_ref()))
41 }
42
43 #[cfg(feature = "alloc")]
45 #[inline(always)]
46 fn new_owned(bytes: alloc::boxed::Box<[u8]>) -> CowBytes<'static> {
47 CowBytes(Imp::Owned(bytes))
48 }
49
50 #[inline(always)]
53 pub(crate) fn as_slice(&self) -> &[u8] {
54 self.0.as_slice()
55 }
56
57 #[cfg(feature = "alloc")]
62 #[inline(always)]
63 pub(crate) fn into_owned(self) -> CowBytes<'static> {
64 match self.0 {
65 Imp::Borrowed(b) => {
66 CowBytes::new_owned(alloc::boxed::Box::from(b))
67 }
68 Imp::Owned(b) => CowBytes::new_owned(b),
69 }
70 }
71}
72
73impl<'a> Imp<'a> {
74 #[inline(always)]
75 pub fn new(bytes: &'a [u8]) -> Imp<'a> {
76 #[cfg(feature = "alloc")]
77 {
78 Imp::Borrowed(bytes)
79 }
80 #[cfg(not(feature = "alloc"))]
81 {
82 Imp(bytes)
83 }
84 }
85
86 #[cfg(feature = "alloc")]
87 #[inline(always)]
88 pub fn as_slice(&self) -> &[u8] {
89 #[cfg(feature = "alloc")]
90 {
91 match self {
92 Imp::Owned(ref x) => x,
93 Imp::Borrowed(x) => x,
94 }
95 }
96 #[cfg(not(feature = "alloc"))]
97 {
98 self.0
99 }
100 }
101
102 #[cfg(not(feature = "alloc"))]
103 #[inline(always)]
104 pub fn as_slice(&self) -> &[u8] {
105 self.0
106 }
107}