From 222543645ee692a6b996a302181655b7d21615c7 Mon Sep 17 00:00:00 2001 From: missing Date: Tue, 20 Dec 2022 23:11:37 -0600 Subject: [PATCH] constify things and remember how booleans work --- src/lib.rs | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 8f4ee44..89b35da 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -65,7 +65,7 @@ impl Stringish { /// Creates a new empty `Stringish`. #[must_use] - pub fn new() -> Self { + pub const fn new() -> Self { Self { ptr: NonNull::dangling(), len: 0, @@ -77,7 +77,7 @@ impl Stringish { /// /// Alternatively, use the [`Ish::ish`] method. #[must_use] - pub fn new_borrowed(s: &'static str) -> Self { + pub const fn new_borrowed(s: &'static str) -> Self { Self { // SAFETY: `s.as_ptr()` is never null ptr: unsafe { NonNull::new_unchecked(s.as_ptr() as *mut u8) }, @@ -123,13 +123,11 @@ impl Stringish { /// If the `Stringish` is empty, returns [`None`]. Otherwise, returns `true` if the `Stringish` /// is borrowed and `false` otherwise. #[must_use] - pub fn is_borrowed(&self) -> Option { + pub const fn is_borrowed(&self) -> Option { if self.len == 0 { None - } else if self.cap == 0 { - Some(true) } else { - Some(false) + Some(self.cap == 0) } } @@ -138,8 +136,12 @@ impl Stringish { /// If the `Stringish` is empty, returns [`None`]. Otherwise, returns `true` if the `Stringish` /// is owned and `false` otherwise. #[must_use] - pub fn is_owned(&self) -> Option { - self.is_borrowed().map(|v| !v) + pub const fn is_owned(&self) -> Option { + if self.len == 0 { + None + } else { + Some(self.cap != 0) + } } /// Converts a borrowed `Stringish` into an owned `Stringish`, in-place. @@ -173,7 +175,7 @@ impl Stringish { /// Returns a byte slice of this `Stringish`'s contents. #[must_use] - pub fn as_bytes(&self) -> &[u8] { + pub const fn as_bytes(&self) -> &[u8] { // SAFETY: `self.ptr` always points to `self.len` valid bytes unsafe { slice::from_raw_parts(self.ptr.as_ptr(), self.len) } } @@ -195,7 +197,7 @@ impl Stringish { /// Returns a string slice of this `Stringish`'s contents. #[must_use] - pub fn as_str(&self) -> &str { + pub const fn as_str(&self) -> &str { // SAFETY: `self.ptr` always points to valid UTF-8 unsafe { str::from_utf8_unchecked(self.as_bytes()) } }