sha3_utils/
enc.rs

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
#![allow(
    clippy::indexing_slicing,
    reason = "The compiler can prove that the indices are in bounds"
)]
#![allow(
    clippy::arithmetic_side_effects,
    reason = "All arithmetic is in bounds"
)]

use core::{
    array, cmp, hint,
    iter::{ExactSizeIterator, FusedIterator},
};

#[cfg(feature = "no-panic")]
use no_panic::no_panic;
use typenum::{
    generic_const_mappings::{Const, ToUInt, U},
    operator_aliases::{Add1, Prod},
    type_operators::IsGreaterOrEqual,
    U2,
};

use super::util::as_chunks;

/// The size in bytes of [`usize`].
const USIZE_BYTES: usize = ((usize::BITS + 7) / 8) as usize;

// This is silly, but it ensures that we're always in
//    [0, ((2^2040)-1)/8]
// which is required by SP 800-185, which requires that
// `left_encode`, `right_encode`, etc. accept integers up to
// (2^2040)-1.
//
// Divide by 8 because of the `*_bytes` routines.
const _: () = assert!(USIZE_BYTES <= 255);

/// Encodes `x` as a byte string in a way that can be
/// unambiguously parsed from the beginning.
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn left_encode(mut x: usize) -> LeftEncode {
    // `x|1` ensures that `n < USIZE_BYTES`. It's cheaper than
    // using a conditional.
    let n = (x | 1).leading_zeros() / 8;
    // Shift into the leading zeros so that we write everything
    // at the start of the buffer. This lets us use constants for
    // writing, as well as lets us use fixed-size writes (see
    // `bytepad_blocks`, etc.).
    x <<= n * 8;

    let mut buf = [0; 1 + USIZE_BYTES];
    buf[0] = (USIZE_BYTES - n as usize) as u8;
    buf[1..].copy_from_slice(&x.to_be_bytes());

    LeftEncode { buf }
}

/// The result of [`left_encode`].
#[derive(Copy, Clone, Debug)]
pub struct LeftEncode {
    // Invariant: `buf[0]` is in [0, buf.len()-1).
    buf: [u8; 1 + USIZE_BYTES],
}

impl LeftEncode {
    /// Returns the number of encoded bytes.
    #[inline]
    #[allow(clippy::len_without_is_empty, reason = "Meaningless for this type")]
    pub const fn len(&self) -> usize {
        (self.buf[0] + 1) as usize
    }

    /// Returns the encoded bytes.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: `self.len()` is in [1, self.buf.len()).
        unsafe { self.buf.get_unchecked(..self.len()) }
    }
}

impl AsRef<[u8]> for LeftEncode {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Eq for LeftEncode {}
impl PartialEq for LeftEncode {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.as_bytes() == rhs.as_bytes()
    }
}

/// Encodes `x*8` as a byte string in a way that can be
/// unambiguously parsed from the beginning.
///
/// # Rationale
///
/// [`left_encode`] is typically used to encode a length in
/// *bits*. In practice, we usually have a length in *bytes*. The
/// conversion from bytes to bits might overflow if the number of
/// bytes is large. This method avoids overflowing.
///
/// # Example
///
/// ```rust
/// use sha3_utils::{left_encode, left_encode_bytes};
///
/// assert_eq!(
///     left_encode(8192 * 8).as_bytes(),
///     left_encode_bytes(8192).as_bytes(),
/// );
///
/// // usize::MAX*8 overflows, causing an incorrect result.
/// assert_ne!(
///     left_encode(usize::MAX.wrapping_mul(8)).as_bytes(),
///     left_encode_bytes(usize::MAX).as_bytes(),
/// );
/// ```
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn left_encode_bytes(x: usize) -> LeftEncodeBytes {
    // Break `x*8` into double word arithmetic.
    let mut hi = (x >> (usize::BITS - 3)) as u8;
    let mut lo = x << 3;

    let n = if hi == 0 {
        // `lo|1` ensures that `n < USIZE_BYTES`. It's cheaper
        // than a conditional.
        let n = (lo | 1).leading_zeros() / 8;
        lo <<= n * 8;
        hi = (lo >> (usize::BITS - 8)) as u8;
        lo <<= 8;
        (n + 1) as usize
    } else {
        0
    };

    // This might be a smidge better than assigning to `buf[0]`
    // and `buf[1]` directly.
    let v = ((1 + USIZE_BYTES - n) as u16) | ((u16::from(hi)) << 8);

    let mut buf = [0; 2 + USIZE_BYTES];
    buf[..2].copy_from_slice(&v.to_le_bytes());
    buf[2..].copy_from_slice(&lo.to_be_bytes());

    LeftEncodeBytes { buf }
}

