ndjson_stream/
as_bytes.rs

1//! This module defines the [AsBytes] with baseline implementations.
2
3use std::borrow::Cow;
4use std::rc::Rc;
5use std::sync::Arc;
6
7#[cfg(feature = "bytes")]
8use bytes::{Bytes, BytesMut};
9
10/// A trait for types which represent a contiguous block of bytes, such as `&[u8]` or `Vec<u8>`.
11pub trait AsBytes {
12
13    /// Gets a slice of the entire block of bytes contained in this instance.
14    fn as_bytes(&self) -> &[u8];
15}
16
17impl AsBytes for [u8] {
18    fn as_bytes(&self) -> &[u8] {
19        self
20    }
21}
22
23impl<const LEN: usize> AsBytes for [u8; LEN] {
24    fn as_bytes(&self) -> &[u8] {
25        self
26    }
27}
28
29impl AsBytes for Vec<u8> {
30    fn as_bytes(&self) -> &[u8] {
31        self
32    }
33}
34
35impl AsBytes for str {
36    fn as_bytes(&self) -> &[u8] {
37        str::as_bytes(self)
38    }
39}
40
41impl AsBytes for String {
42    fn as_bytes(&self) -> &[u8] {
43        self.as_str().as_bytes()
44    }
45}
46
47#[cfg(feature = "bytes")]
48#[cfg_attr(doc_cfg, doc(cfg(feature = "bytes")))]
49impl AsBytes for Bytes {
50    fn as_bytes(&self) -> &[u8] {
51        self.as_ref()
52    }
53}
54
55#[cfg(feature = "bytes")]
56#[cfg_attr(doc_cfg, doc(cfg(feature = "bytes")))]
57impl AsBytes for BytesMut {
58    fn as_bytes(&self) -> &[u8] {
59        self.as_ref()
60    }
61}
62
63impl<T: AsBytes + ?Sized> AsBytes for &T {
64    fn as_bytes(&self) -> &[u8] {
65        T::as_bytes(self)
66    }
67}
68
69impl<T: AsBytes + ?Sized> AsBytes for &mut T {
70    fn as_bytes(&self) -> &[u8] {
71        T::as_bytes(self)
72    }
73}
74
75impl<T: AsBytes + ?Sized> AsBytes for Box<T> {
76    fn as_bytes(&self) -> &[u8] {
77        self.as_ref().as_bytes()
78    }
79}
80
81impl<'cow, T: AsBytes + Clone + ?Sized> AsBytes for Cow<'cow, T> {
82    fn as_bytes(&self) -> &[u8] {
83        self.as_ref().as_bytes()
84    }
85}
86
87impl<T: AsBytes + ?Sized> AsBytes for Rc<T> {
88    fn as_bytes(&self) -> &[u8] {
89        self.as_ref().as_bytes()
90    }
91}
92
93impl<T: AsBytes + ?Sized> AsBytes for Arc<T> {
94    fn as_bytes(&self) -> &[u8] {
95        self.as_ref().as_bytes()
96    }
97}
98
99#[cfg(all(test, feature = "bytes"))]
100mod bytes_tests {
101
102    use bytes::Bytes;
103    use kernal::prelude::*;
104
105    use super::*;
106
107    #[test]
108    fn bytes_works() {
109        let bytes = Bytes::from(&[1, 2, 3][..]);
110
111        assert_that!(bytes.as_bytes()).contains_exactly_in_given_order([1, 2, 3]);
112    }
113
114    #[test]
115    fn bytes_mut_works() {
116        let bytes_mut = BytesMut::from(&[3, 2, 1][..]);
117
118        assert_that!(bytes_mut.as_bytes()).contains_exactly_in_given_order([3, 2, 1]);
119    }
120}