Skip to content

Commit

Permalink
Add pop method
Browse files Browse the repository at this point in the history
  • Loading branch information
DoumanAsh committed Nov 10, 2024
1 parent e230bea commit e5dfc04
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,16 @@ impl<const N: usize> StrBuf<N> {
self.as_mut_slice().make_ascii_uppercase()
}
}

///Removes last character from the buffer, if any present
pub fn pop(&mut self) -> Option<char> {
let ch = self.chars().rev().next()?;
let new_len = self.len() - ch.len_utf8();
unsafe {
self.set_len(new_len)
}
Some(ch)
}
}

impl<const S: usize> AsRef<str> for StrBuf<S> {
Expand Down
17 changes: 17 additions & 0 deletions tests/push.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,11 @@ fn should_correctly_truncate_by_char_boundary() {
assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(buf, "ロ");

assert_eq!(buf.pop(), Some('ロ'));

assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(buf, "ロ");

assert_eq!(buf.push_str("リ"), 0);

assert_eq!(buf.push_str("r"), 1);
Expand Down Expand Up @@ -84,6 +89,11 @@ fn should_correctly_truncate_by_char_boundary_medium() {
buf.set_len(PADDING);
}

assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(&buf[PADDING..], "ロ");

assert_eq!(buf.pop(), Some('ロ'));

assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(&buf[PADDING..], "ロ");
assert_eq!(buf.len(), PADDING + "ロ".len());
Expand Down Expand Up @@ -137,6 +147,13 @@ fn should_correctly_truncate_by_char_boundary_big() {
unsafe {
buf.set_len(PADDING);
}

assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(&buf[PADDING..], "ロ");
assert_eq!(buf.len(), PADDING + "ロ".len());

assert_eq!(buf.pop(), Some('ロ'));

assert_eq!(buf.push_str("ロリ"), 3);
assert_eq!(&buf[PADDING..], "ロ");
assert_eq!(buf.len(), PADDING + "ロ".len());
Expand Down

0 comments on commit e5dfc04

Please sign in to comment.