base-d 3.0.34

Universal base encoder: Encode binary data to 33+ dictionaries including RFC standards, hieroglyphs, emoji, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
use std::fmt;

/// Errors that can occur during encoding.
#[derive(Debug, PartialEq, Eq)]
pub enum EncodeError {
    /// A byte mapped to an invalid Unicode codepoint during ByteRange encoding
    InvalidCodepoint {
        codepoint: u32,
        start_codepoint: u32,
        byte: u8,
    },
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            EncodeError::InvalidCodepoint {
                codepoint,
                start_codepoint,
                byte,
            } => {
                write!(
                    f,
                    "ByteRange encoding produced invalid codepoint U+{:04X} \
                     (start_codepoint=U+{:04X}, byte=0x{:02X}). \
                     This dictionary should have been rejected at construction time.",
                    codepoint, start_codepoint, byte
                )
            }
        }
    }
}

impl std::error::Error for EncodeError {}

/// Errors that can occur during decoding.
#[derive(Debug, PartialEq, Eq)]
pub enum DecodeError {
    /// The input contains a character not in the dictionary
    InvalidCharacter {
        char: char,
        position: usize,
        input: String,
        valid_chars: String,
    },
    /// The input contains a word not in the word dictionary
    InvalidWord {
        word: String,
        position: usize,
        input: String,
    },
    /// The input string is empty
    EmptyInput,
    /// The padding is malformed or incorrect
    InvalidPadding,
    /// Invalid length for the encoding format
    InvalidLength {
        actual: usize,
        expected: String,
        hint: String,
    },
}

/// Truncate a string to at most `max_chars` characters, appending "..." if truncated.
/// Uses char-count instead of byte-index to avoid panics on multi-byte UTF-8 input.
pub(crate) fn safe_truncate(s: &str, max_chars: usize) -> String {
    if s.chars().count() > max_chars {
        let truncated: String = s.chars().take(max_chars).collect();
        format!("{}...", truncated)
    } else {
        s.to_string()
    }
}

impl DecodeError {
    /// Create an InvalidCharacter error with context
    pub fn invalid_character(c: char, position: usize, input: &str, valid_chars: &str) -> Self {
        DecodeError::InvalidCharacter {
            char: c,
            position,
            input: safe_truncate(input, 60),
            valid_chars: valid_chars.to_string(),
        }
    }

    /// Create an InvalidLength error
    pub fn invalid_length(
        actual: usize,
        expected: impl Into<String>,
        hint: impl Into<String>,
    ) -> Self {
        DecodeError::InvalidLength {
            actual,
            expected: expected.into(),
            hint: hint.into(),
        }
    }

