Example: bytes_and_address_types

Example

To run this example:

  • Clone the examples repository: git clone git@github.com:alloy-rs/examples.git
  • Run: cargo run --example bytes_and_address_types
//! Example of basic usage of bytes and address types and macros.

use alloy::primitives::{
    address, b128, b256, b512, b64, bytes, fixed_bytes, Address, Bytes, FixedBytes,
};
use eyre::Result;

fn main() -> Result<()> {
    // Bytes type
    let a = bytes!("0123abcd");
    assert_eq!(a, Bytes::from(&[0x01, 0x23, 0xab, 0xcd]));
    assert_eq!(a.len(), 4);

    // Address type
    let b = address!("f39Fd6e51aad88F6F4ce6aB8827279cffFb92266");
    assert_eq!(
        b,
        Address::from(&[
            0xf3, 0x9f, 0xd6, 0xe5, 0x1a, 0xad, 0x88, 0xf6, 0xf4, 0xce, 0x6a, 0xb8, 0x82, 0x72,
            0x79, 0xcf, 0xff, 0xb9, 0x22, 0x66
        ])
    );
    assert_eq!(b.len(), 20);

    // FixedBytes<8> type
    let c = b64!("0102030405060708");
    assert_eq!(c, FixedBytes::from(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]));
    assert_eq!(c.len(), 8);

    // FixedBytes<16> type
    let d = b128!("0102030405060708090a0b0c0d0e0f10");
    assert_eq!(
        d,
        FixedBytes::from(&[
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10,
        ])
    );
    assert_eq!(d.len(), 16);

    // FixedBytes<32> type
    let e = b256!("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20");
    assert_eq!(
        e,
        FixedBytes::from(&[
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
            0x1d, 0x1e, 0x1f, 0x20,
        ]),
    );
    assert_eq!(e.len(), 32);

    // FixedBytes<64> type
    let f = b512!("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f40");
    assert_eq!(
        f,
        FixedBytes::from(&[
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c,
            0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a,
            0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
            0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
        ]),
    );
    assert_eq!(f.len(), 64);

    // FixedBytes<20> type, determined by the length of the input
    let g = fixed_bytes!("0102030405060708090a0b0c0d0e0f1011121314");
    assert_eq!(
        g,
        FixedBytes::from(&[
            0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e,
            0x0f, 0x10, 0x11, 0x12, 0x13, 0x14,
        ]),
    );
    assert_eq!(g.len(), 20);

    Ok(())
}

Find the source code on Github here.