Skip to content

Commit

Permalink
Serialize/deserializer HeaderName as string
Browse files Browse the repository at this point in the history
This is much more convenient, and is also required to implement Object
Store object headers, since they are serialized to JSON.
  • Loading branch information
oscarwcl committed Dec 1, 2023
1 parent b1ba88f commit 8d83eb0
Showing 1 changed file with 35 additions and 4 deletions.
39 changes: 35 additions & 4 deletions async-nats/src/header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -397,7 +397,7 @@ macro_rules! standard_headers {
)+
) => {
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum StandardHeader {
$(
$variant,
Expand Down Expand Up @@ -481,7 +481,7 @@ standard_headers! {
(NatsExpectedStream, NATS_EXPECTED_STREAM, b"Nats-Expected-Stream");
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
struct CustomHeader {
bytes: Bytes,
}
Expand Down Expand Up @@ -518,7 +518,7 @@ impl<'a> From<&'a str> for CustomHeader {
}
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, Serialize, Deserialize)]
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
enum HeaderRepr {
Standard(StandardHeader),
Custom(CustomHeader),
Expand All @@ -533,7 +533,7 @@ enum HeaderRepr {
///
/// `HeaderName` represents standard header names using an `enum`, as such they
/// will not require an allocation for storage.
#[derive(Clone, PartialEq, Eq, Hash, Debug, Serialize, Deserialize)]
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
pub struct HeaderName {
inner: HeaderRepr,
}
Expand Down Expand Up @@ -600,6 +600,26 @@ impl AsRef<str> for HeaderName {
}
}

impl Serialize for HeaderName {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_str(self.as_str())
}
}

impl<'de> Deserialize<'de> for HeaderName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
String::deserialize(deserializer)?
.parse()
.map_err(|e| serde::de::Error::custom(e))
}
}

#[derive(Debug, Clone)]
pub struct ParseHeaderNameError;

Expand Down Expand Up @@ -760,4 +780,15 @@ mod tests {

assert_eq!(a, b);
}

#[test]
fn header_name_serde() {
let raw = "Nats-Stream";
let raw_json = "\"Nats-Stream\"";
let header = HeaderName::from_static(raw);

// ser/de of HeaderName should be the same as raw string
assert_eq!(serde_json::to_string(&header).unwrap(), raw_json);
assert_eq!(serde_json::from_str::<HeaderName>(raw_json).unwrap(), header);
}
}

0 comments on commit 8d83eb0

Please sign in to comment.