Skip to content

Commit c906cfb

Browse files
authored
Merge pull request #727 from tisonkun/leverage-static-str-key-when-possible
Leverage static str key when possible
2 parents 761461a + 756c279 commit c906cfb

4 files changed

Lines changed: 53 additions & 19 deletions

File tree

src/__private_api.rs

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,28 +6,30 @@ use std::fmt::Arguments;
66
use std::panic::Location;
77
pub use std::{format_args, module_path, stringify};
88

9+
#[cfg(not(feature = "kv"))]
10+
pub type Key<'a> = &'a str;
911
#[cfg(not(feature = "kv"))]
1012
pub type Value<'a> = &'a str;
1113

1214
mod sealed {
1315
/// Types for the `kv` argument.
1416
pub trait KVs<'a> {
15-
fn into_kvs(self) -> Option<&'a [(&'a str, super::Value<'a>)]>;
17+
fn into_kvs(self) -> Option<&'a [(super::Key<'a>, super::Value<'a>)]>;
1618
}
1719
}
1820

1921
// Types for the `kv` argument.
2022

21-
impl<'a> KVs<'a> for &'a [(&'a str, Value<'a>)] {
23+
impl<'a> KVs<'a> for &'a [(Key<'a>, Value<'a>)] {
2224
#[inline]
23-
fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> {
25+
fn into_kvs(self) -> Option<&'a [(Key<'a>, Value<'a>)]> {
2426
Some(self)
2527
}
2628
}
2729

2830
impl<'a> KVs<'a> for () {
2931
#[inline]
30-
fn into_kvs(self) -> Option<&'a [(&'a str, Value<'a>)]> {
32+
fn into_kvs(self) -> Option<&'a [(Key<'a>, Value<'a>)]> {
3133
None
3234
}
3335
}
@@ -58,7 +60,7 @@ fn log_impl<L: Log>(
5860
args: Arguments,
5961
level: Level,
6062
&(target, module_path, loc): &(&str, &'static str, &'static Location),
61-
kvs: Option<&[(&str, Value)]>,
63+
kvs: Option<&[(Key, Value)]>,
6264
) {
6365
#[cfg(not(feature = "kv"))]
6466
if kvs.is_some() {
@@ -113,6 +115,7 @@ pub fn loc() -> &'static Location<'static> {
113115
mod kv_support {
114116
use crate::kv;
115117

118+
pub type Key<'a> = kv::Key<'a>;
116119
pub type Value<'a> = kv::Value<'a>;
117120

118121
// NOTE: Many functions here accept a double reference &&V

src/kv/key.rs

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
//! Structured keys.
22
3+
use crate::MaybeStaticStr;
34
use std::borrow::Borrow;
45
use 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)]
3738
pub struct Key<'k> {
38-
// NOTE: This may become `Cow<'k, str>`
39-
key: &'k str,
39+
key: MaybeStaticStr<'k>,
4040
}
4141

4242
impl<'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

6986
impl<'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
}

src/macros.rs

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -444,12 +444,16 @@ macro_rules! __log_logger {
444444
#[cfg(feature = "kv")]
445445
macro_rules! __log_key {
446446
// key1 = 42
447-
($($args:ident)*) => {
448-
$crate::__private_api::stringify!($($args)*)
447+
($args:ident) => {
448+
$crate::__private_api::Key::from_str_static($crate::__private_api::stringify!($args))
449449
};
450450
// "key1" = 42
451-
($($args:expr)*) => {
452-
$($args)*
451+
($args:literal) => {
452+
$crate::__private_api::Key::from_str_static($args)
453+
};
454+
// key = 42, where key is an expression
455+
($args:expr) => {
456+
$crate::__private_api::Key::from_str($args)
453457
};
454458
}
455459

tests/macros.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,16 @@ fn kv_ident() {
269269
all_log_macros!(cat_1, cat_2:%, cat_count = 2; "hello {world}", world = "world");
270270
}
271271

272+
#[test]
273+
#[cfg(feature = "kv")]
274+
fn kv_static_keys() {
275+
assert_eq!(Some("cat_1"), log::__log_key!(cat_1).to_static_str());
276+
assert_eq!(Some("cat_1"), log::__log_key!("cat_1").to_static_str());
277+
278+
let cat_1 = "chashu".to_string();
279+
assert_eq!(None, log::__log_key!(cat_1.as_str()).to_static_str());
280+
}
281+
272282
#[test]
273283
#[cfg(feature = "kv")]
274284
fn kv_expr_context() {

0 commit comments

Comments
 (0)