metrics-rs / metrics

A metrics ecosystem for Rust.
MIT License
1.06k stars 145 forks source link

Make it possible to extract `&'static T` from `Cow<'static, T>`. #474

Closed Dav1dde closed 2 months ago

Dav1dde commented 2 months ago

I am implementing a recorder from metrics to sentry::metrics and Sentry currently uses std::cow::Cow<'static, str> for tags and metric names. If it was possible to extract a &'static str from a SharedStr many to_owned calls would be saved.

I tried implementing it myself but it seems easy to get wrong.

tobz commented 2 months ago

It's indeed a little tricky, but moreso due to the API required. Since metrics::cow::Cow isn't an enum, we would need a dedicated method for as_borrowed that returns Option<&'a T> since it may not be a borrowed variant, and you'd have to potentially fall back to calling to_owned.

Happy to mentor a PR providing that.

Dav1dde commented 2 months ago

I was thinking either as_borrowed or "easier", something like:

impl<T> Cow<'static, T> {
    fn as_static() {} // or `as_borrowed` but just implement it for the "easier" (?) 'static lifetime
}

I also had the idea of providing a way of turning the Cow into a proper std::cow::Cow and returning that, owning when necessary.

tobz commented 2 months ago

The lifetime used does not change the fact the wrapper might be holding an owned value, which means you cannot provide a static reference to it, so it has to be something like as_borrowed(&self) -> Option<&'a T>, or an impl to convert to std::borrow::Cow, which is also possible.