Skip to content

Commit 734524b

Browse files
authored
Use Cow<'static, str> for api::Value (open-telemetry#332)
1 parent 866ae41 commit 734524b

File tree

12 files changed

+49
-51
lines changed

12 files changed

+49
-51
lines changed

examples/actix-http/src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ async fn main() -> std::io::Result<()> {
3838
.wrap(Logger::default())
3939
.wrap_fn(move |req, srv| {
4040
tracer.in_span("middleware", move |cx| {
41-
cx.span().set_attribute(Key::new("path").string(req.path()));
41+
cx.span()
42+
.set_attribute(Key::new("path").string(req.path().to_string()));
4243
srv.call(req).with_context(cx)
4344
})
4445
})

examples/actix-udp/src/main.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ async fn main() -> std::io::Result<()> {
3838
.wrap_fn(|req, srv| {
3939
let tracer = global::tracer("request");
4040
tracer.in_span("middleware", move |cx| {
41-
cx.span().set_attribute(Key::new("path").string(req.path()));
41+
cx.span()
42+
.set_attribute(Key::new("path").string(req.path().to_string()));
4243
srv.call(req).with_context(cx)
4344
})
4445
})

opentelemetry-contrib/src/datadog/model/v03.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ pub(crate) fn encode(service_name: &str, spans: Vec<trace::SpanData>) -> Result<
2727
if let Some(Value::String(s)) = span.attributes.get(&Key::new("span.type")) {
2828
rmp::encode::write_map_len(&mut encoded, 11)?;
2929
rmp::encode::write_str(&mut encoded, "type")?;
30-
rmp::encode::write_str(&mut encoded, s.as_str())?;
30+
rmp::encode::write_str(&mut encoded, s.as_ref())?;
3131
} else {
3232
rmp::encode::write_map_len(&mut encoded, 10)?;
3333
}

opentelemetry-contrib/src/datadog/model/v05.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ fn encode_spans(
9494
.unwrap_or(0);
9595

9696
let span_type = match span.attributes.get(&Key::new("span.type")) {
97-
Some(Value::String(s)) => interner.intern(s.as_str()),
97+
Some(Value::String(s)) => interner.intern(s.as_ref()),
9898
_ => interner.intern(""),
9999
};
100100

opentelemetry-jaeger/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ impl Into<jaeger::Tag> for KeyValue {
474474
fn into(self) -> jaeger::Tag {
475475
let KeyValue { key, value } = self;
476476
match value {
477-
Value::String(s) => jaeger::Tag::new(key.into(), jaeger::TagType::String, Some(s), None, None, None, None),
477+
Value::String(s) => jaeger::Tag::new(key.into(), jaeger::TagType::String, Some(s.into()), None, None, None, None),
478478
Value::F64(f) => jaeger::Tag::new(key.into(), jaeger::TagType::Double, None, Some(f.into()), None, None, None),
479479
Value::Bool(b) => jaeger::Tag::new(key.into(), jaeger::TagType::Bool, None, None, Some(b), None, None),
480480
Value::I64(i) => jaeger::Tag::new(key.into(), jaeger::TagType::Long, None, None, None, Some(i), None),

opentelemetry-otlp/src/transform/common.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl From<Value> for AnyValue {
4444
Value::Bool(val) => any_value.set_bool_value(val),
4545
Value::I64(val) => any_value.set_int_value(val),
4646
Value::F64(val) => any_value.set_double_value(val),
47-
Value::String(val) => any_value.set_string_value(val),
47+
Value::String(val) => any_value.set_string_value(val.into_owned()),
4848
Value::Array(vals) => any_value.set_array_value({
4949
let mut array_value = ArrayValue::new();
5050
array_value.set_values(RepeatedField::from_vec(

opentelemetry/src/api/baggage.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ impl Baggage {
3939
/// let mut cc = Baggage::new();
4040
/// let _ = cc.insert("my-name", "my-value");
4141
///
42-
/// assert_eq!(cc.get("my-name"), Some(&Value::String("my-value".to_string())))
42+
/// assert_eq!(cc.get("my-name"), Some(&Value::from("my-value")))
4343
/// ```
4444
pub fn get<T: Into<Key>>(&self, key: T) -> Option<&Value> {
4545
self.inner.get(&key.into()).map(|(value, _metadata)| value)
@@ -55,7 +55,7 @@ impl Baggage {
5555
/// let _ = cc.insert("my-name", "my-value");
5656
///
5757
/// // By default, the metadata is empty
58-
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(Value::String("my-value".to_string()), BaggageMetadata::from(""))))
58+
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(Value::from("my-value"), BaggageMetadata::from(""))))
5959
/// ```
6060
pub fn get_with_metadata<T: Into<Key>>(&self, key: T) -> Option<&(Value, BaggageMetadata)> {
6161
self.inner.get(&key.into())
@@ -74,7 +74,7 @@ impl Baggage {
7474
/// let mut cc = Baggage::new();
7575
/// let _ = cc.insert("my-name", "my-value");
7676
///
77-
/// assert_eq!(cc.get("my-name"), Some(&Value::String("my-value".to_string())))
77+
/// assert_eq!(cc.get("my-name"), Some(&Value::from("my-value")))
7878
/// ```
7979
pub fn insert<K, V>(&mut self, key: K, value: V) -> Option<Value>
8080
where
@@ -98,7 +98,7 @@ impl Baggage {
9898
/// let mut cc = Baggage::new();
9999
/// let _ = cc.insert_with_metadata("my-name", "my-value", "test");
100100
///
101-
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(Value::String("my-value".to_string()), BaggageMetadata::from("test"))))
101+
/// assert_eq!(cc.get_with_metadata("my-name"), Some(&(Value::from("my-value"), BaggageMetadata::from("test"))))
102102
/// ```
103103
pub fn insert_with_metadata<K, V, S>(
104104
&mut self,
@@ -257,7 +257,7 @@ pub trait BaggageExt {
257257
///
258258
/// assert_eq!(
259259
/// cx.baggage().get("my-name"),
260-
/// Some(&Value::String("my-value".to_string())),
260+
/// Some(&Value::from("my-value")),
261261
/// )
262262
/// ```
263263
fn with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
@@ -276,7 +276,7 @@ pub trait BaggageExt {
276276
///
277277
/// assert_eq!(
278278
/// cx.baggage().get("my-name"),
279-
/// Some(&Value::String("my-value".to_string())),
279+
/// Some(&Value::from("my-value")),
280280
/// )
281281
/// ```
282282
fn current_with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(

opentelemetry/src/api/core.rs

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ impl Key {
4444
}
4545

4646
/// Create a `KeyValue` pair for `String` values.
47-
pub fn string<T: Into<String>>(&self, value: T) -> KeyValue {
47+
pub fn string<T: Into<Cow<'static, str>>>(&self, value: T) -> KeyValue {
4848
KeyValue {
4949
key: self.clone(),
5050
value: Value::String(value.into()),
@@ -97,7 +97,7 @@ pub enum Value {
9797
/// f64 values
9898
F64(f64),
9999
/// String values
100-
String(String),
100+
String(Cow<'static, str>),
101101
/// Array of homogeneous values
102102
Array(Vec<Value>),
103103
}
@@ -122,14 +122,20 @@ from_values!(
122122
(bool, Value::Bool);
123123
(i64, Value::I64);
124124
(f64, Value::F64);
125-
(String, Value::String);
126125
(Vec<Value>, Value::Array);
127126
);
128127

129-
impl From<&str> for Value {
130-
/// Convenience method for creating a `Value` from a `&str`.
131-
fn from(value_str: &str) -> Self {
132-
Value::String(value_str.to_string())
128+
impl From<&'static str> for Value {
129+
/// Convenience method for creating a `Value` from a `&'static str`.
130+
fn from(s: &'static str) -> Self {
131+
Value::String(s.into())
132+
}
133+
}
134+
135+
impl From<String> for Value {
136+
/// Convenience method for creating a `Value` from a `String`.
137+
fn from(s: String) -> Self {
138+
Value::String(s.into())
133139
}
134140
}
135141

@@ -141,7 +147,7 @@ impl From<Value> for String {
141147
Value::Bool(value) => value.to_string(),
142148
Value::I64(value) => value.to_string(),
143149
Value::F64(value) => value.to_string(),
144-
Value::String(value) => value,
150+
Value::String(value) => value.into_owned(),
145151
Value::Array(value) => format_value_array_as_string(&value),
146152
}
147153
}
@@ -155,7 +161,7 @@ impl From<&Value> for String {
155161
Value::Bool(value) => value.to_string(),
156162
Value::I64(value) => value.to_string(),
157163
Value::F64(value) => value.to_string(),
158-
Value::String(value) => value.clone(),
164+
Value::String(value) => value.to_string(),
159165
Value::Array(value) => format_value_array_as_string(value),
160166
}
161167
}

opentelemetry/src/exporter/metrics/stdout.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ where
135135
let encoded_inst_labels = if !desc.instrumentation_name().is_empty() {
136136
let inst_labels = LabelSet::from_labels(iter::once(KeyValue::new(
137137
"instrumentation.name",
138-
desc.instrumentation_name(),
138+
desc.instrumentation_name().to_owned(),
139139
)));
140140
inst_labels.encoded(Some(self.label_encoder.as_ref()))
141141
} else {

opentelemetry/src/sdk/env.rs

Lines changed: 14 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! Implementation of `ResourceDetector` to extract a `Resource` from environment
44
//! variables.
55
use crate::sdk::{resource::ResourceDetector, Resource};
6-
use crate::{Key, KeyValue, Value};
6+
use crate::KeyValue;
77
use std::env;
88
use std::time::Duration;
99

@@ -45,28 +45,24 @@ impl Default for EnvResourceDetector {
4545
/// Extract key value pairs and construct a resource from resources string like
4646
/// key1=value1,key2=value2,...
4747
fn construct_otel_resources(s: String) -> Resource {
48-
let mut key_values = vec![];
49-
for entries in s.split_terminator(',') {
50-
let key_value_strs = entries.split('=').map(str::trim).collect::<Vec<&str>>();
51-
if key_value_strs.len() != 2 {
52-
continue;
48+
Resource::new(s.split_terminator(',').filter_map(|entry| {
49+
let mut parts = entry.splitn(2, '=');
50+
let key = parts.next()?.trim();
51+
let value = parts.next()?.trim();
52+
if value.find('=').is_some() {
53+
return None;
5354
}
5455

55-
let key = Key::from(key_value_strs.get(0).unwrap().to_string());
56-
let value = Value::String(key_value_strs.get(1).unwrap().to_string());
57-
58-
key_values.push(KeyValue::new(key, value));
59-
}
60-
61-
Resource::new(key_values)
56+
Some(KeyValue::new(key.to_owned(), value.to_owned()))
57+
}))
6258
}
6359

6460
#[cfg(test)]
6561
mod tests {
6662
use crate::sdk::env::OTEL_RESOURCE_ATTRIBUTES;
6763
use crate::sdk::resource::{Resource, ResourceDetector};
6864
use crate::sdk::EnvResourceDetector;
69-
use crate::{Key, KeyValue, Value};
65+
use crate::{Key, KeyValue};
7066
use std::{env, time};
7167

7268
#[test]
@@ -79,13 +75,10 @@ mod tests {
7975
assert_eq!(
8076
resource,
8177
Resource::new(vec![
82-
KeyValue::new(
83-
Key::new("key".to_string()),
84-
Value::String("value".to_string())
85-
),
86-
KeyValue::new(Key::new("k".to_string()), Value::String("v".to_string())),
87-
KeyValue::new(Key::new("a".to_string()), Value::String("x".to_string())),
88-
KeyValue::new(Key::new("a".to_string()), Value::String("z".to_string()))
78+
KeyValue::new(Key::new("key".to_string()), "value"),
79+
KeyValue::new(Key::new("k".to_string()), "v"),
80+
KeyValue::new(Key::new("a".to_string()), "x"),
81+
KeyValue::new(Key::new("a".to_string()), "z"),
8982
])
9083
);
9184

opentelemetry/src/sdk/propagation/baggage.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -246,7 +246,7 @@ mod tests {
246246
vec![
247247
KeyValue::new("key1", Value::Array(vec![Value::Bool(true), Value::Bool(false)])),
248248
KeyValue::new("key2", Value::Array(vec![Value::I64(123), Value::I64(456)])),
249-
KeyValue::new("key3", Value::Array(vec![Value::String("val1".to_string()), Value::String("val2".to_string())])),
249+
KeyValue::new("key3", Value::Array(vec!["val1".into(), "val2".into()])),
250250
],
251251
vec![
252252
"key1=[true%2Cfalse]",

opentelemetry/src/sdk/resource.rs

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -243,13 +243,10 @@ mod tests {
243243
assert_eq!(
244244
resource,
245245
Resource::new(vec![
246-
KeyValue::new(
247-
Key::new("key".to_string()),
248-
Value::String("value".to_string())
249-
),
250-
KeyValue::new(Key::new("k".to_string()), Value::String("v".to_string())),
251-
KeyValue::new(Key::new("a".to_string()), Value::String("x".to_string())),
252-
KeyValue::new(Key::new("a".to_string()), Value::String("z".to_string()))
246+
KeyValue::new(Key::new("key".to_string()), "value"),
247+
KeyValue::new(Key::new("k".to_string()), "v"),
248+
KeyValue::new(Key::new("a".to_string()), "x"),
249+
KeyValue::new(Key::new("a".to_string()), "z")
253250
])
254251
)
255252
}

0 commit comments

Comments
 (0)