Expand description
Welcome to the ByteArrayOps Library
§Introduction
This is a no_std-compatible library designed for security-by-default byte array operations.
Starting with v0.3.0, security features (memory zeroization, constant-time utilities) are always enabled.
The library provides an ergonomic way to conduct operations on byte arrays for cryptographic and security-sensitive use cases.
§Quick Start Examples
§Creating ByteArrays - Multiple Ways
use byte_array_ops::ByteArray;
use byte_array_ops::errors::ByteArrayError;
fn main() -> Result<(), ByteArrayError> {
// From hex string (with 0x prefix)
let from_hex: ByteArray = "0xdeadbeef".parse()?;
assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
// From binary string (with 0b prefix)
let from_bin: ByteArray = "0b11110000".parse()?;
assert_eq!(from_bin.as_bytes(), [0xf0]);
// From UTF-8 string (no prefix)
let from_utf8: ByteArray = "hello".parse()?;
assert_eq!(from_utf8.as_bytes(), b"hello");
// From byte slice using From trait
let from_slice: ByteArray = [0x01, 0x02, 0x03].as_slice().into();
assert_eq!(from_slice.len(), 3);
// From `Vec<u8>` using From trait
let from_vec: ByteArray = vec![0xaa, 0xbb, 0xcc].into();
assert_eq!(from_vec.as_bytes(), [0xaa, 0xbb, 0xcc]);
// From array literal using From trait
let from_array: ByteArray = [0xff; 4].into();
assert_eq!(from_array.as_bytes(), [0xff, 0xff, 0xff, 0xff]);
// Using static constructor with hex
let with_hex = ByteArray::from_hex("cafe")?;
assert_eq!(with_hex.as_bytes(), [0xca, 0xfe]);
// Using static constructor with binary
let with_bin = ByteArray::from_bin("1010_0101")?;
assert_eq!(with_bin.as_bytes(), [0xa5]);
// NOTE: All ByteArray instances are automatically zeroized when dropped
// to prevent sensitive data from remaining in memory.
Ok(())
}§Macro Examples
CAVEAT: The try_bytes! macro silently converts to UTF-8 when no format prefix (0x, 0b, 0o)
is provided. Use try_hex! or try_bin! for guaranteed hex/binary parsing without format detection.
use byte_array_ops::{try_bytes, try_hex, try_bin, bytes};
use byte_array_ops::errors::ByteArrayError;
fn main() -> Result<(), ByteArrayError> {
// try_bytes! - Parse with format detection (0x/0b prefix or UTF-8)
let from_hex = try_bytes!("0xdeadbeef")?;
assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
let from_bin = try_bytes!("0b11110000")?;
assert_eq!(from_bin.as_bytes(), [0xf0]);
// CAVEAT: No prefix = UTF-8 conversion!
let from_utf8 = try_bytes!("hello")?;
assert_eq!(from_utf8.as_bytes(), b"hello");
// try_hex! - Always parses as hex (no UTF-8 fallback)
let hex_only = try_hex!("cafe")?;
assert_eq!(hex_only.as_bytes(), [0xca, 0xfe]);
// try_bin! - Always parses as binary (no UTF-8 fallback)
let bin_only = try_bin!("11110000")?;
assert_eq!(bin_only.as_bytes(), [0xf0]);
// bytes! - Initialize with repeated pattern (similar to vec![val; count])
let repeated = bytes![0xff; 10];
assert_eq!(repeated.len(), 10);
assert_eq!(repeated.as_bytes(), [0xff; 10]);
Ok(())
}§XOR Encryption Example
SECURITY WARNING: This example demonstrates XOR operations for educational purposes only. DO NOT use XOR for encryption in production. Use established encryption algorithms (AES-GCM, ChaCha20-Poly1305) from properly audited libraries.
use byte_array_ops::ByteArray;
use byte_array_ops::errors::ByteArrayError;
fn main() -> Result<(), ByteArrayError> {
// Encrypt plaintext with a key using XOR
let plaintext: ByteArray = "secret message".parse()?;
let key: ByteArray = "0x_de_ad_be_ef_ca_fe_ba_be_01_02_03_04_05_06".parse()?;
let mut cipher_out = vec![0u8; plaintext.len()];
let encrypted_len = encrypt(plaintext.as_bytes(), key.as_bytes(), &mut cipher_out);
assert_eq!(encrypted_len, plaintext.len());
// Decrypt the ciphertext (XOR is symmetric)
let mut decrypted_out = vec![0u8; encrypted_len];
let decrypted_len = decrypt(&cipher_out[..encrypted_len], key.as_bytes(), &mut decrypted_out);
assert_eq!(&decrypted_out[..decrypted_len], plaintext.as_bytes());
// NOTE: plaintext, key, and result ByteArrays are automatically zeroized
// when dropped to prevent sensitive data from remaining in memory.
Ok(())
}
fn encrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
// Simple XOR encryption (NOT secure, for demonstration only!)
let input_ba: ByteArray = input.into();
let key_ba: ByteArray = key.into();
let result = input_ba ^ key_ba;
let bytes_written = result.len().min(output.len());
output[..bytes_written].copy_from_slice(&result.as_bytes()[..bytes_written]);
bytes_written
// NOTE: input_ba, key_ba, and result are zeroized here when function returns
}
fn decrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
// XOR is symmetric, so decrypt is the same as encrypt
encrypt(input, key, output)
}§Bitwise Operations
use byte_array_ops::ByteArray;
let a: ByteArray = "0xff00".parse().unwrap();
let b: ByteArray = "0x0ff0".parse().unwrap();
// XOR operation
let xor_result = a.clone() ^ b.clone();
assert_eq!(xor_result.as_bytes(), [0xf0, 0xf0]);
// AND operation
let and_result = a.clone() & b.clone();
assert_eq!(and_result.as_bytes(), [0x0f, 0x00]);
// OR operation
let or_result = a.clone() | b.clone();
assert_eq!(or_result.as_bytes(), [0xff, 0xf0]);
// NOT operation
let not_result = !a;
assert_eq!(not_result.as_bytes(), [0x00, 0xff]);
// NOTE: All ByteArrays (a, b, xor_result, and_result, or_result, not_result)
// are automatically zeroized when dropped.
§Array Operations
use byte_array_ops::ByteArray;
fn main() -> Result<(), byte_array_ops::errors::ByteArrayError> {
let mut arr: ByteArray = "0xdeadbeefcafe".parse()?;
// Range indexing (immutable)
assert_eq!(arr[1..3], [0xad, 0xbe]);
assert_eq!(arr[2..], [0xbe, 0xef, 0xca, 0xfe]);
assert_eq!(arr[..2], [0xde, 0xad]);
assert_eq!(arr[1..=3], [0xad, 0xbe, 0xef]);
// Range indexing (mutable)
arr[0..2].copy_from_slice(&[0x00, 0x01]);
assert_eq!(arr[0], 0x00);
// Secure truncate (zeroizes discarded bytes)
arr.truncate(3);
assert_eq!(arr.len(), 3);
Ok(())
}§Module Overview
This library is organized into the following modules:
model- CoreByteArraytype and constructorstype_conv- Type conversion implementations (From,Into,FromStr)ops- Bitwise operations (XOR, AND, OR, NOT)iter- Iterator implementationserrors- Error types for parsing and conversionsmacros- Declarative macros for easyByteArrayconstructionsecurity- Security implementations (display, vec operations, zeroization)
§Key Types
§Core Types
ByteArray- Main byte array type with automatic capacity management
§Iterators
ByteArrayIter- Immutable iterator over bytesByteArrayIterMut- Mutable iterator over bytes
§Error Types
ByteArrayError- Errors during parsing and conversions
§Trait Implementations
ByteArray implements many standard Rust traits for ergonomic usage:
Conversions:
From<&[u8]>,From<Vec<u8>>,From<&Vec<u8>>,From<[u8; N]>- Create from bytesFromStr- Parse from strings (hex with0x, binary with0b, UTF-8 fallback)Into<Vec<u8>>- Extract underlying bytes (zero-cost move)AsRef<[u8]>- Borrow as byte slice
Operations:
BitXor,BitXorAssign- XOR operations (^,^=)BitAnd,BitAndAssign- AND operations (&,&=)BitOr,BitOrAssign- OR operations (|,|=)Not- NOT operation (!)
Iteration:
IntoIterator- Iterate by reference (&ByteArray,&mut ByteArray)ExactSizeIterator- Iterators with known length
Comparison:
PartialEq,Eq- Equality comparisonsClone- Cloning supportDefault- Default constructor (empty array)
Indexing:
Index<usize>,IndexMut<usize>- Array-style indexing (arr[0],arr[1] = 0xff)
§Implementation Notes
Feature Flags: Check Cargo.toml for optional features (ops_simd, experimental).
Security features (zeroization, constant-time utilities) are always enabled starting with v0.3.0.
Security-by-Default: Security dependencies (zeroize, subtle) are now required dependencies.
The trust module provides implementations focused on security while maintaining ergonomic use.
See the [installation_notes][Readme Notes]
Re-exports§
pub use model::ByteArray;
Modules§
- errors
- This module encapsulates all errors that core can throw
- iter
- Iterator implementations for ByteArray
- macros
- model
- This is the main model for our ByteArray Object
- ops
- security
- Security relevant features that need extra attention are bundled here for better maintainability
- type_
conv - This module contains all type conversion definitions to and from
ByteArray - usage_
notes - Repository readme mirror
Macros§
- bytes
- Macro to create a [
ByteArray] with a value and a count similar tovec![val; count] - try_bin
- Macro for creating a
ByteArrayfrom a binary string literal (without0bprefix). - try_
bytes - Macro for creating a
ByteArrayfrom a string literal with automatic format detection. - try_hex
- Macro for creating a
ByteArrayfrom a hexadecimal string literal (without0xprefix).
Traits§
- Zeroize
- Trait for securely erasing values from memory.