hexutil
Implement common traits for binary representable data.
Use the impl_hex
macro to implement the ToHex
, FromHex
, Display
, FromStr
, Serialize
and Deserialize
traits.
This can be done by returning a reference to some bytes:
;
impl_hex!;
Or by returning some bytes by value:
;
impl_hex!;
Example
;
impl_hex!;
let test = Test;
// std::fmt::Display
assert_eq!;
// std::string::ToString
let hex = test.to_string;
assert_eq!;
// std::convert::FromStr
let test: Test = hex.parse.unwrap;
assert_eq!;
// hexutil::ToHex
let hex = test.to_hex;
assert_eq!;
// hexutil::FromHex
let test = from_hex.unwrap;
assert_eq!;
// hexutil::ParseHex
let test: Test = hex.parse_hex.unwrap;
assert_eq!;
// serde::Serialize (with serializer.is_human_readable() == true)
let json = to_string.unwrap;
assert_eq!;
// serde::Deserialize (with deserializer.is_human_readable() == true)
let test: Test = from_str.unwrap;
assert_eq!;
// serde::Serialize (with serializer.is_human_readable() == false)
let bin = serialize.unwrap;
assert_eq!;
// serde::Deserialize (with deserializer.is_human_readable() == false)
let test: Test = deserialize.unwrap;
assert_eq!;
Presets
You can append a list of presets what do derive:
Name | Desciption |
---|---|
default |
convert and serde |
convert |
Display and FromStr |
Display |
Implement the std::fmt::Display trait (enables the to_string() method) |
FromStr |
Implement the std::convert::FromStr trait (enables the str.parse() method) |
serde |
Serialize and Deserialize |
Serialize |
Implement the serde::Serialize trait |
Deserialize |
Implement the serde::Deserialize trait |
Derive only the ToHex
, FromHex
, Serialize
and Deserialize
traits:
;
impl_hex!;
FromHex
Error
The second function returns a Result<Self, FromHexError>
:
;
impl_hex!;
Or use FromHexError::InvalidValue
to display a default message:
;
impl_hex!;
One direction only
You can also implement only one direction:
;
impl_to_hex!;
;
impl_from_hex!;
License
Licensed under either of
- Apache License, Version 2.0, (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.