Crates.io | easy-hex |
lib.rs | easy-hex |
version | 1.0.0 |
source | src |
created_at | 2023-06-18 22:32:37.963223 |
updated_at | 2023-12-05 18:11:59.990661 |
description | An easy to use Hex string formatting wrapper |
homepage | |
repository | https://github.com/Kimundi/easy-hex |
max_upload_size | |
id | 893660 |
size | 38,040 |
An easy to use Hex-String formatting wrapper.
The goal of this library is to make it very easy to format or serialize any container of bytes as a hexadecimal string. This includes vectors, arrays, slices, etc. Example:
use easy_hex::Hex;
let hex = Hex([1, 16, 255]);
let json = serde_json::to_string(&hex).unwrap();
assert_eq!(json, r#""0110ff""#);
TryFrom<&[u8]>
and AsRef<[u8]>
.serde
: Any byte container can be easily serialized as
a hex string.std
formatting: Any byte container can be easily formatted as
a hex string.bytemuck
: Allows safely casting between wrapper and wrapped type,
and allows casting of references to the wrapper.The API of this crate aims to support as many types as possible:
T: AsRef<[u8]>
.T: TryFrom<&[u8]>
.This covers, among other things, these types:
Vec<u8>
[u8]
[u8; N]
Box<[u8]>
&[u8]
&Vec<u8>
&mut [u8; N]
GenericArray<u8, N>
(Although this type currently only supports serialization, due to a missing TryFrom
impl)Note the explicit support of dynamically sized types like [u8]
.
They are possible because of the transparent
representation:
use easy_hex::Hex;
let data: &[u8] = &[1, 2, 3];
let hex: &Hex<[u8]> = data.into();
There are many hex string formatting crates already, and this one does not aim to be better than any of them.
The main reason this exists is that the author wanted a reusable crate for hex string serialization with minimal boilerplate.
No particular performance benchmarks or optimizations have been applied to this crate so far. The properties of the implementation are:
hex
crate.Serializing byte vectors as hex strings:
use easy_hex::Hex;
use serde_derive::{Serialize, Deserialize};
#[derive(Serialize, Deserialize)]
struct Example {
// With wrapper
array: Hex<[u8; 16]>,
// Without wrapper
#[serde(with = "easy_hex::serde")]
vec: Vec<u8>
}
Formatting bytes as hex:
use easy_hex::{Hex, HexExt};
let data: [u8; 4] = [222, 173, 190, 239];
// Format by creating a temporary `&Hex<[u8; N]>`
let out = format!("contents of data: {}", data.as_hex());
assert_eq!(out, "contents of data: deadbeef");
// Format by wrapping the data explicitly
let hex = Hex(data);
println!("display: {hex}");
println!("debug: {hex:?}");
println!("explicit lower: {hex:x}");
println!("explicit upper: {hex:X}");