/// The result of [`left_encode_bytes`].
#[derive(Copy, Clone, Debug)]
pub struct LeftEncodeBytes {
    // Invariant: `buf[0]` is in [0, buf.len()-1).
    buf: [u8; 2 + USIZE_BYTES],
}

impl LeftEncodeBytes {
    /// Returns the number of encoded bytes.
    #[inline]
    #[allow(clippy::len_without_is_empty, reason = "Meaningless for this type")]
    pub const fn len(&self) -> usize {
        (self.buf[0] + 1) as usize
    }

    /// Returns the encoded bytes.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: `self.len()` is in [1, self.buf.len()).
        unsafe { self.buf.get_unchecked(..self.len()) }
    }
}

impl AsRef<[u8]> for LeftEncodeBytes {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Eq for LeftEncodeBytes {}
impl PartialEq for LeftEncodeBytes {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.as_bytes() == rhs.as_bytes()
    }
}

/// Encodes `x` as a byte string in a way that can be
/// unambiguously parsed from the end.
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn right_encode(x: usize) -> RightEncode {
    // `x|1` ensures that `n < USIZE_BYTES`. It's cheaper than
    // using a conditional.
    let n = (x | 1).leading_zeros() / 8;

    let mut buf = [0; USIZE_BYTES + 1];
    buf[..USIZE_BYTES].copy_from_slice(&x.to_be_bytes());
    buf[buf.len() - 1] = (USIZE_BYTES - n as usize) as u8;

    RightEncode { buf }
}

/// The result of [`right_encode`].
#[derive(Copy, Clone, Debug)]
pub struct RightEncode {
    // Invariant: `buf[buf.len()-1]` is in [1, buf.len()).
    buf: [u8; USIZE_BYTES + 1],
}

impl RightEncode {
    /// Returns the number of encoded bytes.
    #[inline]
    #[allow(clippy::len_without_is_empty, reason = "Meaningless for this type")]
    pub const fn len(&self) -> usize {
        let n = self.buf[self.buf.len() - 1];
        self.buf.len() - 1 - n as usize
    }

    /// Returns the encoded bytes.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: `self.len()` is in [1, self.buf.len()).
        unsafe { self.buf.get_unchecked(self.len()..) }
    }
}

impl AsRef<[u8]> for RightEncode {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Eq for RightEncode {}
impl PartialEq for RightEncode {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.as_bytes() == rhs.as_bytes()
    }
}

/// Encodes `x*8` as a byte string in a way that can be
/// unambiguously parsed from the beginning.
///
/// # Rationale
///
/// [`right_encode`] is typically used to encode a length in
/// *bits*. In practice, we usually have a length in *bytes*. The
/// conversion from bytes to bits might overflow if the number of
/// bytes is large. This method avoids overflowing.
///
/// # Example
///
/// ```rust
/// use sha3_utils::{right_encode, right_encode_bytes};
///
/// assert_eq!(
///     right_encode(8192 * 8).as_bytes(),
///     right_encode_bytes(8192).as_bytes(),
/// );
///
/// // usize::MAX*8 overflows, causing an incorrect result.
/// assert_ne!(
///     right_encode(usize::MAX.wrapping_mul(8)).as_bytes(),
///     right_encode_bytes(usize::MAX).as_bytes(),
/// );
/// ```
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn right_encode_bytes(mut x: usize) -> RightEncodeBytes {
    // Break `x*8` into double word arithmetic.
    let hi = (x >> (usize::BITS - 3)) & 0x7;
    x <<= 3;

    // `x|1` ensures that `n < 8`. It's cheaper than the
    // obvious `if n == 8 { n = 7; }`.
    let n = if hi == 0 {
        1 + ((x | 1).leading_zeros() / 8)
    } else {
        0
    };

    let mut buf = [0; 1 + USIZE_BYTES + 1];
    buf[0] = hi as u8;
    buf[1..1 + USIZE_BYTES].copy_from_slice(&x.to_be_bytes());
    buf[1 + USIZE_BYTES] = (1 + USIZE_BYTES - n as usize) as u8;

    RightEncodeBytes { buf }
}

/// The result of [`right_encode_bytes`].
#[derive(Copy, Clone, Debug)]
pub struct RightEncodeBytes {
    // Invariant: `buf[buf.len()-1]` is in [1, buf.len()).
    buf: [u8; 1 + USIZE_BYTES + 1],
}

impl RightEncodeBytes {
    /// Returns the number of encoded bytes.
    #[inline]
    #[allow(clippy::len_without_is_empty, reason = "Meaningless for this type")]
    pub const fn len(&self) -> usize {
        let n = self.buf[self.buf.len() - 1];
        self.buf.len() - 1 - n as usize
    }

