Issue #151: impl std::io::Write for u8-based TinyVecs (#152)

* impl std::io::Write for u8-based TinyVec

* undo bad formatting

* fix formatting
This commit is contained in:
Eric Ridge
2021-09-24 11:58:46 -06:00
committed by GitHub
parent fa49aa60ca
commit dca393f1d7
4 changed files with 34 additions and 2 deletions
+4 -1
View File
@@ -22,6 +22,9 @@ default = []
# Provide things that utilize the `alloc` crate, namely `TinyVec`.
alloc = ["tinyvec_macros"]
# Provide things that require Rust's `std` module
std = []
# (not part of Vec!) Extra methods to let you grab the slice of memory after the
# "active" portion of an `ArrayVec` or `SliceVec`.
grab_spare_slice = []
@@ -65,7 +68,7 @@ serde_test = "1.0"
[[test]]
name = "tinyvec"
required-features = ["alloc"]
required-features = ["alloc", "std"]
[[bench]]
name = "macros"
+1 -1
View File
@@ -1,4 +1,4 @@
#![no_std]
#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![cfg_attr(
feature = "nightly_slice_partition_dedup",
+14
View File
@@ -172,6 +172,20 @@ impl<A: Array, I: SliceIndex<[A::Item]>> IndexMut<I> for TinyVec<A> {
}
}
#[cfg(feature = "std")]
impl<A: Array<Item = u8>> std::io::Write for TinyVec<A> {
#[inline(always)]
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
self.extend_from_slice(buf);
Ok(buf.len())
}
#[inline(always)]
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
#[cfg(feature = "serde")]
#[cfg_attr(docs_rs, doc(cfg(feature = "serde")))]
impl<A: Array> Serialize for TinyVec<A>
+15
View File
@@ -394,3 +394,18 @@ fn TinyVec_pretty_debug() {
assert_eq!(s, expected);
}
#[cfg(feature = "std")]
#[test]
fn TinyVec_std_io_write() {
use std::io::Write;
let mut tv: TinyVec<[u8; 3]> = TinyVec::new();
tv.write_all(b"foo").ok();
assert!(tv.is_inline());
assert_eq!(tv, tiny_vec![b'f', b'o', b'o']);
tv.write_all(b"bar").ok();
assert!(tv.is_heap());
assert_eq!(tv, tiny_vec![b'f', b'o', b'o', b'b', b'a', b'r']);
}