metrics-rs / metrics

A metrics ecosystem for Rust.
MIT License
1.1k stars 151 forks source link

Unable to extract Key::name as a SharedString/Cow #383

Closed BMorinDrifter closed 1 year ago

BMorinDrifter commented 1 year ago

Because Key::name() returns a &str instead of a &'static str or SharedString, I either had to copy the string or retain the entire Key for internal book keeping in my collector (https://crates.io/crates/metrics_cloudwatch_embedded)

Please advice on how to get a SharedString or add an accessor.

pub struct Key {
    name: KeyName,
    labels: Cow<'static, [Label]>,
    hashed: AtomicBool,
    hash: AtomicU64,
}

 /// Name of this key.
    pub fn name(&self) -> &str {
        self.name.0.as_ref()
    }
tobz commented 1 year ago

We return &str because it's not actually a &'static str under the hood, at least not always. We also don't return SharedString because that would allocate a new String if it wasn't created from &'static str.

The correct thing to do is to clone the Key. If it was created from &'static str, then it'll be a cheap clone, otherwise it will allocate a new String (or strings, depending on how the labels are configured). That is the optimal approach.