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
use data_encoding::{HEXLOWER_PERMISSIVE, DecodeError};
#[cfg(feature = "serde")]
use serde::{Serialize, Serializer};
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")]
impl Serialize for SpanId {
fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
s.collect_str(self)
}
}
impl SpanId {
pub fn bytes(&self) -> &[u8] {
&self.buf
}
}
impl From<[u8; 8]> for SpanId {
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,
}
}
}