Skip to content

Commit

Permalink
Implement std::io::Write for Vec<'bump, u8>
Browse files Browse the repository at this point in the history
  • Loading branch information
marmeladema committed Sep 14, 2023
1 parent 86c63a4 commit cdaaae1
Show file tree
Hide file tree
Showing 5 changed files with 59 additions and 2 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ default = []
collections = []
boxed = []
allocator_api = []
std = []

# [profile.bench]
# debug = true
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,14 @@ in its space itself.

### `#![no_std]` Support

Bumpalo is a `no_std` crate. It depends only on the `alloc` and `core` crates.
Bumpalo is a `no_std` crate by default. It depends only on the `alloc` and `core` crates.

### `std` Support

You can optionally decide to enable the `std` feature in order to enable some
std only trait implementations for some collections:

* `std::io::Write` for `Vec<'bump, u8>`

### Thread support

Expand Down
22 changes: 22 additions & 0 deletions src/collections/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ use core::ops::{Index, IndexMut, RangeBounds};
use core::ptr;
use core::ptr::NonNull;
use core::slice;
#[cfg(feature = "std")]
use std::io;

unsafe fn arith_offset<T>(p: *const T, offset: isize) -> *const T {
p.offset(offset)
Expand Down Expand Up @@ -2612,3 +2614,23 @@ where
}
}
}

#[cfg(feature = "std")]
impl<'bump> io::Write for Vec<'bump, u8> {
#[inline]
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
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(())
}
}
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#![doc = include_str!("../README.md")]
#![deny(missing_debug_implementations)]
#![deny(missing_docs)]
#![no_std]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "allocator_api", feature(allocator_api))]

#[doc(hidden)]
Expand Down
27 changes: 27 additions & 0 deletions tests/all/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,30 @@ fn test_vec_items_get_dropped() {
}
assert_eq!("Dropped!Dropped!", buffer.borrow().deref());
}

#[cfg(feature = "std")]
#[test]
fn test_vec_write() {
use std::io::Write;

let b = Bump::new();
let mut v = bumpalo::vec![in &b];

assert_eq!(v.write(&[]).unwrap(), 0);

v.flush().unwrap();

assert_eq!(v.write(&[1]).unwrap(), 1);

v.flush().unwrap();

v.write_all(&[]).unwrap();

v.flush().unwrap();

v.write_all(&[2, 3]).unwrap();

v.flush().unwrap();

assert_eq!(v, &[1, 2, 3]);
}

0 comments on commit cdaaae1

Please sign in to comment.