Skip to content

Commit

Permalink
Merge pull request #653 from rust-lang/fix/key-lifetimes
Browse files Browse the repository at this point in the history
Fix up key lifetimes and add method to try get a borrowed key
  • Loading branch information
KodrAus authored Dec 25, 2024
2 parents 134d252 + 7e79d7f commit c875606
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/kv/key.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ impl ToKey for str {
// If a new field (such as an optional index) is added to the key they must not affect comparison
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Key<'k> {
// NOTE: This may become `Cow<'k, str>`
key: &'k str,
}

Expand All @@ -45,9 +46,23 @@ impl<'k> Key<'k> {
}

/// Get a borrowed string from this key.
pub fn as_str(&self) -> &'k str {
///
/// The lifetime of the returned string is bound to the borrow of `self` rather
/// than to `'k`.
pub fn as_str(&self) -> &str {
self.key
}

/// Try get a borrowed string for the lifetime `'k` from this key.
///
/// If the key is a borrow of a longer lived string, this method will return `Some`.
/// If the key is internally buffered, this method will return `None`.
pub fn to_borrowed_str(&self) -> Option<&'k str> {
// NOTE: If the internals of `Key` support buffering this
// won't be unconditionally `Some` anymore. We want to keep
// this option open
Some(self.key)
}
}

impl<'k> fmt::Display for Key<'k> {
Expand Down Expand Up @@ -140,4 +155,9 @@ mod tests {
fn key_from_string() {
assert_eq!("a key", Key::from_str("a key").as_str());
}

#[test]
fn key_to_borrowed() {
assert_eq!("a key", Key::from_str("a key").to_borrowed_str().unwrap());
}
}

0 comments on commit c875606

Please sign in to comment.