diff --git a/src/bounded_str.rs b/src/bounded_str.rs index 0379039..e704bcc 100644 --- a/src/bounded_str.rs +++ b/src/bounded_str.rs @@ -159,16 +159,17 @@ impl BoundedStr { 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(()) } diff --git a/src/tests/bounded_str_tests.rs b/src/tests/bounded_str_tests.rs index 8dbd8e5..4d7df9b 100644 --- a/src/tests/bounded_str_tests.rs +++ b/src/tests/bounded_str_tests.rs @@ -5,6 +5,7 @@ use crate::BStr15; use crate::BStr31; use crate::BStr63; use crate::BStr127; +use crate::ExceedsCapacity; #[test] fn test_size() { @@ -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(); @@ -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() { @@ -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")]