From 7e79d7f5b3bdc85c5893ca3ad8b9d3a383c4f25c Mon Sep 17 00:00:00 2001 From: Ashley Mannix Date: Mon, 23 Dec 2024 08:57:24 +1000 Subject: [PATCH] fix up key lifetimes and add method to try get a borrowed key --- src/kv/key.rs | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/src/kv/key.rs b/src/kv/key.rs index 5221c98f1..6e00a2ca8 100644 --- a/src/kv/key.rs +++ b/src/kv/key.rs @@ -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, } @@ -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> { @@ -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()); + } }