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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
use std::borrow::Cow;
use byteorder::{ByteOrder, LittleEndian};
#[derive(Clone, Debug, PartialEq)]
pub struct RawHeader {
pub name: Cow<'static, [u8]>,
pub data: Cow<'static, [u8]>,
}
impl RawHeader {
pub fn new<N, V>(name: N, data: V) -> Self
where
N: Into<Cow<'static, [u8]>>,
V: Into<Cow<'static, [u8]>>,
{
Self {
name: name.into(),
data: data.into(),
}
}
}
pub trait Header {
fn name() -> &'static [u8];
fn data(&self) -> Cow<'static, [u8]>;
fn into_raw(self) -> RawHeader
where
Self: Sized,
{
RawHeader::new(Self::name(), self.data())
}
}
fn pack_u64(v: u64) -> Vec<u8> {
let mut buf = vec![0; 8];
LittleEndian::write_u64(&mut buf[..], v);
buf
}
#[derive(Clone, Debug, PartialEq)]
pub struct TraceId(pub u64);
impl Header for TraceId {
fn name() -> &'static [u8] {
b"trace_id"
}
fn data(&self) -> Cow<'static, [u8]> {
match *self {
TraceId(v) => pack_u64(v).into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct SpanId(pub u64);
impl Header for SpanId {
fn name() -> &'static [u8] {
b"span_id"
}
fn data(&self) -> Cow<'static, [u8]> {
match *self {
SpanId(v) => pack_u64(v).into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct ParentId(pub u64);
impl Header for ParentId {
fn name() -> &'static [u8] {
b"parent_id"
}
fn data(&self) -> Cow<'static, [u8]> {
match *self {
ParentId(v) => pack_u64(v).into(),
}
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct TraceBit(pub bool);
impl Header for TraceBit {
fn name() -> &'static [u8] {
b"trace_bit"
}
fn data(&self) -> Cow<'static, [u8]> {
if let TraceBit(true) = *self {
b"1"[..].into()
} else {
b"0"[..].into()
}
}
}