Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bump::alloc_str #50

Merged
merged 1 commit into from
Nov 21, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
* Add `alloc_str`, which is similar to `alloc_slice_*` methods, but works on
string slices.

# 2.6.0

Released 2019-08-19.
Expand Down
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ use core::marker::PhantomData;
use core::mem;
use core::ptr::{self, NonNull};
use core::slice;
use core::str;
use core_alloc::alloc::{alloc, dealloc, Layout};

/// An arena to bump allocate into.
Expand Down Expand Up @@ -640,6 +641,29 @@ impl Bump {
}
}

/// `Copy` a string slice into this `Bump` and return an exclusive reference to it.
///
/// ## Panics
///
/// Panics if reserving space for the string would cause an overflow.
///
/// ## Example
///
/// ```
/// let bump = bumpalo::Bump::new();
/// let hello = bump.alloc_str("hello world");
/// assert_eq!("hello world", hello);
/// ```
#[inline(always)]
#[allow(clippy::mut_from_ref)]
pub fn alloc_str(&self, src: &str) -> &mut str {
let buffer = self.alloc_slice_copy(src.as_bytes());
unsafe {
// This is OK, because it already came in as str, so it is guaranteed to be utf8
str::from_utf8_unchecked_mut(buffer)
}
}

/// Allocates a new slice of size `len` into this `Bump` and returns an
/// exclusive reference to the copy.
///
Expand Down
8 changes: 8 additions & 0 deletions tests/quickchecks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,12 @@ quickcheck! {
allocated.push(range);
}
}

fn alloc_strs(allocs: Vec<String>) -> () {
let b = Bump::new();
let allocated: Vec<&str> = allocs.iter().map(|s| b.alloc_str(s) as &_).collect();
for (val, alloc) in allocs.into_iter().zip(allocated) {
assert_eq!(val, alloc);
}
}
}