Skip to content
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

Fix up key lifetimes and add method to try get a borrowed key #653

Merged
merged 1 commit into from
Dec 25, 2024
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
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());
}
}
Loading