Skip to content
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
9 changes: 5 additions & 4 deletions src/bounded_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,16 +159,17 @@ impl<const N: usize, Alignment> BoundedStr<N, Alignment> {
pub fn push_str(&mut self, s: &str) -> Result<(), ExceedsCapacity> {
let bytes = s.as_bytes();
let length = self.length as usize;
let new_len = length + bytes.len();

if length + bytes.len() > N {
if new_len > N {
return Err(ExceedsCapacity {
length,
length: new_len,
capacity: N,
});
}

self.data[length..length + bytes.len()].copy_from_slice(bytes);
self.length += bytes.len() as u8;
self.data[length..new_len].copy_from_slice(bytes);
self.length = new_len as u8;

Ok(())
}
Expand Down
36 changes: 35 additions & 1 deletion src/tests/bounded_str_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use crate::BStr15;
use crate::BStr31;
use crate::BStr63;
use crate::BStr127;
use crate::ExceedsCapacity;

#[test]
fn test_size() {
Expand Down Expand Up @@ -34,6 +35,19 @@ fn test_push_str() {
assert_eq!(s.as_str(), "abcdef");
}

#[test]
fn test_push_str_exceeds_capacity() {
let mut s = BStr7::new();

assert_eq!(
s.push_str("00000000"),
Err(ExceedsCapacity {
length: 8,
capacity: 7
})
);
}

#[test]
fn test_push() {
let mut s = BStr15::new();
Expand Down Expand Up @@ -61,11 +75,12 @@ fn test_into() {

#[cfg(feature = "std")]
mod std {
use std::format;
use std::string::String;
use std::vec;
use std::vec::Vec;

use crate::{Align8, Align64, BStr7, BStr63, StrVec};
use crate::{Align8, Align64, BStr7, BStr63, ExceedsCapacity, StrVec};

#[test]
fn test_into_panic() {
Expand Down Expand Up @@ -114,6 +129,25 @@ mod std {
]
);
}

#[test]
fn test_push_str_exceeds_capacity() {
let mut s = BStr7::new();
let exceeds_capacity = s.push_str("00000000").unwrap_err();

assert_eq!(
exceeds_capacity,
ExceedsCapacity {
length: 8,
capacity: 7
}
);

assert_eq!(
format!("{}", exceeds_capacity),
"String length (8) exceeds capacity (7)"
);
}
}

#[cfg(feature = "serde")]
Expand Down
Loading