Skip to content

Commit

Permalink
Merge pull request #39 from vorner/alloc_str
Browse files Browse the repository at this point in the history
Arena::<u8>::alloc_str
  • Loading branch information
pczarn committed Nov 23, 2019
2 parents 3e8abe0 + ef40195 commit d4b70be
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
2 changes: 1 addition & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Released YYYY/MM/DD.

### Added

* TODO (or remove section if none)
* Added `alloc_str` to `Arena<u8>`, to be able to allocate string slices.

### Changed

Expand Down
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ use core::cmp;
use core::iter;
use core::mem;
use core::slice;
use core::str;

#[cfg(test)]
mod test;
Expand Down Expand Up @@ -427,6 +428,29 @@ impl<T> Arena<T> {
}
}

impl Arena<u8> {
/// Allocates a string slice and returns a mutable reference to it.
///
/// This is on `Arena<u8>`, because string slices use byte slices (`[u8]`) as their backing
/// storage.
///
/// # Example
///
/// ```
/// use typed_arena::Arena;
///
/// let arena: Arena<u8> = Arena::new();
/// let hello = arena.alloc_str("Hello world");
/// assert_eq!("Hello world", hello);
/// ```
#[inline]
pub fn alloc_str(&self, s: &str) -> &mut str {
let buffer = self.alloc_extend(s.bytes());
// Can't fail the utf8 validation, it already came in as utf8
unsafe { str::from_utf8_unchecked_mut(buffer) }
}
}

impl<T> Default for Arena<T> {
fn default() -> Self {
Self::new()
Expand Down

0 comments on commit d4b70be

Please sign in to comment.