-
Notifications
You must be signed in to change notification settings - Fork 159
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
Implement conversion from cow to std cow #478
Conversation
Did some experiments with |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The logic is sound, but I think we just need to clean up the ergonomics a little.
metrics/src/cow.rs
Outdated
/// Extracts the borrowed data. | ||
/// | ||
/// Returns `None` if the data is either shared or owned. | ||
/// | ||
/// # Examples | ||
/// | ||
/// ``` | ||
/// use metrics::SharedString; | ||
/// | ||
/// let s = SharedString::from_borrowed("foobar"); | ||
/// assert_eq!(s.as_borrowed(), Some("foobar")); | ||
/// | ||
/// let s = SharedString::from_owned("foobar".to_owned()); | ||
/// assert_eq!(s.as_borrowed(), None); | ||
/// | ||
/// let s = SharedString::from_shared("foobar".to_owned().into()); | ||
/// assert_eq!(s.as_borrowed(), None); | ||
/// ``` | ||
pub fn as_borrowed(&self) -> Option<&'a T> { | ||
match self.metadata.kind() { | ||
Kind::Owned | Kind::Shared => None, | ||
Kind::Borrowed => { | ||
// SAFETY: We know the contained data is borrowed from 'a, we're simply | ||
// restoring the original immutable reference and returning a copy of it. | ||
Some(unsafe { &*T::borrowed_from_parts(self.ptr, &self.metadata) }) | ||
} | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unless there's a compelling reason to have this be a standalone method, we should just move the logic down into impl From<Cow<'a, T>> for std::borrow::Cow<'a, T>
.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The problem with that is, the From
impl always requires a Clone
(or taking ownership, but the way the SharedString
is exposed it is usually through a reference), the as_borrowed()
allows for a decision. In the future this can be supplemented with as_shared()
.
That being said, we can reduce the API surface and just impl the From
(would be enough for my usecase) and see if more needs come up.
Removed the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good to me. 👍🏻
Released in Thanks again for your contribution. 🙏🏻 |
Closes: #474