    /// Create an InvalidWord error for word-based decoding
    pub fn invalid_word(word: &str, position: usize, input: &str) -> Self {
        DecodeError::InvalidWord {
            word: word.to_string(),
            position,
            input: safe_truncate(input, 80),
        }
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let use_color = should_use_color();

        match self {
            DecodeError::InvalidCharacter {
                char: c,
                position,
                input,
                valid_chars,
            } => {
                // Error header
                if use_color {
                    writeln!(
                        f,
                        "\x1b[1;31merror:\x1b[0m invalid character '{}' at position {}",
                        c, position
                    )?;
                } else {
                    writeln!(
                        f,
                        "error: invalid character '{}' at position {}",
                        c, position
                    )?;
                }
                writeln!(f)?;

                // Show input with caret pointing at error position
                // Need to account for multi-byte UTF-8 characters
                let char_position = input.chars().take(*position).count();
                writeln!(f, "  {}", input)?;
                write!(f, "  {}", " ".repeat(char_position))?;
                if use_color {
                    writeln!(f, "\x1b[1;31m^\x1b[0m")?;
                } else {
                    writeln!(f, "^")?;
                }
                writeln!(f)?;

                // Hint with valid characters (truncate if too long)
                let hint_chars = safe_truncate(valid_chars, 80);

                if use_color {
                    write!(f, "\x1b[1;36mhint:\x1b[0m valid characters: {}", hint_chars)?;
                } else {
                    write!(f, "hint: valid characters: {}", hint_chars)?;
                }
                Ok(())
            }
            DecodeError::InvalidWord {
                word,
                position,
                input,
            } => {
                if use_color {
                    writeln!(
                        f,
                        "\x1b[1;31merror:\x1b[0m unknown word '{}' at position {}",
                        word, position
                    )?;
                } else {
                    writeln!(f, "error: unknown word '{}' at position {}", word, position)?;
                }
                writeln!(f)?;
                writeln!(f, "  {}", input)?;
                writeln!(f)?;
                if use_color {
                    write!(
                        f,
                        "\x1b[1;36mhint:\x1b[0m check spelling or verify word is in dictionary"
                    )?;
                } else {
                    write!(f, "hint: check spelling or verify word is in dictionary")?;
                }
                Ok(())
            }
            DecodeError::EmptyInput => {
                if use_color {
                    write!(f, "\x1b[1;31merror:\x1b[0m cannot decode empty input")?;
                } else {
                    write!(f, "error: cannot decode empty input")?;
                }
                Ok(())
            }
            DecodeError::InvalidPadding => {
                if use_color {
                    writeln!(f, "\x1b[1;31merror:\x1b[0m invalid padding")?;
                    write!(
                        f,
                        "\n\x1b[1;36mhint:\x1b[0m check for missing or incorrect '=' characters at end of input"
                    )?;
                } else {
                    writeln!(f, "error: invalid padding")?;
                    write!(
                        f,
                        "\nhint: check for missing or incorrect '=' characters at end of input"
                    )?;
                }
                Ok(())
            }
            DecodeError::InvalidLength {
                actual,
                expected,
                hint,
            } => {
                if use_color {
                    writeln!(f, "\x1b[1;31merror:\x1b[0m invalid length for decode",)?;
                } else {
                    writeln!(f, "error: invalid length for decode")?;
                }
                writeln!(f)?;
                writeln!(f, "  input is {} characters, expected {}", actual, expected)?;
                writeln!(f)?;
                if use_color {
                    write!(f, "\x1b[1;36mhint:\x1b[0m {}", hint)?;
                } else {
                    write!(f, "hint: {}", hint)?;
                }
                Ok(())
            }
        }
    }
}

impl std::error::Error for DecodeError {}

/// Check if colored output should be used
fn should_use_color() -> bool {
    // Respect NO_COLOR environment variable
    if std::env::var("NO_COLOR").is_ok() {
        return false;
    }

    // Check if stderr is a terminal
    use std::io::IsTerminal;
    std::io::stderr().is_terminal()
}

/// Error when a dictionary is not found
#[derive(Debug)]
pub struct DictionaryNotFoundError {
    pub name: String,
    pub suggestion: Option<String>,
}

impl DictionaryNotFoundError {
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            suggestion: None,
        }
    }

    pub fn with_suggestion(name: impl Into<String>, suggestion: Option<String>) -> Self {
        Self {
            name: name.into(),
            suggestion,
        }
    }

    pub fn with_cause(name: impl Into<String>, cause: impl std::fmt::Display) -> Self {
        Self {
            name: name.into(),
            suggestion: Some(format!("build failed: {}", cause)),
        }
    }
}

impl fmt::Display for DictionaryNotFoundError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let use_color = should_use_color();

        if use_color {
            writeln!(
                f,
                "\x1b[1;31merror:\x1b[0m dictionary '{}' not found",
                self.name
            )?;
        } else {
            writeln!(f, "error: dictionary '{}' not found", self.name)?;
        }

        writeln!(f)?;

        if let Some(suggestion) = &self.suggestion {
            if use_color {
                writeln!(f, "\x1b[1;36mhint:\x1b[0m did you mean '{}'?", suggestion)?;
            } else {
                writeln!(f, "hint: did you mean '{}'?", suggestion)?;
            }
        }

        if use_color {
            write!(
                f,
                "      run \x1b[1m`base-d config --dictionaries`\x1b[0m to see all dictionaries"
            )?;
        } else {
            write!(
                f,
                "      run `base-d config --dictionaries` to see all dictionaries"
            )?;
        }

        Ok(())
    }
}

impl std::error::Error for DictionaryNotFoundError {}

/// Calculate Levenshtein distance between two strings
fn levenshtein_distance(s1: &str, s2: &str) -> usize {
    let len1 = s1.chars().count();
    let len2 = s2.chars().count();

    if len1 == 0 {
        return len2;
    }
    if len2 == 0 {
        return len1;
    }

    let mut prev_row: Vec<usize> = (0..=len2).collect();
    let mut curr_row = vec![0; len2 + 1];

    for (i, c1) in s1.chars().enumerate() {
        curr_row[0] = i + 1;

        for (j, c2) in s2.chars().enumerate() {
            let cost = if c1 == c2 { 0 } else { 1 };
            curr_row[j + 1] = (curr_row[j] + 1)
                .min(prev_row[j + 1] + 1)
                .min(prev_row[j] + cost);
        }

        std::mem::swap(&mut prev_row, &mut curr_row);
    }

    prev_row[len2]
}

