Skip to content

Commit

Permalink
Minor code clean ups (ParkMyCar#350)
Browse files Browse the repository at this point in the history
* Dedup code

* Add missing `#[track_caller]`

* Add `try_new()`

* Call fallible methods in infallible methods
  • Loading branch information
Kijewski authored Jan 9, 2024
1 parent 68d42f5 commit 118963f
Showing 1 changed file with 18 additions and 6 deletions.
24 changes: 18 additions & 6 deletions compact_str/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,16 @@ impl CompactString {
#[inline]
#[track_caller]
pub fn new<T: AsRef<str>>(text: T) -> Self {
CompactString(Repr::new(text.as_ref()).unwrap_with_msg())
Self::try_new(text).unwrap_with_msg()
}

/// Fallible version of [`CompactString::new()`]
///
/// This method won't panic if the system is out-of-memory, but return an [`ReserveError`].
/// Otherwise it behaves the same as [`CompactString::new()`].
#[inline]
pub fn try_new<T: AsRef<str>>(text: T) -> Result<Self, ReserveError> {
Repr::new(text.as_ref()).map(CompactString)
}

/// Creates a new inline [`CompactString`] from `&'static str` at compile time.
Expand Down Expand Up @@ -307,7 +316,7 @@ impl CompactString {
#[inline]
#[track_caller]
pub fn with_capacity(capacity: usize) -> Self {
CompactString(Repr::with_capacity(capacity).unwrap_with_msg())
Self::try_with_capacity(capacity).unwrap_with_msg()
}

/// Fallible version of [`CompactString::with_capacity()`]
Expand Down Expand Up @@ -382,7 +391,9 @@ impl CompactString {
#[must_use]
#[track_caller]
pub unsafe fn from_utf8_unchecked<B: AsRef<[u8]>>(buf: B) -> Self {
CompactString(Repr::from_utf8_unchecked(buf).unwrap_with_msg())
Repr::from_utf8_unchecked(buf)
.map(CompactString)
.unwrap_with_msg()
}

/// Decode a [`UTF-16`](https://en.wikipedia.org/wiki/UTF-16) slice of bytes into a
Expand Down Expand Up @@ -545,7 +556,7 @@ impl CompactString {
#[inline]
#[track_caller]
pub fn reserve(&mut self, additional: usize) {
self.0.reserve(additional).unwrap_with_msg()
self.try_reserve(additional).unwrap_with_msg()
}

/// Fallible version of [`CompactString::reserve()`]
Expand Down Expand Up @@ -2065,8 +2076,7 @@ impl<'a> From<&'a str> for CompactString {
#[inline]
#[track_caller]
fn from(s: &'a str) -> Self {
let repr = Repr::new(s).unwrap_with_msg();
CompactString(repr)
CompactString::new(s)
}
}

Expand All @@ -2080,6 +2090,8 @@ impl From<String> for CompactString {
}

impl<'a> From<&'a String> for CompactString {
#[inline]
#[track_caller]
fn from(s: &'a String) -> Self {
CompactString::new(s)
}
Expand Down

0 comments on commit 118963f

Please sign in to comment.