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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use data_encoding::{DecodeError, HEXLOWER_PERMISSIVE};
use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SpanId {
buf: [u8; 8],
}
impl FromStr for SpanId {
type Err = SpanIdParseError;
fn from_str(s: &str) -> Result<SpanId, SpanIdParseError> {
let mut buf = [0; 8];
match HEXLOWER_PERMISSIVE.decode_len(s.len()) {
Ok(8) => {
HEXLOWER_PERMISSIVE
.decode_mut(s.as_bytes(), &mut buf)
.map_err(|e| SpanIdParseError(Some(e.error)))?;
}
_ => return Err(SpanIdParseError(None)),
}
Ok(SpanId { buf })
}
}
impl fmt::Display for SpanId {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
for b in self.bytes() {
write!(fmt, "{:02x}", b)?;
}
Ok(())
}
}
#[cfg(feature = "serde")]
mod serde {
use serde::de::{Error, Unexpected, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use span_id::SpanId;
impl Serialize for SpanId {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.collect_str(self)
}
}
impl<'de> Deserialize<'de> for SpanId {
fn deserialize<D>(d: D) -> Result<SpanId, D::Error>
where
D: Deserializer<'de>,
{
d.deserialize_str(V)
}
}
struct V;
impl<'de> Visitor<'de> for V {
type Value = SpanId;
fn expecting(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.write_str("a hex-encoded span ID")
}
fn visit_str<E>(self, v: &str) -> Result<SpanId, E>
where
E: Error,
{
v.parse()
.map_err(|_| Error::invalid_value(Unexpected::Str(v), &self))
}
}
}
impl SpanId {
#[inline]
pub fn bytes(&self) -> &[u8] {
&self.buf
}
}
impl From<[u8; 8]> for SpanId {
#[inline]
fn from(bytes: [u8; 8]) -> SpanId {
SpanId { buf: bytes }
}
}
#[derive(Debug)]
pub struct SpanIdParseError(Option<DecodeError>);
impl fmt::Display for SpanIdParseError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
write!(fmt, "{}: ", self.description())?;
match self.0 {
Some(ref err) => write!(fmt, "{}", err),
None => fmt.write_str("invalid length"),
}
}
}
impl Error for SpanIdParseError {
fn description(&self) -> &str {
"error parsing span ID"
}
fn cause(&self) -> Option<&Error> {
match self.0 {
Some(ref e) => Some(e),
None => None,
}
}
}