ckb_jsonrpc_types/
bytes.rs

1use ckb_types::{bytes::Bytes, packed};
2use faster_hex::{hex_decode, hex_encode};
3use schemars::JsonSchema;
4use std::fmt;
5
6/// Variable-length binary encoded as a 0x-prefixed hex string in JSON.
7///
8/// ## Example
9///
10/// | JSON       | Binary                               |
11/// | ---------- | ------------------------------------ |
12/// | "0x"       | Empty binary                         |
13/// | "0x00"     | Single byte 0                        |
14/// | "0x636b62" | 3 bytes, UTF-8 encoding of ckb       |
15/// | "00"       | Invalid, 0x is required              |
16/// | "0x0"      | Invalid, each byte requires 2 digits |
17#[derive(Clone, PartialEq, Eq, Hash, Debug, Default)]
18pub struct JsonBytes(Bytes);
19impl JsonSchema for JsonBytes {
20    fn schema_name() -> String {
21        String::from("JsonBytes")
22    }
23    fn json_schema(generate: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
24        generate.subschema_for::<String>().into_object().into()
25    }
26}
27
28impl JsonBytes {
29    /// Creates the `JsonBytes` from `Bytes`.
30    pub fn from_bytes(bytes: Bytes) -> Self {
31        JsonBytes(bytes)
32    }
33
34    /// Creates the `JsonBytes` from `Vec<u8>`.
35    pub fn from_vec(vec: Vec<u8>) -> Self {
36        JsonBytes(Bytes::from(vec))
37    }
38
39    /// Converts into `Bytes`.
40    pub fn into_bytes(self) -> Bytes {
41        let JsonBytes(bytes) = self;
42        bytes
43    }
44
45    /// Gets the number of bytes.
46    pub fn len(&self) -> usize {
47        self.0.len()
48    }
49
50    /// Tells whether this is an empty bytes.
51    pub fn is_empty(&self) -> bool {
52        0 == self.len()
53    }
54
55    /// Gets the underlying slice.
56    pub fn as_bytes(&self) -> &[u8] {
57        &self.0
58    }
59}
60
61impl From<packed::Bytes> for JsonBytes {
62    fn from(input: packed::Bytes) -> Self {
63        JsonBytes::from_vec(input.raw_data().to_vec())
64    }
65}
66
67impl<'a> From<&'a packed::Bytes> for JsonBytes {
68    fn from(input: &'a packed::Bytes) -> Self {
69        JsonBytes::from_vec(input.raw_data().to_vec())
70    }
71}
72
73impl From<JsonBytes> for packed::Bytes {
74    fn from(input: JsonBytes) -> Self {
75        input.0.into()
76    }
77}
78
79struct BytesVisitor;
80
81impl<'b> serde::de::Visitor<'b> for BytesVisitor {
82    type Value = JsonBytes;
83
84    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
85        write!(formatter, "a 0x-prefixed hex string")
86    }
87
88    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
89    where
90        E: serde::de::Error,
91    {
92        if v.len() < 2 || &v.as_bytes()[0..2] != b"0x" {
93            return Err(E::invalid_value(serde::de::Unexpected::Str(v), &self));
94        }
95
96        if v.len() & 1 != 0 {
97            return Err(E::invalid_length(v.len(), &"even length"));
98        }
99
100        let bytes = &v.as_bytes()[2..];
101        if bytes.is_empty() {
102            return Ok(JsonBytes::default());
103        }
104        let mut buffer = vec![0; bytes.len() >> 1]; // we checked length
105        hex_decode(bytes, &mut buffer).map_err(|e| E::custom(format_args!("{e:?}")))?;
106        Ok(JsonBytes::from_vec(buffer))
107    }
108
109    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
110    where
111        E: serde::de::Error,
112    {
113        self.visit_str(&v)
114    }
115}
116
117impl serde::Serialize for JsonBytes {
118    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
119    where
120        S: serde::Serializer,
121    {
122        let mut buffer = vec![0u8; self.len() * 2 + 2];
123        buffer[0] = b'0';
124        buffer[1] = b'x';
125        hex_encode(self.as_bytes(), &mut buffer[2..])
126            .map_err(|e| serde::ser::Error::custom(format!("{e}")))?;
127        serializer.serialize_str(unsafe { ::std::str::from_utf8_unchecked(&buffer) })
128    }
129}
130
131impl<'de> serde::Deserialize<'de> for JsonBytes {
132    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
133    where
134        D: serde::Deserializer<'de>,
135    {
136        deserializer.deserialize_str(BytesVisitor)
137    }
138}