Skip to content

Commit

Permalink
Implement From for ByteArray, ByteBuf and Bytes
Browse files Browse the repository at this point in the history
Signed-off-by: 0xZensh <txr1883@gmail.com>
  • Loading branch information
zensh committed Jun 14, 2024
1 parent 1dd071d commit 303e938
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/bytearray.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,12 @@ impl<const N: usize> Debug for ByteArray<N> {
}
}

impl<const N: usize> Default for ByteArray<N> {
fn default() -> Self {
ByteArray { bytes: [0; N] }
}
}

impl<const N: usize> AsRef<[u8; N]> for ByteArray<N> {
fn as_ref(&self) -> &[u8; N] {
&self.bytes
Expand Down Expand Up @@ -112,6 +118,12 @@ impl<const N: usize> BorrowMut<Bytes> for ByteArray<N> {
}
}

impl<const N: usize> From<[u8; N]> for ByteArray<N> {
fn from(bytes: [u8; N]) -> Self {
ByteArray { bytes }
}
}

impl<Rhs, const N: usize> PartialEq<Rhs> for ByteArray<N>
where
Rhs: ?Sized + Borrow<[u8; N]>,
Expand Down
11 changes: 11 additions & 0 deletions src/bytebuf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,17 @@ impl BorrowMut<Bytes> for ByteBuf {
}
}

impl<T> From<T> for ByteBuf
where
T: Into<Vec<u8>>,
{
fn from(bytes: T) -> Self {
ByteBuf {
bytes: bytes.into(),
}
}
}

impl<Rhs> PartialEq<Rhs> for ByteBuf
where
Rhs: ?Sized + AsRef<[u8]>,
Expand Down
6 changes: 6 additions & 0 deletions src/bytes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,12 @@ impl DerefMut for Bytes {
}
}

impl<'a> From<&'a [u8]> for &'a Bytes {
fn from(bytes: &'a [u8]) -> Self {
Bytes::new(bytes)
}
}

#[cfg(any(feature = "std", feature = "alloc"))]
impl ToOwned for Bytes {
type Owned = ByteBuf;
Expand Down
52 changes: 52 additions & 0 deletions tests/test_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,55 @@ fn test() {
],
);
}

#[derive(Serialize, Deserialize, PartialEq, Debug, Default)]
struct TestFrom<'a> {
#[serde(borrow)]
bytes: &'a Bytes,
byte_array: ByteArray<4>,
byte_buf: ByteBuf,
}

#[test]
fn test_default() {
let mut test = TestFrom::default();

assert_tokens(
&test,
&[
Token::Struct {
name: "TestFrom",
len: 3,
},
Token::Str("bytes"),
Token::BorrowedBytes(b""),
Token::Str("byte_array"),
Token::Bytes(&[0; 4]),
Token::Str("byte_buf"),
Token::Bytes(b""),
Token::StructEnd,
],
);

let bytes = [255u8; 4];
test.byte_array = bytes.into();
test.bytes = bytes.as_slice().into();
test.byte_buf = bytes.into();

assert_tokens(
&test,
&[
Token::Struct {
name: "TestFrom",
len: 3,
},
Token::Str("bytes"),
Token::BorrowedBytes(b"\xff\xff\xff\xff"),
Token::Str("byte_array"),
Token::Bytes(&[255u8; 4]),
Token::Str("byte_buf"),
Token::Bytes(b"\xff\xff\xff\xff"),
Token::StructEnd,
],
);
}

0 comments on commit 303e938

Please sign in to comment.