hex

repository·main·Indexed 42 days ago

https://github.com/kokakiwi/rust-hex

A lightweight Rust library for encoding and decoding data to and from hexadecimal strings. Version 0.4.3 supports high-level convenience functions, low-level trait-based APIs, and optional Serde integration. It is compatible with no_std environments and requires Rust 1.85 as the minimum supported version.

Tokens
2.9K
Snippets
19
Records
21
Agent score
70%

What's inside hex

  1. Configure hex for no_std environments

    main

    To use hex in a no_std environment, disable the default features in your Cargo.toml. Note that if you need support for allocation types like String in a no_std environment, you should ensure the alloc feature is enabled (it is enabled by default unless you explicitly disable all features).

    [dependencies]
    hex = { version = "0.4", default-features = false }
  2. Serialize and deserialize hex data with Serde

    main

    The hex module provides helper functions to integrate hex encoding/decoding with serde. This allows you to use the #[serde(with = "hex")] attribute on fields to automatically convert between raw bytes (like Vec<u8> or &[u8]) and hex-encoded strings during serialization and deserialization.

    Serialization

    • serialize: Encodes data into a lowercase hex string (e.g., f9b4ca). Requires the alloc feature.
    • serialize_upper: Encodes data into an uppercase hex string (e.g., F9B4CA). Requires the alloc feature.

    Deserialization

    • deserialize: Converts a hex string back into the target type. It accepts both uppercase and lowercase characters, and mixed casing is supported (e.g., f9B4Ca).

    Note: Serialization functions require the alloc feature to be enabled.

    use serde::{Serialize, Deserialize};
    
    #[derive(Serialize, Deserialize)]
    struct Foo {
        #[serde(with = "hex")]
        bar: Vec<u8>,
    }
  3. Decode a hexadecimal string

    main

    Use hex::decode to convert a hexadecimal string back into bytes. This typically returns a Result<Vec<u8>, DecodeError>, so you will need to handle potential errors (e.g., using .unwrap() or proper error handling) before converting the bytes back into a usable format like a String.

    let decoded_string = String::from_utf8(hex::decode("48656c6c6f20776f726c6421").unwrap()).unwrap();
    
    println!("{}", decoded_string); // Prints "Hello world!"
  4. Encode data to a hexadecimal string

    main

    Use hex::encode to convert a string or byte slice into its hexadecimal representation.

    let hex_string = hex::encode("Hello world!");
    
    println!("{}", hex_string); // Prints "48656c6c6f20776f726c6421"
  5. Reference the hex crate features

    main

    The hex crate provides several feature flags to control its capabilities:

    • std: Enabled by default. Adds support for Rust's libstd types.
    • alloc: Enabled by default. Adds support for alloc types (e.g., String) in no_std environments.
    • serde: Disabled by default. Adds support for the serde serialization/deserialization library.
  6. Check the Minimum Supported Rust Version (MSRV)

    main

    The hex crate follows an MSRV policy tied to the current stable Debian release to ensure compatibility with stable Linux distributions. As of the current version, the MSRV is Rust 1.85 (matching Debian Trixie stable).

    You can verify the current requirement by checking the rust-version field in Cargo.toml or by checking the current stable Rust version provided by Debian at https://packages.debian.org/stable/rustc.

    [package]
    rust-version = "1.85"
  7. Encode data to an uppercase hex string with `encode_upper()`

    main

    Use encode_upper() to convert a byte slice or any type implementing AsRef<[u8]> into an uppercase hex String. This requires the alloc feature.

    assert_eq!(hex::encode_upper("Hello world!"), "48656C6C6F20776F726C6421");
    assert_eq!(hex::encode_upper(vec![1, 2, 3, 15, 16]), "0102030F10");
  8. Use `hex::serialize_upper` for uppercase hex serialization

    main

    When the alloc feature is enabled, use serialize_upper to convert a type implementing ToHex into an uppercase hex string during Serde serialization.

    #[cfg(feature = "alloc")]
    pub fn serialize_upper<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
        T: ToHex,
  9. Encode bytes into a mutable slice with `encode_to_slice()`

    main

    Encodes bytes into a mutable slice of bytes using lowercase characters.

    Constraints:

    • The output buffer must be exactly input.len() * 2 bytes long. If the buffer is larger or smaller, it returns Err(FromHexError::InvalidStringLength).
    let mut bytes = [0u8; 4 * 2];
    hex::encode_to_slice(b"kiwi", &mut bytes).unwrap();
    assert_eq!(&bytes, b"6b697769");
  10. Decode hex into a mutable slice with `decode_to_slice()`

    main

    Decodes a hex string into a provided mutable byte slice.

    Constraints:

    • The input hex string length must be exactly twice the length of the output slice.
    • The input hex string must have an even length.

    Returns Err(FromHexError::InvalidStringLength) if the lengths do not match correctly.

    let mut bytes = [0u8; 4];
    hex::decode_to_slice("6b697769", &mut bytes).unwrap();
    assert_eq!(&bytes, b"kiwi");
  11. Encode data to a hex string with `encode()`

    main

    Use encode() to convert a byte slice or any type implementing AsRef<[u8]> into a lowercase hex String. This requires the alloc feature.

    Note: The resulting string's length is always even, containing exactly twice as many characters as the input data has bytes.

    assert_eq!(hex::encode("Hello world!"), "48656c6c6f20776f726c6421");
    assert_eq!(hex::encode(vec![1, 2, 3, 15, 16]), "0102030f10");