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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
use crate::{Dictionary, DictionaryRegistry, EncodingMode, decode, encode};

fn get_dictionary(name: &str) -> Dictionary {
    let config = DictionaryRegistry::load_default().unwrap();
    let dictionary_config = config.get_dictionary(name).unwrap();
    let effective_mode = dictionary_config.effective_mode();

    match effective_mode {
        EncodingMode::ByteRange => {
            let start = dictionary_config.start_codepoint.unwrap();
            Dictionary::builder()
                .mode(effective_mode)
                .start_codepoint(start)
                .build()
                .unwrap()
        }
        _ => {
            let chars: Vec<char> = dictionary_config
                .effective_chars()
                .unwrap()
                .chars()
                .collect();
            let padding = dictionary_config
                .padding
                .as_ref()
                .and_then(|s| s.chars().next());
            let mut builder = Dictionary::builder().chars(chars).mode(effective_mode);
            if let Some(p) = padding {
                builder = builder.padding(p);
            }
            builder.build().unwrap()
        }
    }
}

#[test]
fn test_encode_decode_empty() {
    let dictionary = get_dictionary("cards");
    let data = b"";
    let encoded = encode(data, &dictionary);
    assert_eq!(encoded, "");
}

#[test]
fn test_encode_decode_zero() {
    let dictionary = get_dictionary("cards");
    let data = &[0u8];
    let encoded = encode(data, &dictionary);
    assert_eq!(encoded.chars().count(), 1);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_encode_decode_simple() {
    let dictionary = get_dictionary("cards");
    let data = b"Hello";
    let encoded = encode(data, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_encode_decode_hello_world() {
    let dictionary = get_dictionary("cards");
    let data = b"Hello, World!";
    let encoded = encode(data, &dictionary);
    println!("Encoded: {}", encoded);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_encode_decode_binary() {
    let dictionary = get_dictionary("cards");
    let data = &[0u8, 1, 2, 3, 255, 254, 253];
    let encoded = encode(data, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_encode_decode_leading_zeros() {
    let dictionary = get_dictionary("cards");
    let data = &[0u8, 0, 0, 1, 2, 3];
    let encoded = encode(data, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_decode_invalid_character() {
    let dictionary = get_dictionary("cards");
    let result = decode("ABC", &dictionary);
    assert!(result.is_err());
}

#[test]
fn test_dictionary_base() {
    let dictionary = get_dictionary("cards");
    assert_eq!(dictionary.base(), 52);
}

#[test]
fn test_base64_chunked_mode() {
    let dictionary = get_dictionary("base64");
    assert_eq!(dictionary.mode(), &EncodingMode::Chunked);

    // Test standard base64 encoding
    let data = b"Hello, World!";
    let encoded = encode(data, &dictionary);
    println!("base64 encoded: {}", encoded);

    // Should match standard base64
    let expected = "SGVsbG8sIFdvcmxkIQ==";
    assert_eq!(encoded, expected);

    // Test decoding
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base64_radix_mode() {
    let dictionary = get_dictionary("base64_radix");
    assert_eq!(dictionary.mode(), &EncodingMode::Radix);

    // This should use radix base conversion
    let data = b"Hello, World!";
    let encoded = encode(data, &dictionary);
    println!("base64_radix encoded: {}", encoded);

    // Should NOT match standard base64
    let standard_base64 = "SGVsbG8sIFdvcmxkIQ==";
    assert_ne!(encoded, standard_base64);

    // But should still round-trip
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base100_byte_range_mode() {
    let dictionary = get_dictionary("base100");
    assert_eq!(dictionary.mode(), &EncodingMode::ByteRange);
    assert_eq!(dictionary.base(), 256);

    // Test simple encoding
    let data = b"Hello, World!";
    let encoded = encode(data, &dictionary);
    println!("base100 encoded: {}", encoded);

    // Each byte should map to exactly one emoji
    assert_eq!(encoded.chars().count(), data.len());

    // Verify specific codepoints for first few characters
    // 'H' = 72, should map to 127991 + 72 = 128063 (U+1F43F)
    let first_char = encoded.chars().next().unwrap();
    assert_eq!(first_char as u32, 127991 + 72);

    // Test decoding
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base100_all_bytes() {
    let dictionary = get_dictionary("base100");

    // Test all 256 possible byte values
    let data: Vec<u8> = (0..=255).collect();
    let encoded = encode(&data, &dictionary);

    // Should encode to 256 emojis
    assert_eq!(encoded.chars().count(), 256);

    // Should round-trip correctly
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base100_empty() {
    let dictionary = get_dictionary("base100");

    let data = b"";
    let encoded = encode(data, &dictionary);
    assert_eq!(encoded, "");

    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base100_binary_data() {
    let dictionary = get_dictionary("base100");

    let data = &[0u8, 1, 2, 3, 255, 254, 253, 128, 127];
    let encoded = encode(data, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base1024_large_dictionary() {
    // Test that we can load and use a 1024-character dictionary
    let dictionary = get_dictionary("base1024");

    // Verify base size
    assert_eq!(dictionary.base(), 1024);

    // Test encoding/decoding various data sizes
    let test_data = vec![
        b"A".to_vec(),
        b"Hello".to_vec(),
        b"Hello, World!".to_vec(),
        (0u8..=255).collect::<Vec<u8>>(), // All bytes
    ];

    for data in test_data {
        let encoded = encode(&data, &dictionary);
        let decoded = decode(&encoded, &dictionary).unwrap();
        assert_eq!(decoded, data, "Failed for data of length {}", data.len());

        // Verify that encoding with larger base produces shorter output
        // For mathematical mode, larger base = more compact representation
        // Each 1024-base digit represents ~10 bits (log2(1024) = 10)
        let bits_in = data.len() * 8;
        let max_chars = bits_in.div_ceil(10); // ceiling division
        assert!(
            encoded.chars().count() <= max_chars + 1,
            "Encoding too long: {} chars for {} bytes (expected <= {})",
            encoded.chars().count(),
            data.len(),
            max_chars + 1
        );
    }
}

#[test]
fn test_base1024_uses_hashmap() {
    // Base1024 uses non-ASCII characters, so it should use HashMap not lookup table
    let dictionary = get_dictionary("base1024");

    // Test that decoding works correctly (verifies HashMap fallback)
    let data = b"Testing large dictionary HashMap fallback";
    let encoded = encode(data, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base1024_efficiency() {
    let dictionary = get_dictionary("base1024");

    // Compare with base64 for same data
    let base64 = get_dictionary("base64");
    let data = b"The quick brown fox jumps over the lazy dog";

    let encoded_1024 = encode(data, &dictionary);
    let encoded_64 = encode(data, &base64);

    // Base1024 should produce fewer characters than base64
    // base1024: ~10 bits per char, base64: 6 bits per char
    assert!(
        encoded_1024.chars().count() < encoded_64.chars().count(),
        "Base1024 ({} chars) should be shorter than base64 ({} chars)",
        encoded_1024.chars().count(),
        encoded_64.chars().count()
    );
}

#[test]
fn test_base256_matrix_like_hex() {
    // Test that base256_matrix works identically in both modes (like hexadecimal)
    let dictionary_chunked = get_dictionary("base256_matrix");

    // Verify it's a 256-character dictionary
    assert_eq!(dictionary_chunked.base(), 256);

    // Create radix mode version
    let config = DictionaryRegistry::load_default().unwrap();
    let matrix_config = config.get_dictionary("base256_matrix").unwrap();
    let chars: Vec<char> = matrix_config.effective_chars().unwrap().chars().collect();
    let dictionary_radix = Dictionary::builder()
        .chars(chars)
        .mode(EncodingMode::Radix)
        .build()
        .unwrap();

    // Test various data sizes
    let test_data = vec![
        b"A".to_vec(),
        b"Hi".to_vec(),
        b"Matrix".to_vec(),
        b"The Matrix has you...".to_vec(),
        (0u8..=255).collect::<Vec<u8>>(), // All bytes
    ];

    for data in test_data {
        let chunked_encoded = encode(&data, &dictionary_chunked);
        let radix_encoded = encode(&data, &dictionary_radix);

        // Both modes should produce IDENTICAL output (like hexadecimal)
        assert_eq!(
            chunked_encoded,
            radix_encoded,
            "Modes should produce identical output for {} bytes (like hex!)",
            data.len()
        );

        // Verify round-trip
        let decoded = decode(&chunked_encoded, &dictionary_chunked).unwrap();
        assert_eq!(decoded, data);

        // Verify 1:1 mapping (256 = 2^8 = 1 byte per char)
        assert_eq!(
            chunked_encoded.chars().count(),
            data.len(),
            "Base256 should have 1:1 char-to-byte ratio"
        );
    }
}

#[test]
fn test_base256_matrix_perfect_encoding() {
    let dictionary = get_dictionary("base256_matrix");

    // Test the special property: 8 bits % log2(256) = 8 % 8 = 0
    // This means no expansion, perfect 1:1 mapping
    let data = b"Follow the white rabbit";
    let encoded = encode(data, &dictionary);

    // Should be exactly the same length
    assert_eq!(encoded.chars().count(), data.len());

    // Decode should work perfectly
    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, data);
}

#[test]
fn test_base256_matrix_all_bytes() {
    let dictionary = get_dictionary("base256_matrix");

    // Test that all 256 possible byte values can be encoded/decoded
    let all_bytes: Vec<u8> = (0..=255).collect();
    let encoded = encode(&all_bytes, &dictionary);
    let decoded = decode(&encoded, &dictionary).unwrap();

    assert_eq!(decoded, all_bytes);
    assert_eq!(encoded.chars().count(), 256); // 1:1 ratio
}

// ============================================================================
// RFC 4648 Official Test Vectors
// https://datatracker.ietf.org/doc/html/rfc4648#section-10
// ============================================================================

#[test]
fn test_rfc4648_base64_vectors() {
    let dictionary = get_dictionary("base64");

    // RFC 4648 Section 10 test vectors
    let test_cases = [
        (b"".as_slice(), ""),
        (b"f".as_slice(), "Zg=="),
        (b"fo".as_slice(), "Zm8="),
        (b"foo".as_slice(), "Zm9v"),
        (b"foob".as_slice(), "Zm9vYg=="),
        (b"fooba".as_slice(), "Zm9vYmE="),
        (b"foobar".as_slice(), "Zm9vYmFy"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base64 encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        if !expected.is_empty() {
            let decoded = decode(&encoded, &dictionary).unwrap();
            assert_eq!(
                decoded, input,
                "Base64 round-trip failed for {:?}",
                expected
            );
        }
    }
}

#[test]
fn test_rfc4648_base32_vectors() {
    let dictionary = get_dictionary("base32");

    // RFC 4648 Section 10 test vectors
    let test_cases = [
        (b"".as_slice(), ""),
        (b"f".as_slice(), "MY======"),
        (b"fo".as_slice(), "MZXQ===="),
        (b"foo".as_slice(), "MZXW6==="),
        (b"foob".as_slice(), "MZXW6YQ="),
        (b"fooba".as_slice(), "MZXW6YTB"),
        (b"foobar".as_slice(), "MZXW6YTBOI======"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base32 encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        if !expected.is_empty() {
            let decoded = decode(&encoded, &dictionary).unwrap();
            assert_eq!(
                decoded, input,
                "Base32 round-trip failed for {:?}",
                expected
            );
        }
    }
}

#[test]
fn test_rfc4648_base16_vectors() {
    let dictionary = get_dictionary("base16");

    // RFC 4648 Section 10 test vectors (uppercase)
    let test_cases = [
        (b"".as_slice(), ""),
        (b"f".as_slice(), "66"),
        (b"fo".as_slice(), "666F"),
        (b"foo".as_slice(), "666F6F"),
        (b"foob".as_slice(), "666F6F62"),
        (b"fooba".as_slice(), "666F6F6261"),
        (b"foobar".as_slice(), "666F6F626172"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base16 encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        if !expected.is_empty() {
            let decoded = decode(&encoded, &dictionary).unwrap();
            assert_eq!(
                decoded, input,
                "Base16 round-trip failed for {:?}",
                expected
            );
        }
    }
}

#[test]
fn test_rfc4648_base32hex_vectors() {
    let dictionary = get_dictionary("base32hex");

    // RFC 4648 Section 10 test vectors for base32hex (Extended Hex)
    // These use 0-9A-V instead of A-Z2-7
    let test_cases = [
        (b"".as_slice(), ""),
        (b"f".as_slice(), "CO======"),
        (b"fo".as_slice(), "CPNG===="),
        (b"foo".as_slice(), "CPNMU==="),
        (b"foob".as_slice(), "CPNMUOG="),
        (b"fooba".as_slice(), "CPNMUOJ1"),
        (b"foobar".as_slice(), "CPNMUOJ1E8======"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base32hex encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        if !expected.is_empty() {
            let decoded = decode(&encoded, &dictionary).unwrap();
            assert_eq!(
                decoded, input,
                "Base32hex round-trip failed for {:?}",
                expected
            );
        }
    }
}

// ============================================================================
// Base58 Test Vectors (IETF Draft & Bitcoin wiki)
// https://datatracker.ietf.org/doc/html/draft-msporny-base58-03
// ============================================================================

#[test]
fn test_base58_bitcoin_vectors() {
    let dictionary = get_dictionary("base58");

    // IETF Base58 draft specification test vectors (Bitcoin alphabet)
    let test_cases = [
        (b"Hello World!".as_slice(), "2NEpo7TZRRrLZSi2U"),
        (
            b"The quick brown fox jumps over the lazy dog.".as_slice(),
            "USm3fpXnKG5EUBx2ndxBDMPVciP5hGey2Jh4NDv6gmeo1LkMeiKrLJUUBk6Z",
        ),
        (b"hello world".as_slice(), "StV1DL6CwTryKyV"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base58 encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        let decoded = decode(&encoded, &dictionary).unwrap();
        assert_eq!(
            decoded, input,
            "Base58 round-trip failed for {:?}",
            expected
        );
    }
}

#[test]
fn test_base58_flickr_vectors() {
    let dictionary = get_dictionary("base58flickr");

    // Flickr uses lowercase before uppercase
    // "Hello World" -> "iXf12sRWto45bmC" (from spec)
    let test_cases = [(b"Hello World".as_slice(), "iXf12sRWto45bmC")];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded,
            expected,
            "Base58 Flickr encoding mismatch for {:?}: got {}, expected {}",
            String::from_utf8_lossy(input),
            encoded,
            expected
        );

        // Also verify round-trip
        let decoded = decode(&encoded, &dictionary).unwrap();
        assert_eq!(
            decoded, input,
            "Base58 Flickr round-trip failed for {:?}",
            expected
        );
    }
}

#[test]
fn test_base58_leading_zeros() {
    let dictionary = get_dictionary("base58");

    // Leading zeros should be preserved as '1' characters
    // 0x0000287fb4cd -> "11233QC4"
    let input = &[0x00, 0x00, 0x28, 0x7f, 0xb4, 0xcd];
    let expected = "11233QC4";

    let encoded = encode(input, &dictionary);
    assert_eq!(
        encoded, expected,
        "Base58 leading zeros mismatch: got {}, expected {}",
        encoded, expected
    );

    let decoded = decode(&encoded, &dictionary).unwrap();
    assert_eq!(decoded, input, "Base58 leading zeros round-trip failed");
}

/// Test geohash encoding - regression test for SIMD range-reduction bug
///
/// Geohash uses a non-contiguous 32-char alphabet that doesn't fit in the
/// 16-byte pshufb LUT, so it must fall back to scalar encoding.
#[test]
fn test_base32_geohash() {
    let dictionary = get_dictionary("base32_geohash");

    // Geohash alphabet: 0123456789bcdefghjkmnpqrstuvwxyz (missing a,i,l,o)
    let test_cases = [
        (b"Hello".as_slice(), "91kqsv3g"),
        (b"World".as_slice(), "bxrr4v34"),
        (b"\x00".as_slice(), "00"),
        (b"\xFF".as_slice(), "zw"),
    ];

    for (input, expected) in test_cases {
        let encoded = encode(input, &dictionary);
        assert_eq!(
            encoded, expected,
            "Geohash encoding mismatch for {:?}: got {}, expected {}",
            input, encoded, expected
        );

        // Verify all output chars are valid geohash characters
        let valid_chars = "0123456789bcdefghjkmnpqrstuvwxyz";
        for c in encoded.chars() {
            assert!(
                valid_chars.contains(c),
                "Invalid geohash character '{}' in output",
                c
            );
        }

        // Verify round-trip
        if !input.is_empty() {
            let decoded = decode(&encoded, &dictionary).unwrap();
            assert_eq!(decoded, input, "Geohash round-trip failed for {:?}", input);
        }
    }
}