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 pub(crate) fn new_owned(
47 bytes: alloc::boxed::Box<[u8]>,
48 ) -> CowBytes<'static> {
49 CowBytes(Imp::Owned(bytes))
50 }
51
52 #[inline(always)]
55 pub(crate) fn as_slice(&self) -> &[u8] {
56 self.0.as_slice()
57 }
58
59 #[cfg(feature = "alloc")]
64 #[inline(always)]
65 pub(crate) fn into_owned(self) -> CowBytes<'static> {
66 match self.0 {
67 Imp::Borrowed(b) => {
68 CowBytes::new_owned(alloc::boxed::Box::from(b))
69 }
70 Imp::Owned(b) => CowBytes::new_owned(b),
71 }
72 }
73}
74
75impl<'a> Imp<'a> {
76 #[inline(always)]
77 pub fn new(bytes: &'a [u8]) -> Imp<'a> {
78 #[cfg(feature = "alloc")]
79 {
80 Imp::Borrowed(bytes)
81 }
82 #[cfg(not(feature = "alloc"))]
83 {
84 Imp(bytes)
85 }
86 }
87
88 #[cfg(feature = "alloc")]
89 #[inline(always)]
90 pub fn as_slice(&self) -> &[u8] {
91 #[cfg(feature = "alloc")]
92 {
93 match self {
94 Imp::Owned(ref x) => x,
95 Imp::Borrowed(x) => x,
96 }
97 }
98 #[cfg(not(feature = "alloc"))]
99 {
100 self.0
101 }
102 }
103
104 #[cfg(not(feature = "alloc"))]
105 #[inline(always)]
106 pub fn as_slice(&self) -> &[u8] {
107 self.0
108 }
109}