byte_array_ops/
lib.rs

1//! Welcome to the ByteArrayOps Library
2//!
3//! # Introduction
4//! This is a `no_std`-compatible library designed to provide an ergonomic and easy way to conduct operations on byte arrays.
5//! It is intended both for general use where data sensitivity is not important and for cryptographic use cases or other cases
6//! where privacy may be of concern.
7//!
8#![doc = include_str!("../README.md")]
9//!
10//! # Quick Start Examples
11//!
12//! ## Creating ByteArrays - Multiple Ways
13//!
14//! ```
15//! use byte_array_ops::ByteArray;
16//! use byte_array_ops::errors::ByteArrayError;
17//!
18//! fn main() -> Result<(), ByteArrayError> {
19//!     // From hex string (with 0x prefix)
20//!     let from_hex: ByteArray = "0xdeadbeef".parse()?;
21//!     assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
22//!
23//!     // From binary string (with 0b prefix)
24//!     let from_bin: ByteArray = "0b11110000".parse()?;
25//!     assert_eq!(from_bin.as_bytes(), [0xf0]);
26//!
27//!     // From UTF-8 string (no prefix)
28//!     let from_utf8: ByteArray = "hello".parse()?;
29//!     assert_eq!(from_utf8.as_bytes(), b"hello");
30//!
31//!     // From byte slice using From trait
32//!     let from_slice: ByteArray = [0x01, 0x02, 0x03].as_slice().into();
33//!     assert_eq!(from_slice.len(), 3);
34//!
35//!     // From `Vec<u8>` using From trait
36//!     let from_vec: ByteArray = vec![0xaa, 0xbb, 0xcc].into();
37//!     assert_eq!(from_vec.as_bytes(), [0xaa, 0xbb, 0xcc]);
38//!
39//!     // From array literal using From trait
40//!     let from_array: ByteArray = [0xff; 4].into();
41//!     assert_eq!(from_array.as_bytes(), [0xff, 0xff, 0xff, 0xff]);
42//!
43//!     // Using static constructor with hex
44//!     let with_hex = ByteArray::from_hex("cafe")?;
45//!     assert_eq!(with_hex.as_bytes(), [0xca, 0xfe]);
46//!
47//!     // Using static constructor with binary
48//!     let with_bin = ByteArray::from_bin("1010_0101")?;
49//!     assert_eq!(with_bin.as_bytes(), [0xa5]);
50//!
51//!     Ok(())
52//! }
53//! ```
54//!
55//! ## Macro Examples
56//!
57//! **CAVEAT**: The `try_bytes!` macro silently converts to UTF-8 when no format prefix (`0x`, `0b`, `0o`)
58//! is provided. Use `try_hex!` or `try_bin!` for guaranteed hex/binary parsing without format detection.
59//!
60//! ```
61//! use byte_array_ops::{try_bytes, try_hex, try_bin};
62//! use byte_array_ops::errors::ByteArrayError;
63//!
64//! fn main() -> Result<(), ByteArrayError> {
65//!     // try_bytes! - Parse with format detection (0x/0b prefix or UTF-8)
66//!     let from_hex = try_bytes!("0xdeadbeef")?;
67//!     assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
68//!
69//!     let from_bin = try_bytes!("0b11110000")?;
70//!     assert_eq!(from_bin.as_bytes(), [0xf0]);
71//!
72//!     // CAVEAT: No prefix = UTF-8 conversion!
73//!     let from_utf8 = try_bytes!("hello")?;
74//!     assert_eq!(from_utf8.as_bytes(), b"hello");
75//!
76//!     // try_hex! - Always parses as hex (no UTF-8 fallback)
77//!     let hex_only = try_hex!("cafe")?;
78//!     assert_eq!(hex_only.as_bytes(), [0xca, 0xfe]);
79//!
80//!     // try_bin! - Always parses as binary (no UTF-8 fallback)
81//!     let bin_only = try_bin!("11110000")?;
82//!     assert_eq!(bin_only.as_bytes(), [0xf0]);
83//!
84//!     Ok(())
85//! }
86//! ```
87//!
88//! ## XOR Encryption Example
89//!
90//! ```
91//! use byte_array_ops::ByteArray;
92//! use byte_array_ops::errors::ByteArrayError;
93//!
94//! fn main() -> Result<(), ByteArrayError> {
95//!     // Encrypt plaintext with a key using XOR
96//!     let plaintext: ByteArray = "secret message".parse()?;
97//!     let key: ByteArray = "0x_de_ad_be_ef_ca_fe_ba_be_01_02_03_04_05_06".parse()?;
98//!
99//!     let mut cipher_out = vec![0u8; plaintext.len()];
100//!     let encrypted_len = encrypt(plaintext.as_bytes(), key.as_bytes(), &mut cipher_out);
101//!
102//!     assert_eq!(encrypted_len, plaintext.len());
103//!
104//!     // Decrypt the ciphertext (XOR is symmetric)
105//!     let mut decrypted_out = vec![0u8; encrypted_len];
106//!     let decrypted_len = decrypt(&cipher_out[..encrypted_len], key.as_bytes(), &mut decrypted_out);
107//!
108//!     assert_eq!(&decrypted_out[..decrypted_len], plaintext.as_bytes());
109//!     Ok(())
110//! }
111//!
112//! fn encrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
113//!     // Simple XOR encryption (NOT secure, for demonstration only!)
114//!     let input_ba: ByteArray = input.into();
115//!     let key_ba: ByteArray = key.into();
116//!     let result = input_ba ^ key_ba;
117//!
118//!     let bytes_written = result.len().min(output.len());
119//!     output[..bytes_written].copy_from_slice(&result.as_bytes()[..bytes_written]);
120//!     bytes_written
121//! }
122//!
123//! fn decrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
124//!     // XOR is symmetric, so decrypt is the same as encrypt
125//!     encrypt(input, key, output)
126//! }
127//! ```
128//!
129//! ## Bitwise Operations
130//!
131//! ```
132//! use byte_array_ops::ByteArray;
133//!
134//! fn main() {
135//!     let a: ByteArray = "0xff00".parse().unwrap();
136//!     let b: ByteArray = "0x0ff0".parse().unwrap();
137//!
138//!     // XOR operation
139//!     let xor_result = a.clone() ^ b.clone();
140//!     assert_eq!(xor_result.as_bytes(), [0xf0, 0xf0]);
141//!
142//!     // AND operation
143//!     let and_result = a.clone() & b.clone();
144//!     assert_eq!(and_result.as_bytes(), [0x0f, 0x00]);
145//!
146//!     // OR operation
147//!     let or_result = a.clone() | b.clone();
148//!     assert_eq!(or_result.as_bytes(), [0xff, 0xf0]);
149//!
150//!     // NOT operation
151//!     let not_result = !a;
152//!     assert_eq!(not_result.as_bytes(), [0x00, 0xff]);
153//! }
154//! ```
155//!
156//! # Module Overview
157//!
158//! This library is organized into the following modules:
159//! - [`core::model`](core::model) - Core [`ByteArray`] type and constructors
160//! - [`core::type_conv`](core::type_conv) - Type conversion implementations (`From`, `Into`, `FromStr`)
161//! - [`core::ops`](core::ops) - Bitwise operations (XOR, AND, OR, NOT) - requires `ops_algebra` feature
162//! - [`core::iter`](core::iter) - Iterator implementations
163//! - [`core::errors`](errors) - Error types for parsing and conversions
164//! - [`core::macros`](macros) - Declarative macros for easy [`ByteArray`] construction
165//! - `core::trust::hardened` - Security-hardened implementations (when hardening features enabled)
166//! - `core::trust::insecure` - Convenience implementations (default mode)
167//!
168//! # Key Types
169//!
170//! ## Core Types
171//! - [`ByteArray`] - Main byte array type with automatic capacity management
172//!
173//! ## Iterators
174//! - [`ByteArrayIter`](crate::core::iter::ByteArrayIter) - Immutable iterator over bytes
175//! - [`ByteArrayIterMut`](crate::core::iter::ByteArrayIterMut) - Mutable iterator over bytes
176//!
177//! ## Error Types
178//! - [`ByteArrayError`](crate::errors::ByteArrayError) - Errors during parsing and conversions
179//!
180//! # Trait Implementations
181//!
182//! `ByteArray` implements many standard Rust traits for ergonomic usage:
183//!
184//! **Conversions**:
185//! - `From<&[u8]>`, `From<Vec<u8>>`, `From<&Vec<u8>>`, `From<[u8; N]>` - Create from bytes
186//! - `FromStr` - Parse from strings (hex with `0x`, binary with `0b`, UTF-8 fallback)
187//! - `Into<Vec<u8>>` - Extract underlying bytes (zero-cost move) in insecure mode
188//! - `AsRef<[u8]>` - Borrow as byte slice
189//!
190//! **Operations** (requires `ops_algebra` feature):
191//! - `BitXor`, `BitXorAssign` - XOR operations (`^`, `^=`)
192//! - `BitAnd`, `BitAndAssign` - AND operations (`&`, `&=`)
193//! - `BitOr`, `BitOrAssign` - OR operations (`|`, `|=`)
194//! - `Not` - NOT operation (`!`)
195//!
196//! **Iteration**:
197//! - `IntoIterator` - Iterate by reference (`&ByteArray`, `&mut ByteArray`)
198//! - `ExactSizeIterator` - Iterators with known length
199//!
200//! **Comparison**:
201//! - `PartialEq`, `Eq` - Equality comparisons
202//! - `Clone` - Cloning support
203//! - `Default` - Default constructor (empty array)
204//!
205//! **Indexing**:
206//! - `Index<usize>`, `IndexMut<usize>` - Array-style indexing (`arr[0]`, `arr[1] = 0xff`)
207//!
208//! # Implementation Notes
209//!
210//! **Feature Flags**: Check `Cargo.toml` for hardening tiers. When implementing features, use individual feature flags
211//! (`sec_harden_zeroize`, `sec_harden_const_time_ops`, etc.) in `#[cfg]` attributes. Tiers (`sec_basic_hardening`,
212//! `sec_enhanced_hardening`, `sec_maximum_hardening`) are convenience bundles for users to activate multiple features at once.
213//!
214//! **Security Hardening**: The `trust` module provides two mutually exclusive implementations:
215//! - Hardened mode (any `sec_harden_*` feature): Restricts operations to prevent data leakage
216//! - Insecure mode (default): Provides full `Vec<u8>` compatibility via Deref
217//! See the Security Hardening Guide below for detailed information.
218#![no_std]
219#![forbid(unsafe_code)]
220
221#[cfg(any(
222    feature = "sec_harden_zeroize",
223    feature = "sec_harden_const_time_ops",
224    feature = "sec_harden_memlock",
225    feature = "sec_harden_memencrypt"
226))]
227compile_error!(
228    "The hardened feature is not yet implemented please deactivate and wait for a future release"
229);
230#[cfg(feature = "ops_simd")]
231compile_error!("Currently not implemented");
232
233extern crate alloc;
234
235pub mod core {
236
237    pub(crate) mod common;
238    pub mod errors;
239    pub mod model;
240
241    pub mod iter;
242    pub mod macros;
243    #[cfg(feature = "ops_algebra")]
244    pub mod ops;
245    pub mod type_conv;
246
247    pub mod trust {
248        #[cfg(any(
249            feature = "sec_harden_zeroize",
250            feature = "sec_harden_memlock",
251            feature = "sec_harden_const_time_ops",
252            feature = "sec_harden_memencrypt"
253        ))]
254        pub mod hardened;
255
256        #[cfg(not(any(
257            feature = "sec_harden_zeroize",
258            feature = "sec_harden_memlock",
259            feature = "sec_harden_const_time_ops",
260            feature = "sec_harden_memencrypt"
261        )))]
262        pub mod insecure;
263    }
264}
265
266#[doc = include_str!("../docs/hardening.md")]
267pub mod security_guide {}
268
269pub use core::errors;
270pub use core::macros;
271pub use core::model::ByteArray;
272