Skip to main content

moq_net/model/
bytes.rs

1use bytes::{Bytes, BytesMut};
2
3/// Converts borrowed or owned byte buffers into [`Bytes`].
4///
5/// Owned buffers keep their allocation when possible. Borrowed buffers copy into
6/// a new [`Bytes`] value.
7pub trait IntoBytes: AsRef<[u8]> {
8	/// Convert this buffer into owned bytes.
9	fn into_bytes(self) -> Bytes;
10}
11
12impl IntoBytes for Bytes {
13	fn into_bytes(self) -> Bytes {
14		self
15	}
16}
17
18impl IntoBytes for &Bytes {
19	fn into_bytes(self) -> Bytes {
20		self.clone()
21	}
22}
23
24impl IntoBytes for BytesMut {
25	fn into_bytes(self) -> Bytes {
26		self.freeze()
27	}
28}
29
30impl IntoBytes for &BytesMut {
31	fn into_bytes(self) -> Bytes {
32		Bytes::copy_from_slice(self.as_ref())
33	}
34}
35
36impl IntoBytes for Vec<u8> {
37	fn into_bytes(self) -> Bytes {
38		Bytes::from(self)
39	}
40}
41
42impl IntoBytes for &Vec<u8> {
43	fn into_bytes(self) -> Bytes {
44		Bytes::copy_from_slice(self)
45	}
46}
47
48impl IntoBytes for String {
49	fn into_bytes(self) -> Bytes {
50		Bytes::from(self)
51	}
52}
53
54impl IntoBytes for &String {
55	fn into_bytes(self) -> Bytes {
56		Bytes::copy_from_slice(self.as_bytes())
57	}
58}
59
60impl IntoBytes for &str {
61	fn into_bytes(self) -> Bytes {
62		Bytes::copy_from_slice(self.as_bytes())
63	}
64}
65
66impl IntoBytes for &[u8] {
67	fn into_bytes(self) -> Bytes {
68		Bytes::copy_from_slice(self)
69	}
70}
71
72impl<const N: usize> IntoBytes for &[u8; N] {
73	fn into_bytes(self) -> Bytes {
74		Bytes::copy_from_slice(self)
75	}
76}