Skip to content

Commit

Permalink
Merge pull request #124 from Kijewski/pr-mut-str
Browse files Browse the repository at this point in the history
Add `as_mut_str()` method
  • Loading branch information
ParkMyCar authored Jun 25, 2022
2 parents 6e6a74d + 13882b9 commit fe1a7df
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
36 changes: 35 additions & 1 deletion compact_str/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,10 @@
//! and capacity on the stack, you store the string itself! This avoids the need to heap allocate
//! which reduces the amount of memory used, and improves performance.
use core::borrow::Borrow;
use core::borrow::{
Borrow,
BorrowMut,
};
use core::cmp::Ordering;
use core::fmt;
use core::hash::{
Expand All @@ -24,6 +27,7 @@ use core::iter::FromIterator;
use core::ops::{
Add,
Deref,
DerefMut,
};
use core::str::{
FromStr,
Expand Down Expand Up @@ -362,6 +366,22 @@ impl CompactString {
self.repr.as_str()
}

/// Returns a mutable string slice containing the entire [`CompactString`].
///
/// # Examples
/// ```
/// # use compact_str::CompactString;
/// let mut s = CompactString::new("hello");
/// s.as_mut_str().make_ascii_uppercase();
///
/// assert_eq!(s.as_str(), "HELLO");
/// ```
#[inline]
pub fn as_mut_str(&mut self) -> &mut str {
let len = self.len();
unsafe { std::str::from_utf8_unchecked_mut(&mut self.repr.as_mut_slice()[..len]) }
}

/// Returns a byte slice of the [`CompactString`]'s contents.
///
/// # Examples
Expand Down Expand Up @@ -510,6 +530,13 @@ impl Deref for CompactString {
}
}

impl DerefMut for CompactString {
#[inline]
fn deref_mut(&mut self) -> &mut str {
self.as_mut_str()
}
}

impl AsRef<str> for CompactString {
#[inline]
fn as_ref(&self) -> &str {
Expand All @@ -531,6 +558,13 @@ impl Borrow<str> for CompactString {
}
}

impl BorrowMut<str> for CompactString {
#[inline]
fn borrow_mut(&mut self) -> &mut str {
self.as_mut_str()
}
}

impl Eq for CompactString {}

impl<T: AsRef<str>> PartialEq<T> for CompactString {
Expand Down
9 changes: 9 additions & 0 deletions fuzz/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,7 @@ pub enum Action<'a> {
ExtendChars(Vec<char>),
ExtendStr(Vec<&'a str>),
CheckSubslice(u8, u8),
MakeUppercase,
}

impl Action<'_> {
Expand Down Expand Up @@ -469,6 +470,14 @@ impl Action<'_> {

assert_eq!(control_slice, compact_slice);
}
// get a mutable string slice and turn its ASCII characters uppercase
MakeUppercase => {
control.as_mut_str().make_ascii_uppercase();
compact.as_mut_str().make_ascii_uppercase();

assert_eq!(control, compact);
assert_eq!(control.len(), compact.len());
}
}
}
}
Expand Down

0 comments on commit fe1a7df

Please sign in to comment.