-
Notifications
You must be signed in to change notification settings - Fork 385
/
common.rs
79 lines (71 loc) · 2.51 KB
/
common.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use crate::proto::common::{AnyValue, ArrayValue, KeyValue};
use opentelemetry::sdk::trace::EvictedHashMap;
use opentelemetry::{Array, Value};
use protobuf::RepeatedField;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
pub(crate) struct Attributes(pub(crate) ::protobuf::RepeatedField<crate::proto::common::KeyValue>);
impl From<EvictedHashMap> for Attributes {
fn from(attributes: EvictedHashMap) -> Self {
Attributes(RepeatedField::from_vec(
attributes
.into_iter()
.map(|(key, value)| {
let mut kv: KeyValue = KeyValue::new();
kv.set_key(key.as_str().to_string());
kv.set_value(value.into());
kv
})
.collect(),
))
}
}
impl From<Vec<opentelemetry::KeyValue>> for Attributes {
fn from(kvs: Vec<opentelemetry::KeyValue>) -> Self {
Attributes(RepeatedField::from_vec(
kvs.into_iter()
.map(|api_kv| {
let mut kv: KeyValue = KeyValue::new();
kv.set_key(api_kv.key.as_str().to_string());
kv.set_value(api_kv.value.into());
kv
})
.collect(),
))
}
}
impl From<Value> for AnyValue {
fn from(value: Value) -> Self {
let mut any_value = AnyValue::new();
match value {
Value::Bool(val) => any_value.set_bool_value(val),
Value::I64(val) => any_value.set_int_value(val),
Value::F64(val) => any_value.set_double_value(val),
Value::String(val) => any_value.set_string_value(val.into_owned()),
Value::Array(array) => any_value.set_array_value(match array {
Array::Bool(vals) => array_into_proto(vals),
Array::I64(vals) => array_into_proto(vals),
Array::F64(vals) => array_into_proto(vals),
Array::String(vals) => array_into_proto(vals),
}),
};
any_value
}
}
fn array_into_proto<T>(vals: Vec<T>) -> ArrayValue
where
Value: From<T>,
{
let values = RepeatedField::from_vec(
vals.into_iter()
.map(|val| AnyValue::from(Value::from(val)))
.collect(),
);
let mut array_value = ArrayValue::new();
array_value.set_values(values);
array_value
}
pub(crate) fn to_nanos(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH)
.unwrap_or_else(|_| Duration::from_secs(0))
.as_nanos() as u64
}