Skip to content

Commit

Permalink
Issue #151: impl std::io::Write for u8-based TinyVecs (#152)
Browse files Browse the repository at this point in the history
* impl std::io::Write for u8-based TinyVec

* undo bad formatting

* fix formatting
  • Loading branch information
eeeebbbbrrrr authored Sep 24, 2021
1 parent 5ae2542 commit 750f684
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 2 deletions.
5 changes: 4 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down Expand Up @@ -65,7 +68,7 @@ serde_test = "1.0"

[[test]]
name = "tinyvec"
required-features = ["alloc"]
required-features = ["alloc", "std"]

[[bench]]
name = "macros"
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#![no_std]
#![cfg_attr(not(feature = "std"), no_std)]
#![forbid(unsafe_code)]
#![cfg_attr(
feature = "nightly_slice_partition_dedup",
Expand Down
14 changes: 14 additions & 0 deletions src/tinyvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down
15 changes: 15 additions & 0 deletions tests/tinyvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
}

0 comments on commit 750f684

Please sign in to comment.