Skip to main content

hex/
serde.rs

1//! Serde `serialize`/`deserialize` helpers for hex-encoded byte buffers.
2//!
3//! Use with `#[serde(with = "hex")]` on [`Vec<u8>`] fields:
4//!
5//! ```rust,ignore
6//! use serde::{Serialize, Deserialize};
7//!
8//! #[derive(Serialize, Deserialize)]
9//! struct Foo {
10//!     #[serde(with = "hex")]
11//!     bar: Vec<u8>,
12//! }
13//! ```
14//!
15//! In human-readable formats (e.g. JSON) the field is serialized as a hex
16//! string. In binary formats the raw bytes are used directly.
17
18use alloc::vec::Vec;
19use core::fmt;
20
21use serde::{
22    Deserializer, Serializer,
23    de::{self, Visitor},
24};
25
26use crate::{decode, encode};
27
28/// Serializes `data` to a hex string (human-readable) or raw bytes
29/// (binary formats).
30///
31/// Typically used via `#[serde(with = "hex")]`. See the [module-level
32/// documentation](self) for a full example.
33pub fn serialize<S: Serializer>(data: &[u8], serializer: S) -> Result<S::Ok, S::Error> {
34    if serializer.is_human_readable() {
35        serializer.serialize_str(&encode(data))
36    } else {
37        serializer.serialize_bytes(data)
38    }
39}
40
41/// Deserializes a hex string (human-readable) or raw bytes (binary
42/// formats) into a [`Vec<u8>`].
43///
44/// Usually used via `#[serde(with = "hex")]`.
45pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result<Vec<u8>, D::Error> {
46    if deserializer.is_human_readable() {
47        deserializer.deserialize_str(HexVisitor)
48    } else {
49        deserializer.deserialize_bytes(HexVisitor)
50    }
51}
52
53struct HexVisitor;
54
55impl<'de> Visitor<'de> for HexVisitor {
56    type Value = Vec<u8>;
57
58    fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
59        f.write_str("a hex string")
60    }
61
62    fn visit_str<E: de::Error>(self, v: &str) -> Result<Vec<u8>, E> {
63        decode(v.as_bytes()).map_err(de::Error::custom)
64    }
65
66    fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Vec<u8>, E> {
67        Ok(v.to_vec())
68    }
69}