From 0a2d6d3a2a3d43e747368f002e45b206103c6863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20G=C3=B6ttsche?= Date: Sun, 7 Sep 2025 16:35:27 +0200 Subject: [PATCH] Return NonZero from len() and capacity() Since the string s guaranteed to be non-empty, its length and capacity are similarly guaranteed to be non-zero. Use NonZero to signal this invariant. Breaking change due to API change. --- src/lib.rs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8477b8a..f6dd119 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -10,7 +10,8 @@ mod test_readme { mod something {} } -use std::str::FromStr; +use core::num::NonZero; +use core::str::FromStr; use delegate::delegate; @@ -77,7 +78,9 @@ impl NonEmptyString { /// Is forwarded to the inner String. /// See [`String::capacity`] - pub fn capacity(&self) -> usize; + #[try_into] + #[unwrap] + pub fn capacity(&self) -> NonZero; /// Is forwarded to the inner String. /// See [`String::reserve`] @@ -123,7 +126,9 @@ impl NonEmptyString { /// Is forwarded to the inner String. /// See [`String::len`] - pub fn len(&self) -> usize; + #[try_into] + #[unwrap] + pub fn len(&self) -> NonZero; /// Is forwarded to the inner String. /// See [`String::into_boxed_str`] @@ -222,7 +227,8 @@ mod tests { fn calling_string_methods_works() { let nes = NonEmptyString::new("string".to_owned()).unwrap(); // `len` is a `String` method. - assert!(nes.len() > 0); + assert_eq!(nes.len(), NonZero::new(6).unwrap()); + assert!(nes.capacity() >= NonZero::new(6).unwrap()); } #[test]