base_d/lib.rs
1//! # base-d
2//!
3//! A universal, multi-dictionary encoding library for Rust.
4//!
5//! Encode binary data using numerous dictionaries including RFC standards, ancient scripts,
6//! emoji, playing cards, and more. Supports three encoding modes: radix (true base
7//! conversion), RFC 4648 chunked encoding, and direct byte-range mapping.
8//!
9//! ## Quick Start
10//!
11//! ```
12//! use base_d::{DictionaryRegistry, Dictionary, encode, decode};
13//!
14//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
15//! // Load built-in dictionaries
16//! let config = DictionaryRegistry::load_default()?;
17//! let base64_config = config.get_dictionary("base64").unwrap();
18//!
19//! // Create dictionary
20//! let chars: Vec<char> = base64_config.chars.chars().collect();
21//! let padding = base64_config.padding.as_ref().and_then(|s| s.chars().next());
22//! let mut builder = Dictionary::builder()
23//! .chars(chars)
24//! .mode(base64_config.effective_mode());
25//! if let Some(p) = padding {
26//! builder = builder.padding(p);
27//! }
28//! let dictionary = builder.build()?;
29//!
30//! // Encode and decode
31//! let data = b"Hello, World!";
32//! let encoded = encode(data, &dictionary);
33//! let decoded = decode(&encoded, &dictionary)?;
34//! assert_eq!(data, &decoded[..]);
35//! # Ok(())
36//! # }
37//! ```
38//!
39//! ## Features
40//!
41//! - **33 Built-in Dictionaries**: RFC standards, emoji, ancient scripts, and more
42//! - **3 Encoding Modes**: Radix, chunked (RFC-compliant), byte-range
43//! - **Streaming Support**: Memory-efficient processing for large files
44//! - **Custom Dictionaries**: Define your own via TOML configuration
45//! - **User Configuration**: Load dictionaries from `~/.config/base-d/dictionaries.toml`
46//! - **SIMD Acceleration**: AVX2/SSSE3 on x86_64, NEON on aarch64 (enabled by default)
47//!
48//! ## Cargo Features
49//!
50//! - `simd` (default): Enable SIMD acceleration for encoding/decoding.
51//! Disable with `--no-default-features` for scalar-only builds.
52//!
53//! ## Encoding Modes
54//!
55//! ### Radix Base Conversion
56//!
57//! True base conversion treating data as a large number. Works with any dictionary size.
58//!
59//! ```
60//! use base_d::{Dictionary, EncodingMode, encode};
61//!
62//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
63//! let chars: Vec<char> = "😀😁😂🤣😃😄😅😆".chars().collect();
64//! let dictionary = Dictionary::builder()
65//! .chars(chars)
66//! .mode(EncodingMode::Radix)
67//! .build()?;
68//!
69//! let encoded = encode(b"Hi", &dictionary);
70//! # Ok(())
71//! # }
72//! ```
73//!
74//! ### Chunked Mode (RFC 4648)
75//!
76//! Fixed-size bit groups, compatible with standard base64/base32.
77//!
78//! ```
79//! use base_d::{Dictionary, EncodingMode, encode};
80//!
81//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
82//! let chars: Vec<char> = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
83//! .chars().collect();
84//! let dictionary = Dictionary::builder()
85//! .chars(chars)
86//! .mode(EncodingMode::Chunked)
87//! .padding('=')
88//! .build()?;
89//!
90//! let encoded = encode(b"Hello", &dictionary);
91//! assert_eq!(encoded, "SGVsbG8=");
92//! # Ok(())
93//! # }
94//! ```
95//!
96//! ### Byte Range Mode
97//!
98//! Direct 1:1 byte-to-emoji mapping. Zero encoding overhead.
99//!
100//! ```
101//! use base_d::{Dictionary, EncodingMode, encode};
102//!
103//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
104//! let dictionary = Dictionary::builder()
105//! .mode(EncodingMode::ByteRange)
106//! .start_codepoint(127991) // U+1F3F7
107//! .build()?;
108//!
109//! let data = b"Hi";
110//! let encoded = encode(data, &dictionary);
111//! assert_eq!(encoded.chars().count(), 2); // 1:1 mapping
112//! # Ok(())
113//! # }
114//! ```
115//!
116//! ## Streaming
117//!
118//! For large files, use streaming to avoid loading entire file into memory:
119//!
120//! ```no_run
121//! use base_d::{DictionaryRegistry, StreamingEncoder};
122//! use std::fs::File;
123//!
124//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
125//! let config = DictionaryRegistry::load_default()?;
126//! let dictionary_config = config.get_dictionary("base64").unwrap();
127//!
128//! // ... create dictionary from config
129//! # let chars: Vec<char> = dictionary_config.chars.chars().collect();
130//! # let padding = dictionary_config.padding.as_ref().and_then(|s| s.chars().next());
131//! # let mut builder = base_d::Dictionary::builder().chars(chars).mode(dictionary_config.effective_mode());
132//! # if let Some(p) = padding { builder = builder.padding(p); }
133//! # let dictionary = builder.build()?;
134//!
135//! let mut input = File::open("large_file.bin")?;
136//! let output = File::create("encoded.txt")?;
137//!
138//! let mut encoder = StreamingEncoder::new(&dictionary, output);
139//! encoder.encode(&mut input)?;
140//! # Ok(())
141//! # }
142//! ```
143
144mod core;
145mod encoders;
146mod features;
147
148#[cfg(feature = "simd")]
149mod simd;
150
151#[cfg(feature = "wasm")]
152pub mod wasm;
153
154pub mod bench;
155pub mod convenience;
156pub mod prelude;
157pub mod wordlists;
158
159pub use convenience::{
160 CompressEncodeResult, HashEncodeResult, compress_encode, compress_encode_with, hash_encode,
161 hash_encode_with,
162};
163pub use core::alternating_dictionary::AlternatingWordDictionary;
164pub use core::config::{
165 CompressionConfig, DictionaryConfig, DictionaryRegistry, DictionaryType, EncodingMode, Settings,
166};
167pub use core::dictionary::{Dictionary, DictionaryBuilder};
168pub use core::word_dictionary::{WordDictionary, WordDictionaryBuilder};
169pub use encoders::algorithms::{DecodeError, DictionaryNotFoundError, find_closest_dictionary};
170
171/// Word-based encoding using radix conversion.
172///
173/// Same mathematical approach as character-based radix encoding,
174/// but outputs words joined by a delimiter instead of concatenated characters.
175pub mod word {
176 pub use crate::encoders::algorithms::word::{decode, encode};
177}
178
179/// Alternating word-based encoding for PGP-style biometric word lists.
180///
181/// Provides direct 1:1 byte-to-word mapping where the dictionary selection
182/// alternates based on byte position (e.g., even/odd bytes use different dictionaries).
183pub mod word_alternating {
184 pub use crate::encoders::algorithms::word_alternating::{decode, encode};
185}
186pub use encoders::streaming::{StreamingDecoder, StreamingEncoder};
187
188// Expose schema encoding functions for CLI
189pub use encoders::algorithms::schema::{
190 SchemaCompressionAlgo, decode_schema, decode_stele, decode_stele_path, encode_markdown_stele,
191 encode_markdown_stele_ascii, encode_markdown_stele_light, encode_markdown_stele_markdown,
192 encode_markdown_stele_readable, encode_schema, encode_stele, encode_stele_ascii,
193 encode_stele_light, encode_stele_minified, encode_stele_path, encode_stele_readable,
194};
195
196// Expose stele auto-detection
197pub use encoders::algorithms::schema::stele_analyzer::{DetectedMode, detect_stele_mode};
198
199/// Schema encoding types and traits for building custom frontends
200///
201/// This module provides the intermediate representation (IR) layer for schema encoding,
202/// allowing library users to implement custom parsers (YAML, CSV, TOML, etc.) and
203/// serializers that leverage the binary encoding backend.
204///
205/// # Architecture
206///
207/// The schema encoding pipeline has three layers:
208///
209/// 1. **Input layer**: Parse custom formats into IR
210/// - Implement `InputParser` trait
211/// - Reference: `JsonParser`
212///
213/// 2. **Binary layer**: Pack/unpack IR to/from binary
214/// - `pack()` - IR to binary bytes
215/// - `unpack()` - Binary bytes to IR
216/// - `encode_framed()` - Binary to display96 with delimiters
217/// - `decode_framed()` - Display96 to binary
218///
219/// 3. **Output layer**: Serialize IR to custom formats
220/// - Implement `OutputSerializer` trait
221/// - Reference: `JsonSerializer`
222///
223/// # Example: Custom CSV Parser
224///
225/// ```ignore
226/// use base_d::schema::{
227/// InputParser, IntermediateRepresentation, SchemaHeader, FieldDef,
228/// FieldType, SchemaValue, SchemaError, pack, encode_framed,
229/// };
230///
231/// struct CsvParser;
232///
233/// impl InputParser for CsvParser {
234/// type Error = SchemaError;
235///
236/// fn parse(input: &str) -> Result<IntermediateRepresentation, Self::Error> {
237/// // Parse CSV headers
238/// let lines: Vec<&str> = input.lines().collect();
239/// let headers: Vec<&str> = lines[0].split(',').collect();
240///
241/// // Infer types and build fields
242/// let fields: Vec<FieldDef> = headers.iter()
243/// .map(|h| FieldDef::new(h.to_string(), FieldType::String))
244/// .collect();
245///
246/// // Parse rows
247/// let row_count = lines.len() - 1;
248/// let mut values = Vec::new();
249/// for line in &lines[1..] {
250/// for cell in line.split(',') {
251/// values.push(SchemaValue::String(cell.to_string()));
252/// }
253/// }
254///
255/// let header = SchemaHeader::new(row_count, fields);
256/// IntermediateRepresentation::new(header, values)
257/// }
258/// }
259///
260/// // Encode CSV to schema format
261/// let csv = "name,age\nalice,30\nbob,25";
262/// let ir = CsvParser::parse(csv)?;
263/// let binary = pack(&ir);
264/// let encoded = encode_framed(&binary);
265/// ```
266///
267/// # IR Structure
268///
269/// The `IntermediateRepresentation` consists of:
270///
271/// * **Header**: Schema metadata
272/// - Field definitions (name + type)
273/// - Row count
274/// - Optional root key
275/// - Optional null bitmap
276///
277/// * **Values**: Flat array in row-major order
278/// - `[row0_field0, row0_field1, row1_field0, row1_field1, ...]`
279///
280/// # Type System
281///
282/// Supported field types:
283///
284/// * `U64` - Unsigned 64-bit integer
285/// * `I64` - Signed 64-bit integer
286/// * `F64` - 64-bit floating point
287/// * `String` - UTF-8 string
288/// * `Bool` - Boolean
289/// * `Null` - Null value
290/// * `Array(T)` - Homogeneous array of type T
291/// * `Any` - Mixed-type values
292///
293/// # Compression
294///
295/// Optional compression algorithms:
296///
297/// * `SchemaCompressionAlgo::Brotli` - Best ratio
298/// * `SchemaCompressionAlgo::Lz4` - Fastest
299/// * `SchemaCompressionAlgo::Zstd` - Balanced
300///
301/// # See Also
302///
303/// * [SCHEMA.md](../SCHEMA.md) - Full format specification
304/// * `encode_schema()` / `decode_schema()` - High-level JSON functions
305pub mod schema {
306 pub use crate::encoders::algorithms::schema::{
307 // IR types
308 FieldDef,
309 FieldType,
310 // Traits
311 InputParser,
312 IntermediateRepresentation,
313 // Reference implementations
314 JsonParser,
315 JsonSerializer,
316 OutputSerializer,
317 // Compression
318 SchemaCompressionAlgo,
319 // Errors
320 SchemaError,
321 SchemaHeader,
322 SchemaValue,
323 // Binary layer
324 decode_framed,
325 // High-level API
326 decode_schema,
327 encode_framed,
328 encode_schema,
329 pack,
330 unpack,
331 };
332}
333pub use features::{
334 CompressionAlgorithm, DictionaryDetector, DictionaryMatch, HashAlgorithm, XxHashConfig,
335 compress, decompress, detect_dictionary, hash, hash_with_config,
336};
337
338/// Encodes binary data using the specified dictionary.
339///
340/// Automatically selects the appropriate encoding strategy based on the
341/// dictionary's mode (Radix, Chunked, or ByteRange).
342///
343/// # Arguments
344///
345/// * `data` - The binary data to encode
346/// * `dictionary` - The dictionary to use for encoding
347///
348/// # Returns
349///
350/// A string containing the encoded data
351///
352/// # Examples
353///
354/// ```
355/// use base_d::{Dictionary, EncodingMode};
356///
357/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
358/// let chars: Vec<char> = "01".chars().collect();
359/// let dictionary = Dictionary::builder()
360/// .chars(chars)
361/// .mode(EncodingMode::Radix)
362/// .build()?;
363/// let encoded = base_d::encode(b"Hi", &dictionary);
364/// # Ok(())
365/// # }
366/// ```
367pub fn encode(data: &[u8], dictionary: &Dictionary) -> String {
368 match dictionary.mode() {
369 EncodingMode::Radix => encoders::algorithms::radix::encode(data, dictionary),
370 EncodingMode::Chunked => encoders::algorithms::chunked::encode_chunked(data, dictionary),
371 EncodingMode::ByteRange => {
372 encoders::algorithms::byte_range::encode_byte_range(data, dictionary)
373 }
374 }
375}
376
377/// Decodes a string back to binary data using the specified dictionary.
378///
379/// Automatically selects the appropriate decoding strategy based on the
380/// dictionary's mode (Radix, Chunked, or ByteRange).
381///
382/// # Arguments
383///
384/// * `encoded` - The encoded string to decode
385/// * `dictionary` - The dictionary used for encoding
386///
387/// # Returns
388///
389/// A `Result` containing the decoded binary data, or a `DecodeError` if
390/// the input is invalid
391///
392/// # Errors
393///
394/// Returns `DecodeError` if:
395/// - The input contains invalid characters
396/// - The input is empty
397/// - The padding is invalid (for chunked mode)
398///
399/// # Examples
400///
401/// ```
402/// use base_d::{Dictionary, EncodingMode, encode, decode};
403///
404/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
405/// let chars: Vec<char> = "01".chars().collect();
406/// let dictionary = Dictionary::builder()
407/// .chars(chars)
408/// .mode(EncodingMode::Radix)
409/// .build()?;
410/// let data = b"Hi";
411/// let encoded = encode(data, &dictionary);
412/// let decoded = decode(&encoded, &dictionary)?;
413/// assert_eq!(data, &decoded[..]);
414/// # Ok(())
415/// # }
416/// ```
417pub fn decode(encoded: &str, dictionary: &Dictionary) -> Result<Vec<u8>, DecodeError> {
418 match dictionary.mode() {
419 EncodingMode::Radix => encoders::algorithms::radix::decode(encoded, dictionary),
420 EncodingMode::Chunked => encoders::algorithms::chunked::decode_chunked(encoded, dictionary),
421 EncodingMode::ByteRange => {
422 encoders::algorithms::byte_range::decode_byte_range(encoded, dictionary)
423 }
424 }
425}
426
427#[cfg(test)]
428mod tests;