/// Find the closest matching dictionary name
pub fn find_closest_dictionary(name: &str, available: &[String]) -> Option<String> {
    if available.is_empty() {
        return None;
    }

    let mut best_match = None;
    let mut best_distance = usize::MAX;

    for dict_name in available {
        let distance = levenshtein_distance(name, dict_name);

        // Only suggest if distance is reasonably small
        // (e.g., 1-2 character typos for short names, up to 3 for longer names)
        let threshold = if name.len() < 5 { 2 } else { 3 };

        if distance < best_distance && distance <= threshold {
            best_distance = distance;
            best_match = Some(dict_name.clone());
        }
    }

    best_match
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_levenshtein_distance() {
        assert_eq!(levenshtein_distance("base64", "base64"), 0);
        assert_eq!(levenshtein_distance("base64", "base32"), 2);
        assert_eq!(levenshtein_distance("bas64", "base64"), 1);
        assert_eq!(levenshtein_distance("", "base64"), 6);
    }

    #[test]
    fn test_find_closest_dictionary() {
        let dicts = vec![
            "base64".to_string(),
            "base32".to_string(),
            "base16".to_string(),
            "hex".to_string(),
        ];

        assert_eq!(
            find_closest_dictionary("bas64", &dicts),
            Some("base64".to_string())
        );
        assert_eq!(
            find_closest_dictionary("base63", &dicts),
            Some("base64".to_string())
        );
        assert_eq!(
            find_closest_dictionary("hex_radix", &dicts),
            None // too different
        );
    }

    #[test]
    fn test_error_display_no_color() {
        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::set_var("NO_COLOR", "1");
        }

        let err = DecodeError::invalid_character('_', 12, "SGVsbG9faW52YWxpZA==", "A-Za-z0-9+/=");
        let display = format!("{}", err);

        assert!(display.contains("invalid character '_' at position 12"));
        assert!(display.contains("SGVsbG9faW52YWxpZA=="));
        assert!(display.contains("^"));
        assert!(display.contains("hint:"));

        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::remove_var("NO_COLOR");
        }
    }

    #[test]
    fn test_invalid_length_error() {
        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::set_var("NO_COLOR", "1");
        }

        let err = DecodeError::invalid_length(
            13,
            "multiple of 4",
            "add padding (=) or check for missing characters",
        );
        let display = format!("{}", err);

        assert!(display.contains("invalid length"));
        assert!(display.contains("13 characters"));
        assert!(display.contains("multiple of 4"));
        assert!(display.contains("add padding"));

        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::remove_var("NO_COLOR");
        }
    }

    #[test]
    fn test_dictionary_not_found_error() {
        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::set_var("NO_COLOR", "1");
        }

        let err = DictionaryNotFoundError::with_suggestion("bas64", Some("base64".to_string()));
        let display = format!("{}", err);

        assert!(display.contains("dictionary 'bas64' not found"));
        assert!(display.contains("did you mean 'base64'?"));
        assert!(display.contains("base-d config --dictionaries"));

        // Unsafe: environment variable access (not thread-safe)
        // TODO: Audit that the environment access only happens in single-threaded code.
        unsafe {
            std::env::remove_var("NO_COLOR");
        }
    }

    #[test]
    fn test_safe_truncate_multibyte() {
        let input = "\u{1F3AD}".repeat(20); // 20 chars, 80 bytes
        let result = safe_truncate(&input, 10);
        assert_eq!(result, format!("{}...", "\u{1F3AD}".repeat(10)));
    }

    #[test]
    fn test_safe_truncate_no_truncation() {
        assert_eq!(safe_truncate("hello", 10), "hello");
    }

    #[test]
    fn test_safe_truncate_exact_boundary() {
        assert_eq!(safe_truncate("hello", 5), "hello");
    }

    #[test]
    fn test_invalid_character_multibyte_no_panic() {
        let input = "\u{1F711}".repeat(30); // 30 alchemical symbols, 120 bytes
        // This must not panic -- the old &input[..60] would have
        let err = DecodeError::invalid_character('x', 0, &input, "abc");
        let _ = format!("{}", err);
    }
}