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