From e96793e571a84a0e98656c2cf1361c324f29bd3b Mon Sep 17 00:00:00 2001 From: Thomas Heck Date: Thu, 1 Jun 2017 15:45:43 +0200 Subject: [PATCH] impl std::io::Write for SmallVec --- lib.rs | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/lib.rs b/lib.rs index 7b4243e..13d787c 100644 --- a/lib.rs +++ b/lib.rs @@ -33,6 +33,8 @@ use std::mem; use std::ops; use std::ptr; use std::slice; +#[cfg(feature = "std")] +use std::io; #[cfg(feature="heapsizeof")] use std::os::raw::c_void; @@ -632,6 +634,26 @@ impl BorrowMut<[A::Item]> for SmallVec { } } +#[cfg(feature = "std")] +impl> io::Write for SmallVec { + #[inline] + fn write(&mut self, buf: &[u8]) -> io::Result { + self.extend_from_slice(buf); + Ok(buf.len()) + } + + #[inline] + fn write_all(&mut self, buf: &[u8]) -> io::Result<()> { + self.extend_from_slice(buf); + Ok(()) + } + + #[inline] + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + impl<'a, A: Array> From<&'a [A::Item]> for SmallVec where A::Item: Clone { #[inline] fn from(slice: &'a [A::Item]) -> SmallVec { @@ -1436,4 +1458,21 @@ pub mod tests { assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); drop(small_vec); } + + #[cfg(feature = "std")] + #[test] + fn test_write() { + use io::Write; + + let data = [1, 2, 3, 4, 5]; + + let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new(); + let len = small_vec.write(&data[..]).unwrap(); + assert_eq!(len, 5); + assert_eq!(small_vec.as_ref(), data.as_ref()); + + let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new(); + small_vec.write_all(&data[..]).unwrap(); + assert_eq!(small_vec.as_ref(), data.as_ref()); + } }