From 04844baac1427f1d74a79823a393e0706541f763 Mon Sep 17 00:00:00 2001 From: Yota Toyama Date: Sun, 6 Apr 2025 18:48:04 -0700 Subject: [PATCH] Allow pushing 0 byte --- src/c_string.rs | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/c_string.rs b/src/c_string.rs index 76a6038d..46d6b4cf 100644 --- a/src/c_string.rs +++ b/src/c_string.rs @@ -210,17 +210,13 @@ impl CString { /// assert_eq!(cstr.to_str(), Ok("hey there")); /// ``` pub fn push_bytes(&mut self, bytes: &[u8]) -> Result<(), CapacityError> { - match self.size_if_appended_bytes(bytes) { - Some(resulting_size) if resulting_size > N => { - // Can't store these bytes due to insufficient capacity - return Err(CapacityError); - } - Some(_) => {} - None => { - // Nothing to insert - assert!(false); - return Ok(()); - } + let Some(size) = self.size_if_appended_bytes(bytes) else { + return Ok(()); + }; + + if size > N { + // Can't store these bytes due to insufficient capacity. + return Err(CapacityError); } match memchr(0, bytes) { @@ -388,6 +384,14 @@ mod tests { assert_eq!(empty.to_str(), Ok("")); } + #[test] + fn push_no_bytes() { + let mut cstr = CString::<5>::new(); + assert_eq!(cstr.to_str(), Ok("")); + + cstr.push_bytes(b"").unwrap(); + } + #[test] fn push_bytes() { let mut cstr = CString::<11>::new();