byte_array_ops/
lib.rs

1//! Welcome to the ByteArrayOps Library
2//!
3//! # Introduction
4//! This is a `no_std`-compatible library designed for **security-by-default** byte array operations.
5//! Starting with v0.3.0, security features (memory zeroization, constant-time utilities) are always enabled.
6//! The library provides an ergonomic way to conduct operations on byte arrays for cryptographic and security-sensitive use cases.
7//!
8//!
9//! # Quick Start Examples
10//!
11//! ## Creating ByteArrays - Multiple Ways
12//!
13//! ```
14//! use byte_array_ops::ByteArray;
15//! use byte_array_ops::errors::ByteArrayError;
16//!
17//! fn main() -> Result<(), ByteArrayError> {
18//!     // From hex string (with 0x prefix)
19//!     let from_hex: ByteArray = "0xdeadbeef".parse()?;
20//!     assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
21//!
22//!     // From binary string (with 0b prefix)
23//!     let from_bin: ByteArray = "0b11110000".parse()?;
24//!     assert_eq!(from_bin.as_bytes(), [0xf0]);
25//!
26//!     // From UTF-8 string (no prefix)
27//!     let from_utf8: ByteArray = "hello".parse()?;
28//!     assert_eq!(from_utf8.as_bytes(), b"hello");
29//!
30//!     // From byte slice using From trait
31//!     let from_slice: ByteArray = [0x01, 0x02, 0x03].as_slice().into();
32//!     assert_eq!(from_slice.len(), 3);
33//!
34//!     // From `Vec<u8>` using From trait
35//!     let from_vec: ByteArray = vec![0xaa, 0xbb, 0xcc].into();
36//!     assert_eq!(from_vec.as_bytes(), [0xaa, 0xbb, 0xcc]);
37//!
38//!     // From array literal using From trait
39//!     let from_array: ByteArray = [0xff; 4].into();
40//!     assert_eq!(from_array.as_bytes(), [0xff, 0xff, 0xff, 0xff]);
41//!
42//!     // Using static constructor with hex
43//!     let with_hex = ByteArray::from_hex("cafe")?;
44//!     assert_eq!(with_hex.as_bytes(), [0xca, 0xfe]);
45//!
46//!     // Using static constructor with binary
47//!     let with_bin = ByteArray::from_bin("1010_0101")?;
48//!     assert_eq!(with_bin.as_bytes(), [0xa5]);
49//!
50//!     // NOTE: All ByteArray instances are automatically zeroized when dropped
51//!     // to prevent sensitive data from remaining in memory.
52//!
53//!     Ok(())
54//! }
55//! ```
56//!
57//! ## Macro Examples
58//!
59//! **CAVEAT**: The `try_bytes!` macro silently converts to UTF-8 when no format prefix (`0x`, `0b`, `0o`)
60//! is provided. Use `try_hex!` or `try_bin!` for guaranteed hex/binary parsing without format detection.
61//!
62//! ```
63//! use byte_array_ops::{try_bytes, try_hex, try_bin, bytes};
64//! use byte_array_ops::errors::ByteArrayError;
65//!
66//! fn main() -> Result<(), ByteArrayError> {
67//!     // try_bytes! - Parse with format detection (0x/0b prefix or UTF-8)
68//!     let from_hex = try_bytes!("0xdeadbeef")?;
69//!     assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
70//!
71//!     let from_bin = try_bytes!("0b11110000")?;
72//!     assert_eq!(from_bin.as_bytes(), [0xf0]);
73//!
74//!     // CAVEAT: No prefix = UTF-8 conversion!
75//!     let from_utf8 = try_bytes!("hello")?;
76//!     assert_eq!(from_utf8.as_bytes(), b"hello");
77//!
78//!     // try_hex! - Always parses as hex (no UTF-8 fallback)
79//!     let hex_only = try_hex!("cafe")?;
80//!     assert_eq!(hex_only.as_bytes(), [0xca, 0xfe]);
81//!
82//!     // try_bin! - Always parses as binary (no UTF-8 fallback)
83//!     let bin_only = try_bin!("11110000")?;
84//!     assert_eq!(bin_only.as_bytes(), [0xf0]);
85//!
86//!     // bytes! - Initialize with repeated pattern (similar to vec![val; count])
87//!     let repeated = bytes![0xff; 10];
88//!     assert_eq!(repeated.len(), 10);
89//!     assert_eq!(repeated.as_bytes(), [0xff; 10]);
90//!
91//!     Ok(())
92//! }
93//! ```
94//!
95//! ## XOR Encryption Example
96//!
97//! **SECURITY WARNING**: This example demonstrates XOR operations for educational purposes only.
98//! DO NOT use XOR for encryption in production. Use established encryption algorithms
99//! (AES-GCM, ChaCha20-Poly1305) from properly audited libraries.
100//!
101//! ```
102//! use byte_array_ops::ByteArray;
103//! use byte_array_ops::errors::ByteArrayError;
104//!
105//! fn main() -> Result<(), ByteArrayError> {
106//!     // Encrypt plaintext with a key using XOR
107//!     let plaintext: ByteArray = "secret message".parse()?;
108//!     let key: ByteArray = "0x_de_ad_be_ef_ca_fe_ba_be_01_02_03_04_05_06".parse()?;
109//!
110//!     let mut cipher_out = vec![0u8; plaintext.len()];
111//!     let encrypted_len = encrypt(plaintext.as_bytes(), key.as_bytes(), &mut cipher_out);
112//!
113//!     assert_eq!(encrypted_len, plaintext.len());
114//!
115//!     // Decrypt the ciphertext (XOR is symmetric)
116//!     let mut decrypted_out = vec![0u8; encrypted_len];
117//!     let decrypted_len = decrypt(&cipher_out[..encrypted_len], key.as_bytes(), &mut decrypted_out);
118//!
119//!     assert_eq!(&decrypted_out[..decrypted_len], plaintext.as_bytes());
120//!
121//!     // NOTE: plaintext, key, and result ByteArrays are automatically zeroized
122//!     // when dropped to prevent sensitive data from remaining in memory.
123//!
124//!     Ok(())
125//! }
126//!
127//! fn encrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
128//!     // Simple XOR encryption (NOT secure, for demonstration only!)
129//!     let input_ba: ByteArray = input.into();
130//!     let key_ba: ByteArray = key.into();
131//!     let result = input_ba ^ key_ba;
132//!
133//!     let bytes_written = result.len().min(output.len());
134//!     output[..bytes_written].copy_from_slice(&result.as_bytes()[..bytes_written]);
135//!     bytes_written
136//!     // NOTE: input_ba, key_ba, and result are zeroized here when function returns
137//! }
138//!
139//! fn decrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
140//!     // XOR is symmetric, so decrypt is the same as encrypt
141//!     encrypt(input, key, output)
142//! }
143//! ```
144//!
145//! ## Bitwise Operations
146//!
147//! ```
148//! use byte_array_ops::ByteArray;
149//!
150//!
151//!
152//! let a: ByteArray = "0xff00".parse().unwrap();
153//! let b: ByteArray = "0x0ff0".parse().unwrap();
154//!
155//! // XOR operation
156//! let xor_result = a.clone() ^ b.clone();
157//! assert_eq!(xor_result.as_bytes(), [0xf0, 0xf0]);
158//!
159//! // AND operation
160//! let and_result = a.clone() & b.clone();
161//! assert_eq!(and_result.as_bytes(), [0x0f, 0x00]);
162//!
163//! // OR operation
164//! let or_result = a.clone() | b.clone();
165//! assert_eq!(or_result.as_bytes(), [0xff, 0xf0]);
166//!
167//! // NOT operation
168//! let not_result = !a;
169//! assert_eq!(not_result.as_bytes(), [0x00, 0xff]);
170//!
171//! // NOTE: All ByteArrays (a, b, xor_result, and_result, or_result, not_result)
172//! // are automatically zeroized when dropped.
173//!
174//! ```
175//!
176//! ## Array Operations
177//!
178//! ```
179//! use byte_array_ops::ByteArray;
180//!
181//! fn main() -> Result<(), byte_array_ops::errors::ByteArrayError> {
182//!     let mut arr: ByteArray = "0xdeadbeefcafe".parse()?;
183//!
184//!     // Range indexing (immutable)
185//!     assert_eq!(arr[1..3], [0xad, 0xbe]);
186//!     assert_eq!(arr[2..], [0xbe, 0xef, 0xca, 0xfe]);
187//!     assert_eq!(arr[..2], [0xde, 0xad]);
188//!     assert_eq!(arr[1..=3], [0xad, 0xbe, 0xef]);
189//!
190//!     // Range indexing (mutable)
191//!     arr[0..2].copy_from_slice(&[0x00, 0x01]);
192//!     assert_eq!(arr[0], 0x00);
193//!
194//!     // Secure truncate (zeroizes discarded bytes)
195//!     arr.truncate(3);
196//!     assert_eq!(arr.len(), 3);
197//!
198//!     Ok(())
199//! }
200//! ```
201//!
202//! # Module Overview
203//!
204//! This library is organized into the following modules:
205//! - [`model`] - Core [`ByteArray`] type and constructors
206//! - [`type_conv`] - Type conversion implementations (`From`, `Into`, `FromStr`)
207//! - [`ops`] - Bitwise operations (XOR, AND, OR, NOT)
208//! - [`iter`] - Iterator implementations
209//! - [`errors`] - Error types for parsing and conversions
210//! - [`macros`] - Declarative macros for easy [`ByteArray`] construction
211//! - [`security`] - Security implementations (display, vec operations, zeroization)
212//!
213//! # Key Types
214//!
215//! ## Core Types
216//! - [`ByteArray`] - Main byte array type with automatic capacity management
217//!
218//! ## Iterators
219//! - [`ByteArrayIter`](crate::iter::ByteArrayIter) - Immutable iterator over bytes
220//! - [`ByteArrayIterMut`](crate::iter::ByteArrayIterMut) - Mutable iterator over bytes
221//!
222//! ## Error Types
223//! - [`ByteArrayError`](crate::errors::ByteArrayError) - Errors during parsing and conversions
224//!
225//! # Trait Implementations
226//!
227//! `ByteArray` implements many standard Rust traits for ergonomic usage:
228//!
229//! **Conversions**:
230//! - `From<&[u8]>`, `From<Vec<u8>>`, `From<&Vec<u8>>`, `From<[u8; N]>` - Create from bytes
231//! - `FromStr` - Parse from strings (hex with `0x`, binary with `0b`, UTF-8 fallback)
232//! - `Into<Vec<u8>>` - Extract underlying bytes (zero-cost move)
233//! - `AsRef<[u8]>` - Borrow as byte slice
234//!
235//! **Operations**:
236//! - `BitXor`, `BitXorAssign` - XOR operations (`^`, `^=`)
237//! - `BitAnd`, `BitAndAssign` - AND operations (`&`, `&=`)
238//! - `BitOr`, `BitOrAssign` - OR operations (`|`, `|=`)
239//! - `Not` - NOT operation (`!`)
240//!
241//! **Iteration**:
242//! - `IntoIterator` - Iterate by reference (`&ByteArray`, `&mut ByteArray`)
243//! - `ExactSizeIterator` - Iterators with known length
244//!
245//! **Comparison**:
246//! - `PartialEq`, `Eq` - Equality comparisons
247//! - `Clone` - Cloning support
248//! - `Default` - Default constructor (empty array)
249//!
250//! **Indexing**:
251//! - `Index<usize>`, `IndexMut<usize>` - Array-style indexing (`arr[0]`, `arr[1] = 0xff`)
252//!
253//! # Implementation Notes
254//!
255//! **Feature Flags**: Check `Cargo.toml` for optional features (`ops_simd`, `experimental`).
256//! Security features (zeroization, constant-time utilities) are always enabled starting with v0.3.0.
257//!
258//! **Security-by-Default**: Security dependencies (`zeroize`, `subtle`) are now required dependencies.
259//! The `trust` module provides implementations focused on security while maintaining ergonomic use.
260//! See the [`installation_notes`][Readme Notes]
261#![no_std]
262#![deny(unsafe_code)]
263
264/// Repository readme mirror
265#[doc = include_str!("../README.md")]
266pub mod usage_notes {}
267
268extern crate alloc;
269
270pub(crate) mod common;
271pub mod errors;
272pub mod model;
273
274pub mod iter;
275pub mod macros;
276pub mod ops;
277pub mod type_conv;
278
279pub mod security;
280
281pub use model::ByteArray;
282pub use zeroize::Zeroize;