-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathserde_utils.rs
More file actions
58 lines (52 loc) · 1.88 KB
/
serde_utils.rs
File metadata and controls
58 lines (52 loc) · 1.88 KB
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
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Custom serde serializers for proto types.
//!
//! These are used via `#[serde(serialize_with = "...")]` attributes on generated
//! proto fields to produce human-readable output (hex strings for bytes, enum
//! names for integer enum fields).
use std::fmt::Write;
use serde::Serializer;
/// Generates a serde serializer that converts an `i32` proto enum field to its
/// lowercased string name via `from_i32()` and `as_str_name()`.
macro_rules! stringify_enum_serializer {
($fn_name:ident, $enum_type:ty) => {
pub fn $fn_name<S>(value: &i32, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let name = match <$enum_type>::from_i32(*value) {
Some(v) => v.as_str_name(),
None => "unknown",
};
serializer.serialize_str(&name.to_ascii_lowercase())
}
};
}
stringify_enum_serializer!(serialize_payment_direction, crate::types::PaymentDirection);
stringify_enum_serializer!(serialize_payment_status, crate::types::PaymentStatus);
stringify_enum_serializer!(serialize_balance_source, crate::types::BalanceSource);
/// Serializes `Option<prost::bytes::Bytes>` as a hex string (or null).
pub fn serialize_opt_bytes_hex<S>(
value: &Option<bytes::Bytes>, serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match value {
Some(bytes) => {
let hex = bytes.iter().fold(String::with_capacity(bytes.len() * 2), |mut acc, b| {
let _ = write!(acc, "{b:02x}");
acc
});
serializer.serialize_some(&hex)
},
None => serializer.serialize_none(),
}
}