diff --git a/src/lib.rs b/src/lib.rs index e76c03d..c796d71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,15 +32,15 @@ pub type Bytes16 = Bytes<16>; pub type Bytes32 = Bytes<32>; pub type Bytes64 = Bytes<64>; -impl From> for Bytes { - fn from(vec: Vec) -> Self { - Self { bytes: vec } +impl From> for Bytes { + fn from(vec: Vec) -> Self { + Bytes { bytes: vec }.increase_capacity() } } -impl From> for Vec { - fn from(value: Bytes) -> Self { - value.bytes +impl From> for Vec { + fn from(value: Bytes) -> Self { + value.increase_capacity().bytes } } @@ -56,7 +56,7 @@ impl TryFrom<&[u8]> for Bytes { impl Bytes { /// Construct a new, empty `Bytes`. pub fn new() -> Self { - Bytes::from(Vec::new()) + Self { bytes: Vec::new() } } pub fn as_ptr(&self) -> *const u8 { @@ -315,7 +315,7 @@ impl Bytes { let mut bytes = Vec::new(); // bytes has length 0 and capacity M, self has length N, N <= M, so this can never panic bytes.extend_from_slice(self.as_slice()).unwrap(); - bytes.into() + Bytes { bytes } } } @@ -364,12 +364,12 @@ impl AssertLessThanEq { /// let bytes: Bytes<3> = Bytes::from(&[0, 1, 2, 3]); // does not compile /// ``` impl From<&[u8; M]> for Bytes { - fn from(bytes: &[u8; M]) -> Self { + fn from(data: &[u8; M]) -> Self { let () = AssertLessThanEq::::ASSERT; - let mut vec = Vec::new(); + let mut bytes = Vec::new(); // vec has length 0 and capacity N, bytes has length M, M <= N, so this can never panic - vec.extend_from_slice(bytes).unwrap(); - vec.into() + bytes.extend_from_slice(data).unwrap(); + Bytes { bytes } } } @@ -560,7 +560,7 @@ impl<'de, const N: usize> Deserialize<'de> for Bytes { } #[cfg(test)] -mod tests_serde { +mod tests { use super::*; use serde_test::{assert_tokens, Token}; @@ -595,4 +595,12 @@ mod tests_serde { ) ); } + + #[test] + fn from() { + let _: Bytes<10> = [0; 10].into(); + let _: Bytes<10> = (&[0; 8]).into(); + let _: Bytes<10> = Vec::::new().into(); + let _: Bytes<10> = Vec::::new().into(); + } }