constify things and remember how booleans work

This commit is contained in:
missing 2022-12-20 23:11:37 -06:00
parent e99bd05378
commit 222543645e

View file

@ -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<bool> {
pub const fn is_borrowed(&self) -> Option<bool> {
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<bool> {
self.is_borrowed().map(|v| !v)
pub const fn is_owned(&self) -> Option<bool> {
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()) }
}