11//! Structured keys.
22
3+ use crate :: MaybeStaticStr ;
34use std:: borrow:: Borrow ;
45use std:: fmt;
56
@@ -35,40 +36,56 @@ impl ToKey for str {
3536// If a new field (such as an optional index) is added to the key they must not affect comparison
3637#[ derive( Clone , Debug , PartialEq , Eq , PartialOrd , Ord , Hash ) ]
3738pub struct Key < ' k > {
38- // NOTE: This may become `Cow<'k, str>`
39- key : & ' k str ,
39+ key : MaybeStaticStr < ' k > ,
4040}
4141
4242impl < ' k > Key < ' k > {
4343 /// Get a key from a borrowed string.
4444 #[ allow( clippy:: should_implement_trait) ] // Part of the public API now.
4545 pub fn from_str ( key : & ' k str ) -> Self {
46- Key { key }
46+ Key {
47+ key : MaybeStaticStr :: Borrowed ( key) ,
48+ }
49+ }
50+
51+ /// Get a key from a static str.
52+ pub fn from_str_static ( key : & ' static str ) -> Self {
53+ Key {
54+ key : MaybeStaticStr :: Static ( key) ,
55+ }
4756 }
4857
4958 /// Get a borrowed string from this key.
5059 ///
5160 /// The lifetime of the returned string is bound to the borrow of `self` rather
5261 /// than to `'k`.
5362 pub fn as_str ( & self ) -> & str {
54- self . key
63+ self . key . get ( )
5564 }
5665
57- /// Try get a borrowed string for the lifetime `'k` from this key.
66+ /// Try to get a borrowed string for the lifetime `'k` from this key.
5867 ///
5968 /// If the key is a borrow of a longer lived string, this method will return `Some`.
6069 /// If the key is internally buffered, this method will return `None`.
6170 pub fn to_borrowed_str ( & self ) -> Option < & ' k str > {
6271 // NOTE: If the internals of `Key` support buffering this
6372 // won't be unconditionally `Some` anymore. We want to keep
6473 // this option open
65- Some ( self . key )
74+ Some ( self . key . get ( ) )
75+ }
76+
77+ /// Try to get a static string from this key.
78+ pub fn to_static_str ( & self ) -> Option < & ' static str > {
79+ match self . key {
80+ MaybeStaticStr :: Static ( s) => Some ( s) ,
81+ MaybeStaticStr :: Borrowed ( _) => None ,
82+ }
6683 }
6784}
6885
6986impl < ' k > fmt:: Display for Key < ' k > {
7087 fn fmt ( & self , f : & mut fmt:: Formatter ) -> fmt:: Result {
71- self . key . fmt ( f)
88+ self . key . get ( ) . fmt ( f)
7289 }
7390}
7491
@@ -121,13 +138,13 @@ mod sval_support {
121138 & ' sval self ,
122139 stream : & mut S ,
123140 ) -> sval:: Result {
124- self . key . stream ( stream)
141+ self . key . get ( ) . stream ( stream)
125142 }
126143 }
127144
128145 impl < ' a > ValueRef < ' a > for Key < ' a > {
129146 fn stream_ref < S : sval:: Stream < ' a > + ?Sized > ( & self , stream : & mut S ) -> sval:: Result {
130- self . key . stream ( stream)
147+ self . key . get ( ) . stream ( stream)
131148 }
132149 }
133150}
@@ -143,7 +160,7 @@ mod serde_support {
143160 where
144161 S : Serializer ,
145162 {
146- self . key . serialize ( serializer)
163+ self . key . get ( ) . serialize ( serializer)
147164 }
148165 }
149166}
0 commit comments