    /// Returns the encoded bytes.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn as_bytes(&self) -> &[u8] {
        // SAFETY: `self.len()` is in [1, self.buf.len()).
        unsafe { self.buf.get_unchecked(self.len()..) }
    }
}

impl AsRef<[u8]> for RightEncodeBytes {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Eq for RightEncodeBytes {}
impl PartialEq for RightEncodeBytes {
    #[inline]
    fn eq(&self, rhs: &Self) -> bool {
        self.as_bytes() == rhs.as_bytes()
    }
}

/// Encodes `s` such that it can be unambiguously encoded from
/// the beginning.
///
/// # Example
///
/// ```rust
/// use sha3_utils::encode_string;
///
/// let s = encode_string(b"hello, world!");
/// assert_eq!(
///     s.iter().flatten().copied().collect::<Vec<_>>(),
///     &[
///         1, 104,
///         104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33,
///     ],
/// );
/// ```
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn encode_string(s: &[u8]) -> EncodedString<'_> {
    let prefix = left_encode_bytes(s.len());
    EncodedString { prefix, s }
}

/// The result of [`encode_string`].
#[derive(Copy, Clone, Debug)]
pub struct EncodedString<'a> {
    prefix: LeftEncodeBytes,
    s: &'a [u8],
}

impl EncodedString<'_> {
    /// Returns an iterator over the encoded string.
    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn iter(&self) -> EncodedStringIter<'_> {
        EncodedStringIter {
            iter: [self.prefix.as_bytes(), self.s].into_iter(),
        }
    }
}

impl<'a> IntoIterator for &'a EncodedString<'a> {
    type Item = &'a [u8];
    type IntoIter = EncodedStringIter<'a>;

    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over [`EncodedString`].
#[derive(Clone, Debug)]
pub struct EncodedStringIter<'a> {
    iter: array::IntoIter<&'a [u8], 2>,
}

impl<'a> Iterator for EncodedStringIter<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    #[inline]
    fn count(self) -> usize {
        self.iter.count()
    }

    #[inline]
    fn fold<Acc, F>(self, acc: Acc, f: F) -> Acc
    where
        F: FnMut(Acc, Self::Item) -> Acc,
    {
        self.iter.fold(acc, f)
    }

    #[inline]
    fn last(self) -> Option<Self::Item> {
        self.iter.last()
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter.nth(n)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl ExactSizeIterator for EncodedStringIter<'_> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl FusedIterator for EncodedStringIter<'_> {}

/// The minimum size, in bytes, allowed by [`bytepad_blocks`].
///
/// `USIZE_BYTES` is the size in bytes of [`usize`].
pub type MinBlockSize = Prod<Add1<U<{ USIZE_BYTES }>>, U2>;

/// Same as [`bytepad`], but returns the data as blocks.
///
/// In practice, this has helped avoid needless calls to `memcpy`
/// and has helped remove panicking branches.
pub fn bytepad_blocks<const W: usize>(
    s: EncodedString<'_>,
) -> ([u8; W], &[[u8; W]], Option<[u8; W]>)
where
    Const<W>: ToUInt,
    U<W>: IsGreaterOrEqual<MinBlockSize>,
{
    // `first` is left_encode(w) || left_encode(s) || s[..n].
    let (first, n) = {
        let mut first = [0u8; W];
        let mut i = 0;

        let w = left_encode(W);
        first[..w.buf.len()].copy_from_slice(&w.buf);
        i += w.len();

        first[i..i + s.prefix.buf.len()].copy_from_slice(&s.prefix.buf);
        i += s.prefix.len();

        // Help the compiler out to avoid a bounds check.
        //
        // SAFETY:
        //
        // - `W` must be at least twice as large as
        //   `1+USIZE_BYTES`.
        // - `LeftEncode.buf` is `1+USIZE_BYTES` long.
        // - `LeftEncode.n` is always in [1, buf.len()) (i.e.,
        //   a valid index into `LeftEncode.buf`).
        //
        // Therefore, `i < first.len()`.
        //
        // TODO(eric): Figure out how to express this without
        // unsafe.
        unsafe { hint::assert_unchecked(i < first.len()) }

        let n = cmp::min(first[i..].len(), s.s.len());
        first[i..i + n].copy_from_slice(&s.s[..n]);
        (first, n)
    };

    // `mid` is s[n..m].
    let (mid, rest) = as_chunks(&s.s[n..]);

    // `last` is s[..m].
    let last = if !rest.is_empty() {
        let mut block = [0u8; W];
        block[..rest.len()].copy_from_slice(rest);
        Some(block)
    } else {
        None
    };

    (first, mid, last)
}

/// Prepends the integer encoding of `W` to `s`, then pads the
/// result to a multiple of `W`.
///
/// # Preconditions
///
/// - `W` must be non-zero.
///
/// # Example
///
/// ```rust
/// use sha3_utils::{bytepad, encode_string};
///
/// let v = bytepad::<32>(encode_string(b"hello, world!"));
/// assert_eq!(
///     v.iter().flatten().copied().collect::<Vec<_>>(),
///     &[
///         1, 32,
///         1, 104,
///         104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33,
///         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
///     ],
/// );
/// ```
#[inline]
#[cfg_attr(feature = "no-panic", no_panic)]
pub fn bytepad<const W: usize>(s: EncodedString<'_>) -> BytePad<'_, W> {
    const { assert!(W > 0) }

    BytePad {
        w: left_encode(W),
        s,
        pad: [0u8; W],
    }
}

/// The result of [`bytepad`].
#[derive(Copy, Clone, Debug)]
pub struct BytePad<'a, const W: usize> {
    w: LeftEncode,
    s: EncodedString<'a>,
    pad: [u8; W],
}

impl<const W: usize> BytePad<'_, W> {
    /// Returns an iterator over the byte-padded string.
    #[cfg_attr(feature = "no-panic", no_panic)]
    pub fn iter(&self) -> BytePadIter<'_> {
        let w = self.w.as_bytes();
        let prefix = self.s.prefix.as_bytes();
        let s = self.s.s;
        // TODO(eric): What if this overflows?
        let n = w.len() + prefix.len() + s.len();
        let m = if n % W != 0 { W - (n % W) } else { 0 };
        let pad = &self.pad[..m];
        BytePadIter {
            iter: [w, prefix, s, pad].into_iter(),
        }
    }
}

