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//! ```
58//! use byte_array_ops::{try_bytes, try_hex, try_bin};
59//! use byte_array_ops::errors::ByteArrayError;
60//!
61//! fn main() -> Result<(), ByteArrayError> {
62//!     // try_bytes! - Parse with format detection (0x/0b prefix or UTF-8)
63//!     let from_hex = try_bytes!("0xdeadbeef")?;
64//!     assert_eq!(from_hex.as_bytes(), [0xde, 0xad, 0xbe, 0xef]);
65//!
66//!     let from_bin = try_bytes!("0b11110000")?;
67//!     assert_eq!(from_bin.as_bytes(), [0xf0]);
68//!
69//!     let from_utf8 = try_bytes!("hello")?;
70//!     assert_eq!(from_utf8.as_bytes(), b"hello");
71//!
72//!     // try_hex! - Parse as hex without prefix
73//!     let hex_only = try_hex!("cafe")?;
74//!     assert_eq!(hex_only.as_bytes(), [0xca, 0xfe]);
75//!
76//!     // try_bin! - Parse as binary without prefix
77//!     let bin_only = try_bin!("11110000")?;
78//!     assert_eq!(bin_only.as_bytes(), [0xf0]);
79//!
80//!     Ok(())
81//! }
82//! ```
83//!
84//! ## XOR Encryption Example
85//!
86//! ```
87//! use byte_array_ops::ByteArray;
88//! use byte_array_ops::errors::ByteArrayError;
89//!
90//! fn main() -> Result<(), ByteArrayError> {
91//!     // Encrypt plaintext with a key using XOR
92//!     let plaintext: ByteArray = "secret message".parse()?;
93//!     let key: ByteArray = "0x_de_ad_be_ef_ca_fe_ba_be_01_02_03_04_05_06".parse()?;
94//!
95//!     let mut cipher_out = vec![0u8; plaintext.len()];
96//!     let encrypted_len = encrypt(plaintext.as_bytes(), key.as_bytes(), &mut cipher_out);
97//!
98//!     assert_eq!(encrypted_len, plaintext.len());
99//!
100//!     // Decrypt the ciphertext (XOR is symmetric)
101//!     let mut decrypted_out = vec![0u8; encrypted_len];
102//!     let decrypted_len = decrypt(&cipher_out[..encrypted_len], key.as_bytes(), &mut decrypted_out);
103//!
104//!     assert_eq!(&decrypted_out[..decrypted_len], plaintext.as_bytes());
105//!     Ok(())
106//! }
107//!
108//! fn encrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
109//!     // Simple XOR encryption (NOT secure, for demonstration only!)
110//!     let input_ba: ByteArray = input.into();
111//!     let key_ba: ByteArray = key.into();
112//!     let result = input_ba ^ key_ba;
113//!
114//!     let bytes_written = result.len().min(output.len());
115//!     output[..bytes_written].copy_from_slice(&result.as_bytes()[..bytes_written]);
116//!     bytes_written
117//! }
118//!
119//! fn decrypt(input: &[u8], key: &[u8], output: &mut [u8]) -> usize {
120//!     // XOR is symmetric, so decrypt is the same as encrypt
121//!     encrypt(input, key, output)
122//! }
123//! ```
124//!
125//! ## Bitwise Operations
126//!
127//! ```
128//! use byte_array_ops::ByteArray;
129//!
130//! fn main() {
131//!     let a: ByteArray = "0xff00".parse().unwrap();
132//!     let b: ByteArray = "0x0ff0".parse().unwrap();
133//!
134//!     // XOR operation
135//!     let xor_result = a.clone() ^ b.clone();
136//!     assert_eq!(xor_result.as_bytes(), [0xf0, 0xf0]);
137//!
138//!     // AND operation
139//!     let and_result = a.clone() & b.clone();
140//!     assert_eq!(and_result.as_bytes(), [0x0f, 0x00]);
141//!
142//!     // OR operation
143//!     let or_result = a.clone() | b.clone();
144//!     assert_eq!(or_result.as_bytes(), [0xff, 0xf0]);
145//!
146//!     // NOT operation
147//!     let not_result = !a;
148//!     assert_eq!(not_result.as_bytes(), [0x00, 0xff]);
149//! }
150//! ```
151//!
152//! # Module Overview
153//!
154//! This library is organized into the following modules:
155//!
156//! - [`byte_array::model`](byte_array::model) - Core [`ByteArray`] type and constructors
157//! - [`byte_array::type_conv`](byte_array::type_conv) - Type conversion implementations (`From`, `Into`, `FromStr`)
158//! - [`byte_array::ops`](byte_array::ops) - Bitwise operations (XOR, AND, OR, NOT) - requires `ops_algebra` feature
159//! - [`byte_array::iter`](byte_array::iter) - Iterator implementations
160//! - [`byte_array::errors`](errors) - Error types for parsing and conversions
161//! - [`byte_array::macros`](macros) - Declarative macros for easy [`ByteArray`] construction
162//!
163//! # Key Types
164//!
165//! ## Core Types
166//! - [`ByteArray`] - Main byte array type with automatic capacity management
167//! - [`UninitByteArray`](crate::byte_array::model::UninitByteArray) - Builder for configuring ByteArray construction (odd-word padding)
168//! - [`ByteArrayOddWordPad`](crate::byte_array::model::ByteArrayOddWordPad) - Padding direction for odd-length hex/binary inputs
169//!
170//! ## Iterators
171//! - [`ByteArrayIter`](crate::byte_array::iter::ByteArrayIter) - Immutable iterator over bytes
172//! - [`ByteArrayIterMut`](crate::byte_array::iter::ByteArrayIterMut) - Mutable iterator over bytes
173//!
174//! ## Error Types
175//! - [`ByteArrayError`](crate::errors::ByteArrayError) - Errors during parsing and conversions
176//!
177//! # Trait Implementations
178//!
179//! `ByteArray` implements many standard Rust traits for ergonomic usage:
180//!
181//! **Conversions**:
182//! - `From<&[u8]>`, `From<Vec<u8>>`, `From<&Vec<u8>>`, `From<[u8; N]>` - Create from bytes
183//! - `FromStr` - Parse from strings (hex with `0x`, binary with `0b`, UTF-8 fallback)
184//! - `Into<Vec<u8>>` - Extract underlying bytes (zero-cost move)
185//! - `AsRef<[u8]>` - Borrow as byte slice
186//!
187//! **Operations** (requires `ops_algebra` feature):
188//! - `BitXor`, `BitXorAssign` - XOR operations (`^`, `^=`)
189//! - `BitAnd`, `BitAndAssign` - AND operations (`&`, `&=`)
190//! - `BitOr`, `BitOrAssign` - OR operations (`|`, `|=`)
191//! - `Not` - NOT operation (`!`)
192//!
193//! **Iteration**:
194//! - `IntoIterator` - Iterate by reference (`&ByteArray`, `&mut ByteArray`)
195//! - `ExactSizeIterator` - Iterators with known length
196//!
197//! **Comparison**:
198//! - `PartialEq`, `Eq` - Equality comparisons
199//! - `Clone` - Cloning support
200//! - `Default` - Default constructor (empty array)
201//!
202//! **Indexing**:
203//! - `Index<usize>`, `IndexMut<usize>` - Array-style indexing (`arr[0]`, `arr[1] = 0xff`)
204//!
205//! # Implementation Notes
206//!
207//! **Feature Flags**: Check `Cargo.toml` for hardening tiers. When implementing features, use individual feature flags
208//! (`sec_harden_zeroize`, `sec_harden_const_time_ops`, etc.) in `#[cfg]` attributes. Tiers (`sec_basic_hardening`,
209//! `sec_enhanced_hardening`, `sec_maximum_hardening`) are convenience bundles for users to activate multiple features at once.
210#![no_std]
211#![forbid(unsafe_code)]
212
213#[cfg(any(
214    feature = "sec_harden_zeroize",
215    feature = "sec_harden_const_time_ops",
216    feature = "sec_harden_memlock",
217    feature = "sec_harden_memencrypt"
218))]
219compile_error!(
220    "The hardened feature is not yet implemented please deactivate and wait for a future release"
221);
222#[cfg(feature = "ops_simd")]
223compile_error!("Currently not implemented");
224
225extern crate alloc;
226
227pub mod byte_array {
228
229    pub(crate) mod common;
230    pub mod errors;
231    pub mod model;
232
233    pub mod iter;
234    pub mod macros;
235    #[cfg(feature = "ops_algebra")]
236    pub mod ops;
237    pub mod type_conv;
238
239    pub mod trust {
240        #[cfg(any(
241            feature = "sec_harden_zeroize",
242            feature = "sec_harden_memlock",
243            feature = "sec_harden_const_time_ops",
244            feature = "sec_harden_memencrypt"
245        ))]
246        pub mod hardened_ops;
247
248        #[cfg(not(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 insecure_ops;
255    }
256}
257
258pub use byte_array::errors;
259pub use byte_array::model::ByteArray;