Skip to content

Commit e96793e

Browse files
committed
impl std::io::Write for SmallVec
1 parent b7f5fe5 commit e96793e

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

lib.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ use std::mem;
3333
use std::ops;
3434
use std::ptr;
3535
use std::slice;
36+
#[cfg(feature = "std")]
37+
use std::io;
3638
#[cfg(feature="heapsizeof")]
3739
use std::os::raw::c_void;
3840

@@ -632,6 +634,26 @@ impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
632634
}
633635
}
634636

637+
#[cfg(feature = "std")]
638+
impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
639+
#[inline]
640+
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
641+
self.extend_from_slice(buf);
642+
Ok(buf.len())
643+
}
644+
645+
#[inline]
646+
fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
647+
self.extend_from_slice(buf);
648+
Ok(())
649+
}
650+
651+
#[inline]
652+
fn flush(&mut self) -> io::Result<()> {
653+
Ok(())
654+
}
655+
}
656+
635657
impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A> where A::Item: Clone {
636658
#[inline]
637659
fn from(slice: &'a [A::Item]) -> SmallVec<A> {
@@ -1436,4 +1458,21 @@ pub mod tests {
14361458
assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
14371459
drop(small_vec);
14381460
}
1461+
1462+
#[cfg(feature = "std")]
1463+
#[test]
1464+
fn test_write() {
1465+
use io::Write;
1466+
1467+
let data = [1, 2, 3, 4, 5];
1468+
1469+
let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new();
1470+
let len = small_vec.write(&data[..]).unwrap();
1471+
assert_eq!(len, 5);
1472+
assert_eq!(small_vec.as_ref(), data.as_ref());
1473+
1474+
let mut small_vec: SmallVec<[u8; 2]> = SmallVec::new();
1475+
small_vec.write_all(&data[..]).unwrap();
1476+
assert_eq!(small_vec.as_ref(), data.as_ref());
1477+
}
14391478
}

0 commit comments

Comments
 (0)