impl<'a, const W: usize> IntoIterator for &'a BytePad<'a, W> {
    type Item = &'a [u8];
    type IntoIter = BytePadIter<'a>;

    #[inline]
    #[cfg_attr(feature = "no-panic", no_panic)]
    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// An iterator over [`BytePad`].
#[derive(Clone, Debug)]
pub struct BytePadIter<'a> {
    iter: array::IntoIter<&'a [u8], 4>,
}

impl<'a> Iterator for BytePadIter<'a> {
    type Item = &'a [u8];

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next()
    }

    #[inline]
    fn count(self) -> usize {
        self.iter.count()
    }

    #[inline]
    fn fold<Acc, F>(self, acc: Acc, f: F) -> Acc
    where
        F: FnMut(Acc, Self::Item) -> Acc,
    {
        self.iter.fold(acc, f)
    }

    #[inline]
    fn last(self) -> Option<Self::Item> {
        self.iter.last()
    }

    #[inline]
    fn nth(&mut self, n: usize) -> Option<Self::Item> {
        self.iter.nth(n)
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }
}

impl ExactSizeIterator for BytePadIter<'_> {
    #[inline]
    fn len(&self) -> usize {
        self.iter.len()
    }
}

impl FusedIterator for BytePadIter<'_> {}

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

    #[test]
    fn test_left_encode() {
        assert_eq!(left_encode(0).as_bytes(), &[1, 0], "#0");
        for i in 0..usize::BITS {
            let x: usize = 1 << i;
            let mut want = vec![0; 1];
            want.extend(x.to_be_bytes().iter().skip_while(|&&v| v == 0));
            want[0] = (want.len() - 1) as u8;
            assert_eq!(left_encode(x).as_bytes(), want, "#{x}");
        }
    }

    #[test]
    fn test_left_encode_bytes() {
        for i in 0..usize::BITS {
            let x: usize = 1 << i;
            let mut want = vec![0; 1];
            want.extend(
                (8 * x as u128)
                    .to_be_bytes()
                    .iter()
                    .skip_while(|&&v| v == 0),
            );
            want[0] = (want.len() - 1) as u8;
            assert_eq!(left_encode_bytes(x).as_bytes(), want, "#{x}");
        }
    }

    #[test]
    fn test_right_encode() {
        for i in 0..usize::BITS {
            let x: usize = 1 << i;
            let mut want = Vec::from_iter(x.to_be_bytes().iter().copied().skip_while(|&v| v == 0));
            want.push(want.len() as u8);
            assert_eq!(right_encode(x).as_bytes(), want, "#{x}");
        }
    }

    #[test]
    fn test_right_encode_bytes() {
        for i in 0..usize::BITS {
            let x: usize = 1 << i;
            let mut want = Vec::from_iter(
                (8 * x as u128)
                    .to_be_bytes()
                    .iter()
                    .copied()
                    .skip_while(|&v| v == 0),
            );
            want.push(want.len() as u8);
            assert_eq!(right_encode_bytes(x).as_bytes(), want, "#{x}");
        }
    }
}