From fb7ba225d197f4a54771ac528abee69e89155b50 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Tue, 23 Aug 2016 16:23:44 -0400 Subject: [PATCH 1/2] Add constructors for Bytes and ByteBuf This commit adds `Bytes::new(&[u8])` and `ByteBuf::from>>(T)`. --- serde/src/bytes.rs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs index 67f8ce85..12e42e75 100644 --- a/serde/src/bytes.rs +++ b/serde/src/bytes.rs @@ -19,6 +19,15 @@ pub struct Bytes<'a> { bytes: &'a [u8], } +impl<'a> Bytes<'a> { + /// Wrap an existing `&[u8]`. + pub fn new(bytes: &'a [u8]) -> Self { + Bytes { + bytes: bytes, + } + } +} + impl<'a> fmt::Debug for Bytes<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(f.write_str("b\"")); @@ -101,6 +110,13 @@ mod bytebuf { bytes: Vec::with_capacity(cap) } } + + /// Wrap existing bytes in a `ByteBuf`. + pub fn from>>(bytes: T) -> Self { + ByteBuf { + bytes: bytes.into(), + } + } } impl fmt::Debug for ByteBuf { From 08bc2d2e76e9d9965c3067d5b5f54dfe92ab7192 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Mon, 5 Sep 2016 08:09:23 -0700 Subject: [PATCH 2/2] Use constructors to create Bytes and ByteBuf --- serde/src/bytes.rs | 32 ++++++++------------------------ 1 file changed, 8 insertions(+), 24 deletions(-) diff --git a/serde/src/bytes.rs b/serde/src/bytes.rs index 12e42e75..a732712c 100644 --- a/serde/src/bytes.rs +++ b/serde/src/bytes.rs @@ -40,18 +40,14 @@ impl<'a> fmt::Debug for Bytes<'a> { impl<'a> From<&'a [u8]> for Bytes<'a> { fn from(bytes: &'a [u8]) -> Self { - Bytes { - bytes: bytes, - } + Bytes::new(bytes) } } #[cfg(any(feature = "std", feature = "collections"))] impl<'a> From<&'a Vec> for Bytes<'a> { fn from(bytes: &'a Vec) -> Self { - Bytes { - bytes: bytes, - } + Bytes::new(bytes) } } @@ -99,16 +95,12 @@ mod bytebuf { impl ByteBuf { /// Construct a new, empty `ByteBuf`. pub fn new() -> Self { - ByteBuf { - bytes: Vec::new(), - } + ByteBuf::from(Vec::new()) } /// Construct a new, empty `ByteBuf` with the specified capacity. pub fn with_capacity(cap: usize) -> Self { - ByteBuf { - bytes: Vec::with_capacity(cap) - } + ByteBuf::from(Vec::with_capacity(cap)) } /// Wrap existing bytes in a `ByteBuf`. @@ -137,9 +129,7 @@ mod bytebuf { impl From> for ByteBuf { fn from(bytes: Vec) -> Self { - ByteBuf { - bytes: bytes, - } + ByteBuf::from(bytes) } } @@ -195,9 +185,7 @@ mod bytebuf { fn visit_unit(&mut self) -> Result where E: de::Error, { - Ok(ByteBuf { - bytes: Vec::new(), - }) + Ok(ByteBuf::new()) } #[inline] @@ -213,9 +201,7 @@ mod bytebuf { try!(visitor.end()); - Ok(ByteBuf { - bytes: values, - }) + Ok(ByteBuf::from(values)) } #[inline] @@ -229,9 +215,7 @@ mod bytebuf { fn visit_byte_buf(&mut self, v: Vec) -> Result where E: de::Error, { - Ok(ByteBuf { - bytes: v, - }) + Ok(ByteBuf::from(v)) } }