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};
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//! Ok(())
87//! }
88//! ```
89//!
90//! ## XOR Encryption Example
91//!
92//! **SECURITY WARNING**: This example demonstrates XOR operations for educational purposes only.
93//! DO NOT use XOR for encryption in production. Use established encryption algorithms
94//! (AES-GCM, ChaCha20-Poly1305) from properly audited libraries.
95//!
96//! ```
97//! use byte_array_ops::ByteArray;
98//! use byte_array_ops::errors::ByteArrayError;
99//!
100//! fn main() -> Result<(), ByteArrayError> {
101//! // Encrypt plaintext with a key using XOR
102//! let plaintext: ByteArray = "secret message".parse()?;
103//! let key: ByteArray = "0x_de_ad_be_ef_ca_fe_ba_be_01_02_03_04_05_06".parse()?;
104//!
105//! let mut cipher_out = vec![0u8; plaintext.len()];
106//! let encrypted_len = encrypt(plaintext.as_bytes(), key.as_bytes(), &mut cipher_out);
107//!
108//! assert_eq!(encrypted_len, plaintext.len());
109//!
110//! // Decrypt the ciphertext (XOR is symmetric)
111//! let mut decrypted_out = vec![0u8; encrypted_len];
112//! let decrypted_len = decrypt(&cipher_out[..encrypted_len], key.as_bytes(), &mut decrypted_out);
113//!
114//! assert_eq!(&decrypted_out[..decrypted_len], plaintext.as_bytes());
115//!
116//! // NOTE: plaintext, key, and result ByteArrays are automatically zeroized
117//! // when dropped to prevent sensitive data from remaining in memory.
118//!
119//! Ok(())
120//! }
121//!
122//! fn encrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
123//! // Simple XOR encryption (NOT secure, for demonstration only!)
124//! let input_ba: ByteArray = input.into();
125//! let key_ba: ByteArray = key.into();
126//! let result = input_ba ^ key_ba;
127//!
128//! let bytes_written = result.len().min(output.len());
129//! output[..bytes_written].copy_from_slice(&result.as_bytes()[..bytes_written]);
130//! bytes_written
131//! // NOTE: input_ba, key_ba, and result are zeroized here when function returns
132//! }
133//!
134//! fn decrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
135//! // XOR is symmetric, so decrypt is the same as encrypt
136//! encrypt(input, key, output)
137//! }
138//! ```
139//!
140//! ## Bitwise Operations
141//!
142//! ```
143//! use byte_array_ops::ByteArray;
144//!
145//!
146//!
147//! let a: ByteArray = "0xff00".parse().unwrap();
148//! let b: ByteArray = "0x0ff0".parse().unwrap();
149//!
150//! // XOR operation
151//! let xor_result = a.clone() ^ b.clone();
152//! assert_eq!(xor_result.as_bytes(), [0xf0, 0xf0]);
153//!
154//! // AND operation
155//! let and_result = a.clone() & b.clone();
156//! assert_eq!(and_result.as_bytes(), [0x0f, 0x00]);
157//!
158//! // OR operation
159//! let or_result = a.clone() | b.clone();
160//! assert_eq!(or_result.as_bytes(), [0xff, 0xf0]);
161//!
162//! // NOT operation
163//! let not_result = !a;
164//! assert_eq!(not_result.as_bytes(), [0x00, 0xff]);
165//!
166//! // NOTE: All ByteArrays (a, b, xor_result, and_result, or_result, not_result)
167//! // are automatically zeroized when dropped.
168//!
169//! ```
170//!
171//! # Module Overview
172//!
173//! This library is organized into the following modules:
174//! - [`model`] - Core [`ByteArray`] type and constructors
175//! - [`type_conv`] - Type conversion implementations (`From`, `Into`, `FromStr`)
176//! - [`ops`] - Bitwise operations (XOR, AND, OR, NOT)
177//! - [`iter`] - Iterator implementations
178//! - [`errors`] - Error types for parsing and conversions
179//! - [`macros`] - Declarative macros for easy [`ByteArray`] construction
180//! - [`security`] - Security implementations (display, vec operations, zeroization)
181//!
182//! # Key Types
183//!
184//! ## Core Types
185//! - [`ByteArray`] - Main byte array type with automatic capacity management
186//!
187//! ## Iterators
188//! - [`ByteArrayIter`](crate::iter::ByteArrayIter) - Immutable iterator over bytes
189//! - [`ByteArrayIterMut`](crate::iter::ByteArrayIterMut) - Mutable iterator over bytes
190//!
191//! ## Error Types
192//! - [`ByteArrayError`](crate::errors::ByteArrayError) - Errors during parsing and conversions
193//!
194//! # Trait Implementations
195//!
196//! `ByteArray` implements many standard Rust traits for ergonomic usage:
197//!
198//! **Conversions**:
199//! - `From<&[u8]>`, `From<Vec<u8>>`, `From<&Vec<u8>>`, `From<[u8; N]>` - Create from bytes
200//! - `FromStr` - Parse from strings (hex with `0x`, binary with `0b`, UTF-8 fallback)
201//! - `Into<Vec<u8>>` - Extract underlying bytes (zero-cost move)
202//! - `AsRef<[u8]>` - Borrow as byte slice
203//!
204//! **Operations**:
205//! - `BitXor`, `BitXorAssign` - XOR operations (`^`, `^=`)
206//! - `BitAnd`, `BitAndAssign` - AND operations (`&`, `&=`)
207//! - `BitOr`, `BitOrAssign` - OR operations (`|`, `|=`)
208//! - `Not` - NOT operation (`!`)
209//!
210//! **Iteration**:
211//! - `IntoIterator` - Iterate by reference (`&ByteArray`, `&mut ByteArray`)
212//! - `ExactSizeIterator` - Iterators with known length
213//!
214//! **Comparison**:
215//! - `PartialEq`, `Eq` - Equality comparisons
216//! - `Clone` - Cloning support
217//! - `Default` - Default constructor (empty array)
218//!
219//! **Indexing**:
220//! - `Index<usize>`, `IndexMut<usize>` - Array-style indexing (`arr[0]`, `arr[1] = 0xff`)
221//!
222//! # Implementation Notes
223//!
224//! **Feature Flags**: Check `Cargo.toml` for optional features (`ops_simd`, `experimental`).
225//! Security features (zeroization, constant-time utilities) are always enabled starting with v0.3.0.
226//!
227//! **Security-by-Default**: Security dependencies (`zeroize`, `subtle`) are now required dependencies.
228//! The `trust` module provides implementations focused on security while maintaining ergonomic use.
229//! See the [`installation_notes`][Readme Notes]
230#![no_std]
231#![deny(unsafe_code)]
232
233/// Repository readme mirror
234#[doc = include_str!("../README.md")]
235pub mod usage_notes {}
236
237#[cfg(feature = "ops_simd")]
238compile_error!("Currently not implemented");
239
240extern crate alloc;
241
242pub(crate) mod common;
243pub mod errors;
244pub mod model;
245
246pub mod iter;
247pub mod macros;
248pub mod ops;
249pub mod type_conv;
250
251pub mod security {
252 pub mod display;
253 pub mod vec;
254 pub mod zeroize;
255}
256
257pub use model::ByteArray;