hex-serde-util
This crate provides a convenient approach to serializing/deserializing hex numbers with hex string of several formats.
Examples
use ;
let lower_data: HexUsizeLower = 0x1ausize.into;
let upper_data: HexUsizeUpper = 0x1ausize.into;
let prefix_lower_data: HexUsizePrefixLower = 0x1ausize.into;
let prefix_upper_data: HexUsizePrefixUpper = 0x1ausize.into;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
assert_eq!;
In summary, this crate provides a way to serialize/deserialize hex number from/to hex string with:
- lower case without
0xprefix (1afor example) - upper case without
0xprefix (1Afor example) - lower case with
0xprefix (0x1afor example) - upper case with
0xprefix (0x1Afor example)
Generally, a project may only use one format of hex string, so just use an alias when using this crate in your project for convenience:
use HexUsizePrefixUpper as Hex;
use Deserialize;
Necessity
serde provides many attributes for customizing serialization/deserialization, such as
[serde(serialize_with = "path")][serde(deserialize_with = "path")][serde(with = "module")]
These attributes can be used to work with hex strings, but there are some disadvantages:
-
Boilerplate needed
You need to write some boilerplates in your project to use these attributes.
-
Can't use these attributes when in a wrapper such as
OptionIt is a common practice to use
Optionto wrap some fields if these type may be null when processing. However, if this field is designed to be a hex string, you have to write additional boilerplates for just serializing/deserializing those fields.
This crate handles these problems.
Usages
Just as shown above, users can just use types provided by this crate when serialize/deserialize hex strings with hex numbers. Moreover, these types also implements some convenient traits:
-
Deref,DerefMutAfter deserializing, users can just use these traits to get the real number:
use HexUsizePrefixUpper as Hex; let hex_wrapper = .unwrap; let value = *hex_wrapper; // `value` is 26 with type `usize` assert_eq!; -
From,IntoBefore serializing, users can just use
.intoto construct corresponding types. -
DisplayWhen printing those structs with
println!("{}");, the field is displayed as if it is a hex string:use HexUsizePrefixUpper as Hex; let hex_wrapper: Hex = 0x1a.into; let hex_str = hex_wrapper.to_string; assert_eq!; -
Eq,PartialEq,Ord,PartialOrdFor comparing.