-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathlib.rs
More file actions
2810 lines (2672 loc) · 125 KB
/
lib.rs
File metadata and controls
2810 lines (2672 loc) · 125 KB
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Efficient and customizable data-encoding functions like base64, base32, and hex
//!
//! This [crate] provides little-endian ASCII base-conversion encodings for
//! bases of size 2, 4, 8, 16, 32, and 64. It supports:
//!
//! - [padding] for streaming
//! - canonical encodings (e.g. [trailing bits] are checked)
//! - in-place [encoding] and [decoding] functions
//! - partial [decoding] functions (e.g. for error recovery)
//! - character [translation] (e.g. for case-insensitivity)
//! - most and least significant [bit-order]
//! - [ignoring] characters when decoding (e.g. for skipping newlines)
//! - [wrapping] the output when encoding
//! - no-std environments with `default-features = false, features = ["alloc"]`
//! - no-alloc environments with `default-features = false`
//!
//! You may use the [binary] or the [website] to play around.
//!
//! # Examples
//!
//! This crate provides predefined encodings as [constants]. These constants are of type
//! [`Encoding`]. This type provides encoding and decoding functions with in-place or allocating
//! variants. Here is an example using the allocating encoding function of [`BASE64`]:
//!
//! ```rust
//! use data_encoding::BASE64;
//! assert_eq!(BASE64.encode(b"Hello world"), "SGVsbG8gd29ybGQ=");
//! ```
//!
//! Here is an example using the in-place decoding function of [`BASE32`]:
//!
//! ```rust
//! use data_encoding::BASE32;
//! let input = b"JBSWY3DPEB3W64TMMQ======";
//! let mut output = vec![0; BASE32.decode_len(input.len()).unwrap()];
//! let len = BASE32.decode_mut(input, &mut output).unwrap();
//! assert_eq!(&output[0 .. len], b"Hello world");
//! ```
//!
//! You are not limited to the predefined encodings. You may define your own encodings (with the
//! same correctness and performance properties as the predefined ones) using the [`Specification`]
//! type:
//!
//! ```rust
//! use data_encoding::Specification;
//! let hex = {
//! let mut spec = Specification::new();
//! spec.symbols.push_str("0123456789abcdef");
//! spec.encoding().unwrap()
//! };
//! assert_eq!(hex.encode(b"hello"), "68656c6c6f");
//! ```
//!
//! You may use the [macro] library to define a compile-time custom encoding:
//!
//! ```rust,ignore
//! use data_encoding::Encoding;
//! use data_encoding_macro::new_encoding;
//! const HEX: Encoding = new_encoding!{
//! symbols: "0123456789abcdef",
//! translate_from: "ABCDEF",
//! translate_to: "abcdef",
//! };
//! const BASE64: Encoding = new_encoding!{
//! symbols: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",
//! padding: '=',
//! };
//! ```
//!
//! # Properties
//!
//! The [`HEXUPPER`], [`BASE32`], [`BASE32HEX`], [`BASE64`], and [`BASE64URL`] predefined encodings
//! conform to [RFC4648].
//!
//! In general, the encoding and decoding functions satisfy the following properties:
//!
//! - They are deterministic: their output only depends on their input
//! - They have no side-effects: they do not modify any hidden mutable state
//! - They are correct: encoding followed by decoding gives the initial data
//! - They are canonical (unless [`is_canonical`] returns false): decoding followed by encoding
//! gives the initial data
//!
//! This last property is usually not satisfied by base64 implementations. This is a matter of
//! choice and this crate has made the choice to let the user choose. Support for canonical encoding
//! as described by the [RFC][canonical] is provided. But it is also possible to disable checking
//! trailing bits, to add characters translation, to decode concatenated padded inputs, and to
//! ignore some characters. Note that non-canonical encodings may be an attack vector as described
//! in [Base64 Malleability in Practice](https://eprint.iacr.org/2022/361.pdf).
//!
//! Since the RFC specifies the encoding function on all inputs and the decoding function on all
//! possible encoded outputs, the differences between implementations come from the decoding
//! function which may be more or less permissive. In this crate, the decoding function of canonical
//! encodings rejects all inputs that are not a possible output of the encoding function. Here are
//! some concrete examples of decoding differences between this crate, the `base64` crate, and the
//! `base64` GNU program:
//!
//! | Input | `data-encoding` | `base64` | GNU `base64` |
//! | ---------- | --------------- | --------- | ------------- |
//! | `AAB=` | `Trailing(2)` | `Last(2)` | `\x00\x00` |
//! | `AA\nB=` | `Length(4)` | `Byte(2)` | `\x00\x00` |
//! | `AAB` | `Length(0)` | `Padding` | Invalid input |
//! | `AAA` | `Length(0)` | `Padding` | Invalid input |
//! | `A\rA\nB=` | `Length(4)` | `Byte(1)` | Invalid input |
//! | `-_\r\n` | `Symbol(0)` | `Byte(0)` | Invalid input |
//! | `AA==AA==` | `[0, 0]` | `Byte(2)` | `\x00\x00` |
//!
//! We can summarize these discrepancies as follows:
//!
//! | Discrepancy | `data-encoding` | `base64` | GNU `base64` |
//! | -------------------------- | --------------- | -------- | ------------ |
//! | Check trailing bits | Yes | Yes | No |
//! | Ignored characters | None | None | `\n` |
//! | Translated characters | None | None | None |
//! | Check padding | Yes | No | Yes |
//! | Support concatenated input | Yes | No | Yes |
//!
//! This crate permits to disable checking trailing bits. It permits to ignore some characters. It
//! permits to translate characters. It permits to use unpadded encodings. However, for padded
//! encodings, support for concatenated inputs cannot be disabled. This is simply because it doesn't
//! make sense to use padding if it is not to support concatenated inputs.
//!
//! [RFC4648]: https://tools.ietf.org/html/rfc4648
//! [`BASE32HEX`]: constant.BASE32HEX.html
//! [`BASE32`]: constant.BASE32.html
//! [`BASE64URL`]: constant.BASE64URL.html
//! [`BASE64`]: constant.BASE64.html
//! [`Encoding`]: struct.Encoding.html
//! [`HEXUPPER`]: constant.HEXUPPER.html
//! [`Specification`]: struct.Specification.html
//! [`is_canonical`]: struct.Encoding.html#method.is_canonical
//! [binary]: https://crates.io/crates/data-encoding-bin
//! [bit-order]: struct.Specification.html#structfield.bit_order
//! [canonical]: https://tools.ietf.org/html/rfc4648#section-3.5
//! [constants]: index.html#constants
//! [crate]: https://crates.io/crates/data-encoding
//! [decoding]: struct.Encoding.html#method.decode_mut
//! [encoding]: struct.Encoding.html#method.encode_mut
//! [ignoring]: struct.Specification.html#structfield.ignore
//! [macro]: https://crates.io/crates/data-encoding-macro
//! [padding]: struct.Specification.html#structfield.padding
//! [trailing bits]: struct.Specification.html#structfield.check_trailing_bits
//! [translation]: struct.Specification.html#structfield.translate
//! [website]: https://data-encoding.rs
//! [wrapping]: struct.Specification.html#structfield.wrap
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(feature = "std")]
extern crate std;
#[cfg(feature = "alloc")]
use alloc::borrow::{Cow, ToOwned};
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(feature = "alloc")]
use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
use core::convert::TryInto;
use core::debug_assert as safety_assert;
macro_rules! check {
($e: expr, $c: expr) => {
if !$c {
return Err($e);
}
};
}
trait Static<T: Copy>: Copy {
fn val(self) -> T;
}
macro_rules! define {
($name: ident: $type: ty = $val: expr) => {
#[derive(Copy, Clone)]
struct $name;
impl Static<$type> for $name {
fn val(self) -> $type {
$val
}
}
};
}
define!(Bf: bool = false);
define!(Bt: bool = true);
define!(N1: usize = 1);
define!(N2: usize = 2);
define!(N3: usize = 3);
define!(N4: usize = 4);
define!(N5: usize = 5);
define!(N6: usize = 6);
#[derive(Copy, Clone)]
struct On;
impl<T: Copy> Static<Option<T>> for On {
fn val(self) -> Option<T> {
None
}
}
#[derive(Copy, Clone)]
struct Os<T>(T);
impl<T: Copy> Static<Option<T>> for Os<T> {
fn val(self) -> Option<T> {
Some(self.0)
}
}
macro_rules! dispatch {
(let $var: ident: bool = $val: expr; $($body: tt)*) => {
if $val {
let $var = Bt; dispatch!($($body)*)
} else {
let $var = Bf; dispatch!($($body)*)
}
};
(let $var: ident: usize = $val: expr; $($body: tt)*) => {
match $val {
1 => { let $var = N1; dispatch!($($body)*) },
2 => { let $var = N2; dispatch!($($body)*) },
3 => { let $var = N3; dispatch!($($body)*) },
4 => { let $var = N4; dispatch!($($body)*) },
5 => { let $var = N5; dispatch!($($body)*) },
6 => { let $var = N6; dispatch!($($body)*) },
_ => panic!(),
}
};
(let $var: ident: Option<$type: ty> = $val: expr; $($body: tt)*) => {
match $val {
None => { let $var = On; dispatch!($($body)*) },
Some(x) => { let $var = Os(x); dispatch!($($body)*) },
}
};
($body: expr) => { $body };
}
fn chunk_unchecked<T>(x: &[T], n: usize, i: usize) -> &[T] {
safety_assert!((i + 1) * n <= x.len());
// SAFETY: Ensured by correctness requirements (and asserted above).
unsafe { core::slice::from_raw_parts(x.as_ptr().add(n * i), n) }
}
fn chunk_mut_unchecked<T>(x: &mut [T], n: usize, i: usize) -> &mut [T] {
safety_assert!((i + 1) * n <= x.len());
// SAFETY: Ensured by correctness requirements (and asserted above).
unsafe { core::slice::from_raw_parts_mut(x.as_mut_ptr().add(n * i), n) }
}
fn div_ceil(x: usize, m: usize) -> usize {
(x + m - 1) / m
}
fn floor(x: usize, m: usize) -> usize {
x / m * m
}
#[inline]
fn vectorize<F: FnMut(usize)>(n: usize, bs: usize, mut f: F) {
for k in 0 .. n / bs {
for i in k * bs .. (k + 1) * bs {
f(i);
}
}
for i in floor(n, bs) .. n {
f(i);
}
}
/// Decoding error kind
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum DecodeKind {
/// Invalid length
Length,
/// Invalid symbol
Symbol,
/// Non-zero trailing bits
Trailing,
/// Invalid padding length
Padding,
}
impl core::fmt::Display for DecodeKind {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let description = match self {
DecodeKind::Length => "invalid length",
DecodeKind::Symbol => "invalid symbol",
DecodeKind::Trailing => "non-zero trailing bits",
DecodeKind::Padding => "invalid padding length",
};
write!(f, "{}", description)
}
}
/// Decoding error
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct DecodeError {
/// Error position
///
/// This position is always a valid input position and represents the first encountered error.
pub position: usize,
/// Error kind
pub kind: DecodeKind,
}
#[cfg(feature = "std")]
impl std::error::Error for DecodeError {}
impl core::fmt::Display for DecodeError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{} at {}", self.kind, self.position)
}
}
/// Decoding error with partial result
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct DecodePartial {
/// Number of bytes read from input
///
/// This number does not exceed the error position: `read <= error.position`.
pub read: usize,
/// Number of bytes written to output
///
/// This number does not exceed the decoded length: `written <= decode_len(read)`.
pub written: usize,
/// Decoding error
pub error: DecodeError,
}
const INVALID: u8 = 128;
const IGNORE: u8 = 129;
const PADDING: u8 = 130;
fn order(msb: bool, n: usize, i: usize) -> usize {
if msb {
n - 1 - i
} else {
i
}
}
#[inline]
fn enc(bit: usize) -> usize {
match bit {
1 | 2 | 4 => 1,
3 | 6 => 3,
5 => 5,
_ => unreachable!(),
}
}
#[inline]
fn dec(bit: usize) -> usize {
enc(bit) * 8 / bit
}
fn encode_len<B: Static<usize>>(bit: B, len: usize) -> usize {
div_ceil(8 * len, bit.val())
}
fn encode_block<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, symbols: &[u8; 256], input: &[u8], output: &mut [u8],
) {
debug_assert!(input.len() <= enc(bit.val()));
debug_assert_eq!(output.len(), encode_len(bit, input.len()));
let bit = bit.val();
let msb = msb.val();
let mut x = 0u64;
for (i, input) in input.iter().enumerate() {
x |= u64::from(*input) << (8 * order(msb, enc(bit), i));
}
for (i, output) in output.iter_mut().enumerate() {
let y = x >> (bit * order(msb, dec(bit), i));
*output = symbols[(y & 0xff) as usize];
}
}
fn encode_mut<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, symbols: &[u8; 256], input: &[u8], output: &mut [u8],
) {
debug_assert_eq!(output.len(), encode_len(bit, input.len()));
let enc = enc(bit.val());
let dec = dec(bit.val());
let n = input.len() / enc;
let bs = match bit.val() {
5 => 2,
6 => 4,
_ => 1,
};
vectorize(n, bs, |i| {
let input = chunk_unchecked(input, enc, i);
let output = chunk_mut_unchecked(output, dec, i);
encode_block(bit, msb, symbols, input, output);
});
encode_block(bit, msb, symbols, &input[enc * n ..], &mut output[dec * n ..]);
}
// Fails if an input character does not translate to a symbol. The error is the
// lowest index of such character. The output is not written to.
fn decode_block<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, values: &[u8; 256], input: &[u8], output: &mut [u8],
) -> Result<(), usize> {
debug_assert!(output.len() <= enc(bit.val()));
debug_assert_eq!(input.len(), encode_len(bit, output.len()));
let bit = bit.val();
let msb = msb.val();
let mut x = 0u64;
for j in 0 .. input.len() {
let y = values[input[j] as usize];
check!(j, y < 1 << bit);
x |= u64::from(y) << (bit * order(msb, dec(bit), j));
}
for (j, output) in output.iter_mut().enumerate() {
*output = ((x >> (8 * order(msb, enc(bit), j))) & 0xff) as u8;
}
Ok(())
}
// Fails if an input character does not translate to a symbol. The error `pos`
// is the lowest index of such character. The output is valid up to `pos / dec *
// enc` excluded.
fn decode_mut<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, values: &[u8; 256], input: &[u8], output: &mut [u8],
) -> Result<(), usize> {
debug_assert_eq!(input.len(), encode_len(bit, output.len()));
let enc = enc(bit.val());
let dec = dec(bit.val());
let n = input.len() / dec;
for i in 0 .. n {
let input = chunk_unchecked(input, dec, i);
let output = chunk_mut_unchecked(output, enc, i);
decode_block(bit, msb, values, input, output).map_err(|e| dec * i + e)?;
}
decode_block(bit, msb, values, &input[dec * n ..], &mut output[enc * n ..])
.map_err(|e| dec * n + e)
}
// Fails if there are non-zero trailing bits.
fn check_trail<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], input: &[u8],
) -> Result<(), ()> {
if 8 % bit.val() == 0 || !ctb {
return Ok(());
}
let trail = bit.val() * input.len() % 8;
if trail == 0 {
return Ok(());
}
let mut mask = (1 << trail) - 1;
if !msb.val() {
mask <<= bit.val() - trail;
}
check!((), values[input[input.len() - 1] as usize] & mask == 0);
Ok(())
}
// Fails if the padding length is invalid. The error is the index of the first
// padding character.
fn check_pad<B: Static<usize>>(bit: B, values: &[u8; 256], input: &[u8]) -> Result<usize, usize> {
let bit = bit.val();
debug_assert_eq!(input.len(), dec(bit));
let is_pad = |x: &&u8| values[**x as usize] == PADDING;
let count = input.iter().rev().take_while(is_pad).count();
let len = input.len() - count;
check!(len, len > 0 && bit * len % 8 < bit);
Ok(len)
}
fn encode_base_len<B: Static<usize>>(bit: B, len: usize) -> usize {
encode_len(bit, len)
}
fn encode_base<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, symbols: &[u8; 256], input: &[u8], output: &mut [u8],
) {
debug_assert_eq!(output.len(), encode_base_len(bit, input.len()));
encode_mut(bit, msb, symbols, input, output);
}
fn encode_pad_len<B: Static<usize>, P: Static<Option<u8>>>(bit: B, pad: P, len: usize) -> usize {
match pad.val() {
None => encode_base_len(bit, len),
Some(_) => div_ceil(len, enc(bit.val())) * dec(bit.val()),
}
}
fn encode_pad<B: Static<usize>, M: Static<bool>, P: Static<Option<u8>>>(
bit: B, msb: M, symbols: &[u8; 256], spad: P, input: &[u8], output: &mut [u8],
) {
let pad = match spad.val() {
None => return encode_base(bit, msb, symbols, input, output),
Some(pad) => pad,
};
debug_assert_eq!(output.len(), encode_pad_len(bit, spad, input.len()));
let olen = encode_base_len(bit, input.len());
encode_base(bit, msb, symbols, input, &mut output[.. olen]);
for output in output.iter_mut().skip(olen) {
*output = pad;
}
}
fn encode_wrap_len<
'a,
B: Static<usize>,
P: Static<Option<u8>>,
W: Static<Option<(usize, &'a [u8])>>,
>(
bit: B, pad: P, wrap: W, ilen: usize,
) -> usize {
let olen = encode_pad_len(bit, pad, ilen);
match wrap.val() {
None => olen,
Some((col, end)) => olen + end.len() * div_ceil(olen, col),
}
}
fn encode_wrap_mut<
'a,
B: Static<usize>,
M: Static<bool>,
P: Static<Option<u8>>,
W: Static<Option<(usize, &'a [u8])>>,
>(
bit: B, msb: M, symbols: &[u8; 256], pad: P, wrap: W, input: &[u8], output: &mut [u8],
) {
let (col, end) = match wrap.val() {
None => return encode_pad(bit, msb, symbols, pad, input, output),
Some((col, end)) => (col, end),
};
debug_assert_eq!(output.len(), encode_wrap_len(bit, pad, wrap, input.len()));
debug_assert_eq!(col % dec(bit.val()), 0);
let col = col / dec(bit.val());
let enc = col * enc(bit.val());
let dec = col * dec(bit.val()) + end.len();
let olen = dec - end.len();
let n = input.len() / enc;
for i in 0 .. n {
let input = chunk_unchecked(input, enc, i);
let output = chunk_mut_unchecked(output, dec, i);
encode_base(bit, msb, symbols, input, &mut output[.. olen]);
output[olen ..].copy_from_slice(end);
}
if input.len() > enc * n {
let olen = dec * n + encode_pad_len(bit, pad, input.len() - enc * n);
encode_pad(bit, msb, symbols, pad, &input[enc * n ..], &mut output[dec * n .. olen]);
output[olen ..].copy_from_slice(end);
}
}
// Returns the longest valid input length and associated output length.
fn decode_wrap_len<B: Static<usize>, P: Static<bool>>(
bit: B, pad: P, len: usize,
) -> (usize, usize) {
let bit = bit.val();
if pad.val() {
(floor(len, dec(bit)), len / dec(bit) * enc(bit))
} else {
let trail = bit * len % 8;
(len - trail / bit, bit * len / 8)
}
}
// Fails with Length if length is invalid. The error is the largest valid
// length.
fn decode_pad_len<B: Static<usize>, P: Static<bool>>(
bit: B, pad: P, len: usize,
) -> Result<usize, DecodeError> {
let (ilen, olen) = decode_wrap_len(bit, pad, len);
check!(DecodeError { position: ilen, kind: DecodeKind::Length }, ilen == len);
Ok(olen)
}
// Fails with Length if length is invalid. The error is the largest valid
// length.
fn decode_base_len<B: Static<usize>>(bit: B, len: usize) -> Result<usize, DecodeError> {
decode_pad_len(bit, Bf, len)
}
// Fails with Symbol if an input character does not translate to a symbol. The
// error is the lowest index of such character.
// Fails with Trailing if there are non-zero trailing bits.
fn decode_base_mut<B: Static<usize>, M: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], input: &[u8], output: &mut [u8],
) -> Result<usize, DecodePartial> {
debug_assert_eq!(Ok(output.len()), decode_base_len(bit, input.len()));
let fail = |pos, kind| DecodePartial {
read: pos / dec(bit.val()) * dec(bit.val()),
written: pos / dec(bit.val()) * enc(bit.val()),
error: DecodeError { position: pos, kind },
};
decode_mut(bit, msb, values, input, output).map_err(|pos| fail(pos, DecodeKind::Symbol))?;
check_trail(bit, msb, ctb, values, input)
.map_err(|()| fail(input.len() - 1, DecodeKind::Trailing))?;
Ok(output.len())
}
// Fails with Symbol if an input character does not translate to a symbol. The
// error is the lowest index of such character.
// Fails with Padding if some padding length is invalid. The error is the index
// of the first padding character of the invalid padding.
// Fails with Trailing if there are non-zero trailing bits.
fn decode_pad_mut<B: Static<usize>, M: Static<bool>, P: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], pad: P, input: &[u8], output: &mut [u8],
) -> Result<usize, DecodePartial> {
if !pad.val() {
return decode_base_mut(bit, msb, ctb, values, input, output);
}
debug_assert_eq!(Ok(output.len()), decode_pad_len(bit, pad, input.len()));
let enc = enc(bit.val());
let dec = dec(bit.val());
let mut inpos = 0;
let mut outpos = 0;
let mut outend = output.len();
while inpos < input.len() {
match decode_base_mut(
bit,
msb,
ctb,
values,
&input[inpos ..],
&mut output[outpos .. outend],
) {
Ok(written) => {
if cfg!(debug_assertions) {
inpos = input.len();
}
outpos += written;
break;
}
Err(partial) => {
inpos += partial.read;
outpos += partial.written;
}
}
let inlen =
check_pad(bit, values, &input[inpos .. inpos + dec]).map_err(|pos| DecodePartial {
read: inpos,
written: outpos,
error: DecodeError { position: inpos + pos, kind: DecodeKind::Padding },
})?;
let outlen = decode_base_len(bit, inlen).unwrap();
let written = decode_base_mut(
bit,
msb,
ctb,
values,
&input[inpos .. inpos + inlen],
&mut output[outpos .. outpos + outlen],
)
.map_err(|partial| {
debug_assert_eq!(partial.read, 0);
debug_assert_eq!(partial.written, 0);
DecodePartial {
read: inpos,
written: outpos,
error: DecodeError {
position: inpos + partial.error.position,
kind: partial.error.kind,
},
}
})?;
debug_assert_eq!(written, outlen);
inpos += dec;
outpos += outlen;
outend -= enc - outlen;
}
debug_assert_eq!(inpos, input.len());
debug_assert_eq!(outpos, outend);
Ok(outend)
}
fn skip_ignore(values: &[u8; 256], input: &[u8], mut inpos: usize) -> usize {
while inpos < input.len() && values[input[inpos] as usize] == IGNORE {
inpos += 1;
}
inpos
}
// Returns next input and output position.
// Fails with Symbol if an input character does not translate to a symbol. The
// error is the lowest index of such character.
// Fails with Padding if some padding length is invalid. The error is the index
// of the first padding character of the invalid padding.
// Fails with Trailing if there are non-zero trailing bits.
fn decode_wrap_block<B: Static<usize>, M: Static<bool>, P: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], pad: P, input: &[u8], output: &mut [u8],
) -> Result<(usize, usize), DecodeError> {
let dec = dec(bit.val());
let mut buf = [0u8; 8];
let mut shift = [0usize; 8];
let mut bufpos = 0;
let mut inpos = 0;
while bufpos < dec {
inpos = skip_ignore(values, input, inpos);
if inpos == input.len() {
break;
}
shift[bufpos] = inpos;
buf[bufpos] = input[inpos];
bufpos += 1;
inpos += 1;
}
let olen = decode_pad_len(bit, pad, bufpos).map_err(|mut e| {
e.position = shift[e.position];
e
})?;
let written = decode_pad_mut(bit, msb, ctb, values, pad, &buf[.. bufpos], &mut output[.. olen])
.map_err(|partial| {
debug_assert_eq!(partial.read, 0);
debug_assert_eq!(partial.written, 0);
DecodeError { position: shift[partial.error.position], kind: partial.error.kind }
})?;
Ok((inpos, written))
}
// Fails with Symbol if an input character does not translate to a symbol. The
// error is the lowest index of such character.
// Fails with Padding if some padding length is invalid. The error is the index
// of the first padding character of the invalid padding.
// Fails with Trailing if there are non-zero trailing bits.
// Fails with Length if input length (without ignored characters) is invalid.
#[allow(clippy::too_many_arguments)]
fn decode_wrap_mut<B: Static<usize>, M: Static<bool>, P: Static<bool>, I: Static<bool>>(
bit: B, msb: M, ctb: bool, values: &[u8; 256], pad: P, has_ignore: I, input: &[u8],
output: &mut [u8],
) -> Result<usize, DecodePartial> {
if !has_ignore.val() {
return decode_pad_mut(bit, msb, ctb, values, pad, input, output);
}
debug_assert_eq!(output.len(), decode_wrap_len(bit, pad, input.len()).1);
let mut inpos = 0;
let mut outpos = 0;
while inpos < input.len() {
let (inlen, outlen) = decode_wrap_len(bit, pad, input.len() - inpos);
match decode_pad_mut(
bit,
msb,
ctb,
values,
pad,
&input[inpos .. inpos + inlen],
&mut output[outpos .. outpos + outlen],
) {
Ok(written) => {
inpos += inlen;
outpos += written;
break;
}
Err(partial) => {
inpos += partial.read;
outpos += partial.written;
}
}
let (ipos, opos) =
decode_wrap_block(bit, msb, ctb, values, pad, &input[inpos ..], &mut output[outpos ..])
.map_err(|mut error| {
error.position += inpos;
DecodePartial { read: inpos, written: outpos, error }
})?;
inpos += ipos;
outpos += opos;
}
let inpos = skip_ignore(values, input, inpos);
if inpos == input.len() {
Ok(outpos)
} else {
Err(DecodePartial {
read: inpos,
written: outpos,
error: DecodeError { position: inpos, kind: DecodeKind::Length },
})
}
}
/// Order in which bits are read from a byte
///
/// The base-conversion encoding is always little-endian. This means that the least significant
/// **byte** is always first. However, we can still choose whether, within a byte, this is the most
/// significant or the least significant **bit** that is first. If the terminology is confusing,
/// testing on an asymmetrical example should be enough to choose the correct value.
///
/// # Examples
///
/// In the following example, we can see that a base with the `MostSignificantFirst` bit-order has
/// the most significant bit first in the encoded output. In particular, the output is in the same
/// order as the bits in the byte. The opposite happens with the `LeastSignificantFirst` bit-order.
/// The least significant bit is first and the output is in the reverse order.
///
/// ```rust
/// use data_encoding::{BitOrder, Specification};
/// let mut spec = Specification::new();
/// spec.symbols.push_str("01");
/// spec.bit_order = BitOrder::MostSignificantFirst; // default
/// let msb = spec.encoding().unwrap();
/// spec.bit_order = BitOrder::LeastSignificantFirst;
/// let lsb = spec.encoding().unwrap();
/// assert_eq!(msb.encode(&[0b01010011]), "01010011");
/// assert_eq!(lsb.encode(&[0b01010011]), "11001010");
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg(feature = "alloc")]
pub enum BitOrder {
/// Most significant bit first
///
/// This is the most common and most intuitive bit-order. In particular, this is the bit-order
/// used by [RFC4648] and thus the usual hexadecimal, base64, base32, base64url, and base32hex
/// encodings. This is the default bit-order when [specifying](struct.Specification.html) a
/// base.
///
/// [RFC4648]: https://tools.ietf.org/html/rfc4648
MostSignificantFirst,
/// Least significant bit first
///
/// # Examples
///
/// DNSCurve [base32] uses least significant bit first:
///
/// ```rust
/// use data_encoding::BASE32_DNSCURVE;
/// assert_eq!(BASE32_DNSCURVE.encode(&[0x64, 0x88]), "4321");
/// assert_eq!(BASE32_DNSCURVE.decode(b"4321").unwrap(), vec![0x64, 0x88]);
/// ```
///
/// [base32]: constant.BASE32_DNSCURVE.html
LeastSignificantFirst,
}
#[cfg(feature = "alloc")]
use crate::BitOrder::*;
/// Interpretation of a byte for decoding purposes
///
/// For a given encoding, a byte can either be a symbol of that encoding (with a value within the
/// number of symbols of that encoding), a padding character, an ignored character, or an invalid
/// character.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Character {
/// A symbol
Symbol {
/// The value of the symbol
value: usize,
},
/// A padding character
Padding,
/// An ignored character
Ignored,
/// An invalid character
Invalid,
}
impl Character {
/// Returns whether the character is a symbol
///
/// If the character is a symbol, its value is returned.
pub fn is_symbol(self) -> Option<usize> {
match self {
Character::Symbol { value } => Some(value),
_ => None,
}
}
/// Returns whether the character is padding
pub fn is_padding(self) -> bool {
matches!(self, Character::Padding)
}
/// Returns whether the character is ignored
pub fn is_ignored(self) -> bool {
matches!(self, Character::Ignored)
}
/// Returns whether the character is invalid
pub fn is_invalid(self) -> bool {
matches!(self, Character::Invalid)
}
}
#[doc(hidden)]
#[cfg(feature = "alloc")]
pub type InternalEncoding = Cow<'static, [u8]>;
#[doc(hidden)]
#[cfg(not(feature = "alloc"))]
pub type InternalEncoding = &'static [u8];
/// Base-conversion encoding
///
/// See [Specification](struct.Specification.html) for technical details or how to define a new one.
// Required fields:
// 0 - 256 (256) symbols
// 256 - 512 (256) values
// 512 - 513 ( 1) padding
// 513 - 514 ( 1) reserved(3),ctb(1),msb(1),bit(3)
// Optional fields:
// 514 - 515 ( 1) width
// 515 - * ( N) separator
// Invariants:
// - symbols is 2^bit unique characters repeated 2^(8-bit) times
// - values[128 ..] are INVALID
// - values[0 .. 128] are either INVALID, IGNORE, PADDING, or < 2^bit
// - padding is either < 128 or INVALID
// - values[padding] is PADDING if padding < 128
// - values and symbols are inverse
// - ctb is true if 8 % bit == 0
// - width is present if there is x such that values[x] is IGNORE
// - width % dec(bit) == 0
// - for all x in separator values[x] is IGNORE
#[derive(Debug, Clone, PartialEq, Eq)]
#[repr(transparent)]
pub struct Encoding(#[doc(hidden)] pub InternalEncoding);
/// How to translate characters when decoding
///
/// The order matters. The first character of the `from` field is translated to the first character
/// of the `to` field. The second to the second. Etc.
///
/// See [Specification](struct.Specification.html) for more information.
#[derive(Debug, Clone)]
#[cfg(feature = "alloc")]
pub struct Translate {
/// Characters to translate from
pub from: String,
/// Characters to translate to
pub to: String,
}
/// How to wrap the output when encoding
///
/// See [Specification](struct.Specification.html) for more information.
#[derive(Debug, Clone)]
#[cfg(feature = "alloc")]
pub struct Wrap {
/// Wrapping width
///
/// Must be a multiple of:
///
/// - 8 for a bit-width of 1 (binary), 3 (octal), and 5 (base32)
/// - 4 for a bit-width of 2 (base4) and 6 (base64)
/// - 2 for a bit-width of 4 (hexadecimal)
///
/// Wrapping is disabled if null.
pub width: usize,
/// Wrapping characters
///
/// Wrapping is disabled if empty.
pub separator: String,
}
/// Base-conversion specification
///
/// It is possible to define custom encodings given a specification. To do so, it is important to
/// understand the theory first.
///
/// # Theory
///
/// Each subsection has an equivalent subsection in the [Practice](#practice) section.
///
/// ## Basics
///
/// The main idea of a [base-conversion] encoding is to see `[u8]` as numbers written in
/// little-endian base256 and convert them in another little-endian base. For performance reasons,
/// this crate restricts this other base to be of size 2 (binary), 4 (base4), 8 (octal), 16
/// (hexadecimal), 32 (base32), or 64 (base64). The converted number is written as `[u8]` although
/// it doesn't use all the 256 possible values of `u8`. This crate encodes to ASCII, so only values
/// smaller than 128 are allowed.
///
/// More precisely, we need the following elements:
///
/// - The bit-width N: 1 for binary, 2 for base4, 3 for octal, 4 for hexadecimal, 5 for base32, and
/// 6 for base64
/// - The [bit-order](enum.BitOrder.html): most or least significant bit first
/// - The symbols function S from [0, 2<sup>N</sup>) (called values and written `uN`) to symbols
/// (represented as `u8` although only ASCII symbols are allowed, i.e. smaller than 128)
/// - The values partial function V from ASCII to [0, 2<sup>N</sup>), i.e. from `u8` to `uN`
/// - Whether trailing bits are checked: trailing bits are leading zeros in theory, but since
/// numbers are little-endian they come last
///
/// For the encoding to be correct (i.e. encoding then decoding gives back the initial input),
/// V(S(i)) must be defined and equal to i for all i in [0, 2<sup>N</sup>). For the encoding to be
/// [canonical][canonical] (i.e. different inputs decode to different outputs, or equivalently,
/// decoding then encoding gives back the initial input), trailing bits must be checked and if V(i)
/// is defined then S(V(i)) is equal to i for all i.
///