Skip to content

Commit

Permalink
add feature for serializing TraceId as byte array
Browse files Browse the repository at this point in the history
  • Loading branch information
Kouzukii committed Mar 30, 2021
1 parent 90bc7f7 commit a3057cf
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
1 change: 1 addition & 0 deletions tarpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ description = "An RPC framework for Rust with a focus on ease of use."
default = []

serde1 = ["tarpc-plugins/serde1", "serde", "serde/derive"]
serde1-no-u128 = ["serde1"]
tokio1 = ["tokio/rt-multi-thread"]
serde-transport = ["serde1", "tokio1", "tokio-serde/json", "tokio-util/codec"]
tcp = ["tokio/net"]
Expand Down
48 changes: 47 additions & 1 deletion tarpc/src/trace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,10 @@ pub struct Context {
/// A 128-bit UUID identifying a trace. All spans caused by the same originating span share the
/// same trace ID.
#[derive(Debug, Default, PartialEq, Eq, Hash, Clone, Copy)]
#[cfg_attr(feature = "serde1", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(
all(feature = "serde1", not(feature = "serde1-no-u128")),
derive(serde::Serialize, serde::Deserialize)
)]
pub struct TraceId(u128);

/// A 64-bit identifier of a span within a trace. The identifier is unique within the span's trace.
Expand Down Expand Up @@ -95,3 +98,46 @@ impl fmt::Display for SpanId {
Ok(())
}
}

#[cfg(feature = "serde1-no-u128")]
impl serde::Serialize for TraceId {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
use serde::ser::SerializeTupleStruct;
let mut tup = serializer.serialize_tuple_struct("TraceId", 1)?;
tup.serialize_field(&self.0.to_le_bytes())?;
tup.end()
}
}

#[cfg(feature = "serde1-no-u128")]
impl<'de> serde::Deserialize<'de> for TraceId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct Visitor;

impl<'de> serde::de::Visitor<'de> for Visitor {
type Value = TraceId;

fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str("tuple struct TraceId")
}

fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
where
A: serde::de::SeqAccess<'de>,
{
let bytes: [u8; 16] = seq.next_element()?.ok_or_else(|| {
serde::de::Error::invalid_length(0, &"tuple struct TraceId with 1 element")
})?;
Ok(TraceId(u128::from_le_bytes(bytes)))
}
}

deserializer.deserialize_tuple_struct("TraceId", 1, Visitor)
}
}

0 comments on commit a3057cf

Please sign in to comment.