Skip to content

Add Cow helpers for IString #10

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 30, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 39 additions & 2 deletions src/string.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::borrow::Cow;
use std::fmt::Debug;

/// An immutable string type inspired by [Immutable.js](https://immutable-js.com/).
Expand Down Expand Up @@ -27,10 +28,25 @@ impl IString {
/// ```
pub fn as_str(&self) -> &str {
match self {
Self::Static(s) => *s,
Self::Rc(s) => &*s,
Self::Static(s) => s,
Self::Rc(s) => s,
}
}

/// Obtain the contents of [`IString`] as a [`Cow`].
///
/// # Examples
///
/// ```
/// # use implicit_clone::unsync::IString;
/// use std::borrow::Cow;
/// let s = IString::from("foo");
///
/// let cow: Cow<'_, str> = s.as_cow();
/// ```
pub fn as_cow(&self) -> Cow<'_, str> {
Cow::Borrowed(self.as_str())
}
}

impl Default for IString {
Expand Down Expand Up @@ -65,6 +81,15 @@ impl From<Rc<str>> for IString {
}
}

impl From<Cow<'static, str>> for IString {
fn from(cow: Cow<'static, str>) -> Self {
match cow {
Cow::Borrowed(s) => IString::Static(s),
Cow::Owned(s) => s.into(),
}
}
}
Comment on lines +84 to +91
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you forgot to write a test for this. It's not super important but it makes sure that someone does not remove it by mistake


impl PartialEq<IString> for IString {
fn eq(&self, other: &IString) -> bool {
self.as_str().eq(other.as_str())
Expand Down Expand Up @@ -164,4 +189,16 @@ mod test_string {
assert_eq!(map.get("foo").copied(), Some(true));
assert_eq!(map.get("bar").copied(), Some(true));
}

#[test]
fn as_cow_does_not_clone() {
let rc_s = Rc::from("foo");
let s = IString::Rc(Rc::clone(&rc_s));
assert_eq!(Rc::strong_count(&rc_s), 2);
let cow: Cow<'_, str> = s.as_cow();
assert_eq!(Rc::strong_count(&rc_s), 2);
// this assert exists to ensure the cow lives after the strong_count asset
assert_eq!(cow, "foo");

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change

}
}