polysmelt 0.21.0

Pure-Rust 3D asset interchange: glTF/GLB reading and writing, meshopt compression, and readers for common mesh formats, SketchUp included
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
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
//! Reading a model a block at a time, so a reader never holds the whole file, and parsing
//! numbers out of its text.

use std::io::{self, Read};

/// How much of the file is in memory at once, unless a single line or token is longer.
#[cfg(feature = "fs")]
const BLOCK: usize = 256 * 1024;

/// A model read through a buffer of one block, or bytes already in memory read in place.
/// `fill` tops the buffer up and returns the bytes not yet consumed; `consume` marks some of
/// them done.
pub(crate) struct Blocks<'a> {
    /// The stream; `None` when the bytes are all in `slice`.
    source: Option<Box<dyn Read + 'a>>,
    /// The whole model, when it was in memory to begin with.
    slice: &'a [u8],
    buf: Vec<u8>,
    /// Consumed bytes at the front of the view.
    pos: usize,
    /// Filled bytes in the view.
    len: usize,
    eof: bool,
    /// The model's size, as far as is known when it was opened.
    size: u64,
}

impl<'a> Blocks<'a> {
    /// Reads `source`, whose size is about `size` bytes.
    #[cfg(feature = "fs")]
    pub fn reader(source: impl Read + 'a, size: u64) -> Self {
        let cap = usize::try_from(size).unwrap_or(BLOCK).clamp(64, BLOCK);
        Self {
            source: Some(Box::new(source)),
            slice: &[],
            buf: vec![0; cap],
            pos: 0,
            len: 0,
            eof: false,
            size,
        }
    }

    /// Bytes already in memory, read where they are.
    pub fn slice(bytes: &'a [u8]) -> Self {
        Self {
            source: None,
            slice: bytes,
            buf: Vec::new(),
            pos: 0,
            len: bytes.len(),
            eof: true,
            size: bytes.len() as u64,
        }
    }

    /// The buffered bytes, consumed or not.
    #[inline]
    fn view(&self) -> &[u8] {
        if self.source.is_some() { &self.buf } else { self.slice }
    }

    /// The unconsumed bytes, after reading as much as fits. Empty only at the end of the file.
    pub fn fill(&mut self) -> io::Result<&[u8]> {
        if let Some(source) = &mut self.source {
            if self.pos > 0 {
                self.buf.copy_within(self.pos..self.len, 0);
                self.len -= self.pos;
                self.pos = 0;
            }
            while self.len < self.buf.len() && !self.eof {
                match source.read(&mut self.buf[self.len..]) {
                    Ok(0) => self.eof = true,
                    Ok(n) => self.len += n,
                    Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                    Err(e) => return Err(e),
                }
            }
        }
        Ok(self.data())
    }

    /// The file's size, for estimating what it holds.
    pub fn size_hint(&self) -> usize {
        usize::try_from(self.size).unwrap_or(usize::MAX)
    }

    /// The unconsumed bytes, as they are.
    pub fn data(&self) -> &[u8] {
        &self.view()[self.pos..self.len]
    }

    pub fn consume(&mut self, n: usize) {
        self.pos = (self.pos + n).min(self.len);
    }

    /// Whether the whole file has been read into the buffer (the unconsumed bytes are all that
    /// is left).
    pub fn at_end(&self) -> bool {
        self.eof
    }

    /// Room for more than a block: for a line or record longer than the buffer.
    fn grow(&mut self) {
        let n = self.buf.len() * 2;
        self.buf.resize(n, 0);
    }

    /// At least `n` unconsumed bytes, or fewer at the end of the file.
    pub fn need(&mut self, n: usize) -> io::Result<&[u8]> {
        if self.len - self.pos < n && !self.eof {
            while self.buf.len() < n {
                self.grow();
            }
            self.fill()?;
        }
        Ok(self.data())
    }

    /// The next stretch of text, cut where `cut` says (the length of a prefix that ends on a
    /// line or token boundary), and consumed. The rest of the file once it has all been read;
    /// `None` after that.
    pub fn text(&mut self, cut: impl Fn(&[u8]) -> Option<usize>) -> io::Result<Option<&[u8]>> {
        loop {
            self.fill()?;
            let (start, len) = (self.pos, self.len);
            if len == start {
                return Ok(None);
            }
            let n = if self.eof {
                len - start
            } else if let Some(n) = cut(&self.view()[start..len]).filter(|&n| n > 0) {
                n
            } else {
                // One line fills the buffer: make room for more of it.
                self.grow();
                continue;
            };
            self.pos = start + n;
            return Ok(Some(&self.view()[start..start + n]));
        }
    }
}

/// Text up to and including the last line break.
#[cfg(any(feature = "bvh", feature = "xyz", all(test, feature = "fs")))]
pub(crate) fn lines(data: &[u8]) -> Option<usize> {
    data.iter().rposition(|&b| b == b'\n').map(|i| i + 1)
}

/// Text up to and including the last byte that separates tokens.
pub(crate) fn words(data: &[u8]) -> Option<usize> {
    data.iter().rposition(|&b| space(b)).map(|i| i + 1)
}

/// Whether `b` separates tokens: ASCII whitespace, or any other control character.
#[inline]
pub(crate) fn space(b: u8) -> bool {
    b <= b' '
}

/// A plain decimal number, `[+-]digits[.digits][(e|E)[+-]digits]`, as its sign, its digits as
/// an integer and the power of ten that scales them. `None` for anything else, or more digits
/// than a `u64` holds.
#[inline]
fn decimal(s: &[u8]) -> Option<(bool, u64, i32)> {
    let (neg, m, e, len) = decimal_lead(s)?;
    (len == s.len()).then_some((neg, m, e))
}

/// The run of decimal digits `s` starts with: its value (meaningless past 19 digits) and its
/// length. Eight bytes are read at once where there are eight.
#[inline]
fn leading_digits(s: &[u8]) -> (u64, usize) {
    let (mut v, mut n) = s.first_chunk::<8>().map_or((0, 0), |w| eight_digits(*w));
    if n < 8 && s.len() >= 8 {
        return (v, n);
    }
    while let Some(&c) = s.get(n) {
        let d = c.wrapping_sub(b'0');
        if d > 9 {
            break;
        }
        v = v.wrapping_mul(10).wrapping_add(u64::from(d));
        n += 1;
    }
    (v, n)
}

/// The run of decimal digits `s` starts with, a digit at a time: quicker for runs of a few, like
/// a number's whole part or a face's index.
#[inline]
pub(crate) fn few_digits(s: &[u8]) -> (u64, usize) {
    let mut v = 0u64;
    let mut n = 0;
    while let Some(&c) = s.get(n) {
        let d = c.wrapping_sub(b'0');
        if d > 9 {
            break;
        }
        v = v.wrapping_mul(10).wrapping_add(u64::from(d));
        n += 1;
    }
    (v, n)
}

/// The value of the digits that start `w` and how many there are, from all eight bytes at once:
/// each byte's distance from `'0'` marks the first that isn't a digit, and three multiplies sum
/// the digits before it.
#[inline]
fn eight_digits(w: [u8; 8]) -> (u64, usize) {
    const LOW: u64 = 0x7F7F_7F7F_7F7F_7F7F;
    const HIGH: u64 = 0x8080_8080_8080_8080;
    let a = u64::from_le_bytes(w) ^ 0x3030_3030_3030_3030;
    // A byte's top bit is set unless it was a digit: 10 or more (or top bit already set).
    let over = (((a & LOW) + 0x7676_7676_7676_7676) | a) & HIGH;
    let n = (over.trailing_zeros() / 8) as usize;
    if n == 0 {
        return (0, 0);
    }
    // The digits to the top, after zeros as leading digits; then pairs, fours and all eight.
    let v = a << (8 * (8 - n));
    let v = v.wrapping_mul(10).wrapping_add(v >> 8);
    let pairs = 0x0000_00FF_0000_00FF;
    let v = (v & pairs)
        .wrapping_mul(100 + (1_000_000 << 32))
        .wrapping_add(((v >> 16) & pairs).wrapping_mul(1 + (10_000 << 32)))
        >> 32;
    (v, n)
}

const POW10_U64: [u64; 20] = [
    1,
    10,
    100,
    1_000,
    10_000,
    100_000,
    1_000_000,
    10_000_000,
    100_000_000,
    1_000_000_000,
    10_000_000_000,
    100_000_000_000,
    1_000_000_000_000,
    10_000_000_000_000,
    100_000_000_000_000,
    1_000_000_000_000_000,
    10_000_000_000_000_000,
    100_000_000_000_000_000,
    1_000_000_000_000_000_000,
    10_000_000_000_000_000_000,
];

/// The plain decimal number `s` starts with, like [`decimal`], and how many bytes it takes.
#[inline]
fn decimal_lead(s: &[u8]) -> Option<(bool, u64, i32, usize)> {
    let mut i = 0;
    let neg = match s.first() {
        Some(b'-') => {
            i = 1;
            true
        }
        Some(b'+') => {
            i = 1;
            false
        }
        _ => false,
    };
    // Nineteen digits always fit in a u64; more are left to the standard parser. The whole part
    // is usually short and the fraction long.
    let (mut m, mut digits) = few_digits(&s[i..]);
    i += digits;
    let mut exp: i32 = 0;
    if s.get(i) == Some(&b'.') {
        i += 1;
        let (f, n) = leading_digits(&s[i..]);
        if n > 0 {
            if digits + n > 19 {
                return None;
            }
            m = m * POW10_U64[n] + f;
            digits += n;
            i += n;
            exp = -i32::try_from(n).ok()?;
        }
    }
    if digits == 0 || digits > 19 {
        return None;
    }
    if let Some(b'e' | b'E') = s.get(i) {
        i += 1;
        let eneg = match s.get(i) {
            Some(b'-') => {
                i += 1;
                true
            }
            Some(b'+') => {
                i += 1;
                false
            }
            _ => false,
        };
        let start = i;
        let mut e: i32 = 0;
        while let Some(&c) = s.get(i) {
            let d = c.wrapping_sub(b'0');
            if d > 9 || i - start >= 6 {
                break;
            }
            e = e * 10 + i32::from(d);
            i += 1;
        }
        if i == start {
            return None;
        }
        exp += if eneg { -e } else { e };
    }
    Some((neg, m, exp, i))
}

const POW10_F32: [f32; 11] = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];
const POW10_F64: [f64; 23] = [
    1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, 1e20,
    1e21, 1e22,
];

/// A decimal's value as an `f32`, when it can be had exactly rounded without the standard
/// parser.
#[inline]
fn f32_quick(neg: bool, m: u64, e: i32) -> Option<f32> {
    // Both the digits and the power of ten are exact in an f32, so one multiply or divide
    // rounds correctly (Clinger's fast path).
    if m <= 1 << 24 && (-10..=10).contains(&e) {
        #[allow(clippy::cast_precision_loss, reason = "checked to be at most 2^24, exact in an f32")]
        let v = m as f32;
        let p = POW10_F32[e.unsigned_abs() as usize];
        let v = if e < 0 { v / p } else { v * p };
        return Some(if neg { -v } else { v });
    }
    // Longer digits (nine, as `%.9g` writes): the same in an f64, then rounded to an f32. That
    // second rounding goes the same way as rounding the exact value, since every point halfway
    // between two f32s is an f64 too, unless the f64 landed on one; those go to the standard
    // parser. The values here (1e-22 to 1e38) are all normal f32s.
    if m <= 1 << 53 && (-22..=22).contains(&e) {
        #[allow(clippy::cast_precision_loss, reason = "checked to be at most 2^53, exact in an f64")]
        let v = m as f64;
        let p = POW10_F64[e.unsigned_abs() as usize];
        let v = if e < 0 { v / p } else { v * p };
        if v.to_bits() & 0x1FFF_FFFF != 0x1000_0000 {
            #[allow(clippy::cast_possible_truncation, reason = "rounded to the nearest f32 on purpose")]
            let v = v as f32;
            return Some(if neg { -v } else { v });
        }
    }
    None
}

/// `s` as an `f32`, rounded exactly as `str::parse` rounds it. Decimals of up to 15 digits or so
/// with small exponents (what exporters write) take a fast path; everything else goes to the
/// standard parser.
#[inline]
pub(crate) fn f32_from(s: &[u8]) -> Option<f32> {
    if let Some((neg, m, e)) = decimal(s)
        && let Some(v) = f32_quick(neg, m, e)
    {
        return Some(v);
    }
    std::str::from_utf8(s).ok()?.parse().ok()
}

/// The number `s` starts with, as an `f32` like [`f32_from`], and how many bytes it takes; `None`
/// unless it ends at a space, a control character or the end of `s`.
#[inline]
pub(crate) fn f32_lead(s: &[u8]) -> Option<(f32, usize)> {
    let (neg, m, e, len) = decimal_lead(s)?;
    if s.get(len).is_some_and(|&b| !space(b)) {
        return None;
    }
    if let Some(v) = f32_quick(neg, m, e) {
        return Some((v, len));
    }
    Some((std::str::from_utf8(&s[..len]).ok()?.parse().ok()?, len))
}

/// `s` as an `f64`, like [`f32_from`].
#[inline]
pub(crate) fn f64_from(s: &[u8]) -> Option<f64> {
    if let Some((neg, m, e)) = decimal(s)
        && m <= 1 << 53
        && (-22..=22).contains(&e)
    {
        #[allow(clippy::cast_precision_loss, reason = "checked to be at most 2^53, exact in an f64")]
        let v = m as f64;
        let p = POW10_F64[e.unsigned_abs() as usize];
        let v = if e < 0 { v / p } else { v * p };
        return Some(if neg { -v } else { v });
    }
    std::str::from_utf8(s).ok()?.parse().ok()
}

/// `s` as an `f64` like [`f64_from`], or failing that, in the spellings some writers use: `1.#INF` and
/// `-1.#INF` (infinite) or `1.#QNAN`, `1.#SNAN` and `-1.#IND` (not a number), as old Windows runtimes print
/// them, and `1,5` with a decimal comma.
#[inline]
pub(crate) fn f64_lenient(s: &[u8]) -> Option<f64> {
    f64_from(s).or_else(|| lenient(s))
}

/// `s` as an `f32`, like [`f64_lenient`].
#[inline]
pub(crate) fn f32_lenient(s: &[u8]) -> Option<f32> {
    f32_from(s).or_else(|| lenient(s))
}

/// The spellings [`f64_lenient`] takes past the standard parser's: off the fast path, as they are rare.
#[cold]
#[inline(never)]
fn lenient<T: std::str::FromStr + From<f32>>(s: &[u8]) -> Option<T> {
    let t = std::str::from_utf8(s).ok()?;
    if t.contains("INF") {
        let inf = if t.starts_with('-') {
            f32::NEG_INFINITY
        } else {
            f32::INFINITY
        };
        return Some(T::from(inf));
    }
    if let Some((_, tag)) = t.split_once('#')
        && ["IND", "QNAN", "SNAN", "NAN"].iter().any(|k| tag.starts_with(k))
    {
        return Some(T::from(f32::NAN));
    }
    // `1,5`: one comma and no point, as writers set to such a locale put it.
    let mut commas = t.match_indices(',');
    if commas.next().is_some() && commas.next().is_none() && !t.contains('.') {
        return t.replace(',', ".").parse().ok();
    }
    None
}

/// A whole number as written, an optional sign and digits, as a `T` if it fits; `None` for anything else,
/// spaces and points included. It reads what `str::parse::<i64>` does, and `-0` as 0 for unsigned types.
#[inline]
pub(crate) fn int<T: TryFrom<i64>>(s: &[u8]) -> Option<T> {
    let (neg, mut d) = match s.first()? {
        b'-' => (true, &s[1..]),
        b'+' => (false, &s[1..]),
        _ => (false, s),
    };
    if d.len() > 18 {
        let zeros = d.iter().take_while(|&&c| c == b'0').count();
        d = &d[zeros.min(d.len() - 1)..];
        if d.len() > 18 {
            // Too many digits to add up without overflow checks.
            return long(s);
        }
    }
    if d.is_empty() {
        return None;
    }
    let mut n: i64 = 0;
    for &c in d {
        let k = c.wrapping_sub(b'0');
        if k > 9 {
            return None;
        }
        n = n * 10 + i64::from(k);
    }
    T::try_from(if neg { -n } else { n }).ok()
}

/// [`int`] past 18 digits, read by the standard parser, which checks for overflow.
#[cold]
#[inline(never)]
fn long<T: TryFrom<i64>>(s: &[u8]) -> Option<T> {
    T::try_from(std::str::from_utf8(s).ok()?.parse::<i64>().ok()?).ok()
}

/// `s` as an `f32` with spaces around it ignored, as `str::trim` and `str::parse` read it.
pub(crate) fn num(s: &[u8]) -> Option<f32> {
    // Failing that, with other Unicode spaces trimmed too, as `str::trim` takes them.
    f32_from(s.trim_ascii()).or_else(|| std::str::from_utf8(s).ok()?.trim().parse().ok())
}

/// `s` as a whole number with spaces around it ignored, like [`num`]: what [`int`] takes, or else what
/// `str::trim` and `str::parse` do.
pub(crate) fn whole<T: TryFrom<i64> + std::str::FromStr>(s: &[u8]) -> Option<T> {
    int(s.trim_ascii()).or_else(|| std::str::from_utf8(s).ok()?.trim().parse().ok())
}

/// `s` without the bytes [`space`] takes at its ends: spaces and control characters, so a line that
/// [`tokens`] finds nothing in trims to nothing.
#[inline]
pub(crate) fn trim(s: &[u8]) -> &[u8] {
    let start = s.iter().position(|&b| !space(b)).unwrap_or(s.len());
    let end = s.iter().rposition(|&b| !space(b)).map_or(start, |e| e + 1);
    &s[start..end]
}

/// The whitespace-separated tokens of `text`: split at ASCII spaces and control characters.
pub(crate) fn tokens(text: &[u8]) -> Tokens<'_> {
    Tokens { text, at: 0 }
}

/// The iterator [`tokens`] returns. A scan a byte at a time, which beats `split` and a filter for
/// the short tokens number lists hold.
pub(crate) struct Tokens<'a> {
    text: &'a [u8],
    at: usize,
}

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

    #[inline]
    fn next(&mut self) -> Option<&'a [u8]> {
        let t = self.text;
        let mut i = self.at;
        while i < t.len() && space(t[i]) {
            i += 1;
        }
        let start = i;
        while i < t.len() && !space(t[i]) {
            i += 1;
        }
        self.at = i;
        (i > start).then(|| &t[start..i])
    }
}

/// The line at `*at` in `d`, without its end (`\n`, `\r\n` or a lone `\r`), moving `at` past it; `None` at
/// the end of `d`.
#[inline]
pub(crate) fn next_line<'d>(d: &'d [u8], at: &mut usize) -> Option<&'d [u8]> {
    let rest = d.get(*at..).filter(|r| !r.is_empty())?;
    let n = rest
        .iter()
        .position(|&b| b == b'\n' || b == b'\r')
        .unwrap_or(rest.len());
    let mut end = *at + n;
    if end < d.len() {
        end += if d[end] == b'\r' && d.get(end + 1) == Some(&b'\n') {
            2
        } else {
            1
        };
    }
    *at = end;
    Some(&rest[..n])
}

#[cfg(all(test, feature = "fs"))]
mod tests {
    use super::*;

    #[test]
    fn numbers_round_like_the_standard_parser() {
        let cases = [
            "0",
            "-0",
            "+1",
            "1.",
            ".5",
            "-.5",
            "1e5",
            "1E-5",
            "1.5e+3",
            "-1.234567e-01",
            "0.1",
            "0.2",
            "0.3",
            "3.4028235e38",
            "1e-45",
            "1e39",
            "16777217",
            "123.456789",
            "0.000001",
            "9.999999",
            "1.17549435e-38",
            "inf",
            "-infinity",
            "NaN",
            "1e",
            "e5",
            "--1",
            "1.2.3",
            "",
            ".",
            "+",
            "0x10",
            "1_0",
            "99999999999999999999999",
            "7e-11",
            "1234567.0",
            "0.12345678",
            "-12.345678",
        ];
        for s in cases {
            let want32 = s.parse::<f32>().ok();
            let got32 = f32_from(s.as_bytes());
            assert_eq!(
                got32.map(f32::to_bits),
                want32.map(f32::to_bits),
                "f32 {s:?}: {got32:?} vs {want32:?}"
            );
            let want64 = s.parse::<f64>().ok();
            let got64 = f64_from(s.as_bytes());
            assert_eq!(got64.map(f64::to_bits), want64.map(f64::to_bits), "f64 {s:?}");
        }
        // Every short decimal the fast path takes, against the standard parser.
        let mut x: u32 = 1;
        for _ in 0..200_000 {
            x = x.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            let m = x % 16_777_216;
            let e = (x >> 24) % 21;
            let s = format!("{m}e-{e}");
            assert_eq!(
                f32_from(s.as_bytes()).map(f32::to_bits),
                s.parse::<f32>().ok().map(f32::to_bits),
                "{s}"
            );
            let s = format!("-{m}.{e}e{e}");
            assert_eq!(
                f32_from(s.as_bytes()).map(f32::to_bits),
                s.parse::<f32>().ok().map(f32::to_bits),
                "{s}"
            );
        }
    }

    #[test]
    fn digit_runs_read_eight_at_a_time_like_one_at_a_time() {
        let slow = |s: &[u8]| {
            let n = s.iter().take_while(|c| c.is_ascii_digit()).count();
            let v = s[..n]
                .iter()
                .fold(0u64, |v, &c| v.wrapping_mul(10).wrapping_add(u64::from(c - b'0')));
            (v, n)
        };
        let mut rng = crate::test_rng::Pcg32::new(11);
        let stops = b" /\t\n\r.e-+:\x00\xff\x2f\x3a";
        for _ in 0..200_000 {
            let len = rng.below(26) as usize;
            let mut s: Vec<u8> = (0..len).map(|_| b"0123456789"[rng.below(10) as usize]).collect();
            if rng.below(4) > 0 {
                s.push(stops[rng.below(u32::try_from(stops.len()).unwrap()) as usize]);
            }
            s.extend(b"123456789");
            let cut = rng.below(u32::try_from(s.len()).unwrap() + 1) as usize;
            for t in [&s[..], &s[..cut]] {
                let (v, n) = leading_digits(t);
                let (w, m) = slow(t);
                assert_eq!(n, m, "{:?}", crate::bytes::text(t));
                if n <= 19 {
                    assert_eq!(v, w, "{:?}", crate::bytes::text(t));
                }
            }
        }
    }

    #[test]
    fn long_decimals_round_like_the_standard_parser() {
        let check = |s: &str| {
            let want = s.parse::<f32>().ok().map(f32::to_bits);
            assert_eq!(f32_from(s.as_bytes()).map(f32::to_bits), want, "{s}");
            // Read from the front of a line, ended by a space, a line break or nothing; anything
            // but a plain decimal (`inf`, more digits than a u64 holds) is left to the line's own
            // reader.
            let plain = decimal(s.as_bytes()).is_some();
            for end in ["", " ", "\t", "\r\n", "\n"] {
                let t = format!("{s}{end}");
                let got = f32_lead(t.as_bytes());
                if !plain && got.is_none() {
                    continue;
                }
                assert_eq!(got.map(|g| g.0.to_bits()), want, "{t:?}");
                if let Some((_, len)) = got {
                    assert_eq!(len, s.len(), "{t:?}");
                }
            }
        };
        for s in [
            "-2.19910035e-10",
            "1.23456789",
            "-0",
            "-0.0e5",
            "0e-30",
            // Exactly halfway between two f32s: ties go to even.
            "16777217",
            "16777219",
            "33554434",
            "0.5000000298023223876953125",
            "1.00000005960464477539062500",
            "3.40282356779733661637539395458142568448e38",
            "3.4028236e38",
            "1e22",
            "1e-22",
            "123456789012345e-22",
            "9007199254740993",
            "9007199254740992e22",
            "1e38",
            "1e39",
            "1e-38",
            "1e-46",
            "inf",
            "-nan",
            "1.5x",
        ] {
            check(s);
        }
        // Nine and more significant digits over the exponents the fast path takes, and past it.
        let mut x: u64 = 7;
        for _ in 0..300_000 {
            x = x
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            let digits = 1 + (x >> 60) as u32;
            let m = (x >> 8) % 10u64.pow(digits.min(16));
            let e = i64::from(((x >> 3) % 60) as u32) - 34;
            check(&format!("{m}e{e}"));
            let m = (x >> 20) % 1_000_000_000;
            check(&format!("-{}.{:08}e{}", m / 100_000_000, m % 100_000_000, e / 3));
        }
        // Lines the line reader shouldn't take a number from.
        for s in ["1.5\\", "2#", "nan", "", "-", "1e", "1.5/2"] {
            assert!(f32_lead(s.as_bytes()).is_none(), "{s:?}");
        }
    }

    #[test]
    fn lenient_numbers_take_old_windows_spellings_and_decimal_commas() {
        let bits = |v: Option<f64>| v.map(f64::to_bits);
        // Whatever the standard parser takes reads as it does.
        for s in [
            "0.1",
            "-2.5e-3",
            "+1",
            ".5",
            "5.",
            "inf",
            "-Infinity",
            "NaN",
            "123456789012345678901234",
        ] {
            assert_eq!(bits(f64_lenient(s.as_bytes())), bits(s.parse().ok()), "{s}");
            assert_eq!(
                f32_lenient(s.as_bytes()).map(f32::to_bits),
                s.parse::<f32>().ok().map(f32::to_bits),
                "{s}"
            );
        }
        for (s, want) in [
            ("1.#INF", f32::INFINITY),
            ("1.#INF00", f32::INFINITY),
            ("-1.#INF", f32::NEG_INFINITY),
            ("1,5", 1.5),
            ("-0,25", -0.25),
            ("1,5e3", 1500.0),
        ] {
            assert_eq!(f64_lenient(s.as_bytes()), Some(f64::from(want)), "{s}");
            assert_eq!(f32_lenient(s.as_bytes()), Some(want), "{s}");
        }
        // A decimal comma rounds once, to the type asked for.
        assert_eq!(f32_lenient(b"0,1"), Some(0.1));
        assert_eq!(f64_lenient(b"0,1"), Some(0.1));
        for s in ["1.#QNAN", "1.#QNAN0", "-1.#IND", "-1.#IND00", "1.#SNAN"] {
            assert!(f64_lenient(s.as_bytes()).is_some_and(f64::is_nan), "{s}");
            assert!(f32_lenient(s.as_bytes()).is_some_and(f32::is_nan), "{s}");
        }
        for s in ["", "-", "x", "1,5,6", "1.5,2", ",", "1.#", "1.#FOO", "1e", "1 2"] {
            assert_eq!(f64_lenient(s.as_bytes()), None, "{s}");
            assert_eq!(f32_lenient(s.as_bytes()), None, "{s}");
        }
    }

    #[test]
    fn whole_numbers_read_like_the_standard_parser() {
        // Every token as the standard parser reads it for each type.
        for s in [
            "0",
            "-0",
            "+0",
            "7",
            "-12",
            "+34",
            "007",
            "999999999999999999",
            "-999999999999999999",
            "0000000000000000000000000042",
            "-000000000000000000000000042",
            "4294967295",
            "4294967296",
            "-1",
            "2147483648",
            "-2147483649",
            "",
            "-",
            "+",
            "--1",
            "+-1",
            "1.0",
            "1e3",
            " 1",
            "1 ",
            "0x10",
            "1_000",
            "12a",
        ] {
            let b = s.as_bytes();
            assert_eq!(int::<i64>(b), s.parse().ok(), "i64 {s:?}");
            assert_eq!(int::<i32>(b), s.parse().ok(), "i32 {s:?}");
            // Unsigned types take `-0` too, where the standard parser doesn't.
            let zero = s.len() > 1 && s.starts_with('-') && s[1..].bytes().all(|c| c == b'0');
            let want = if zero { Some(0) } else { s.parse().ok() };
            assert_eq!(int::<u32>(b), want, "u32 {s:?}");
            let want = if zero { Some(0) } else { s.parse().ok() };
            assert_eq!(int::<usize>(b), want, "usize {s:?}");
        }
        // Past 18 digits, up to the ends of `i64`.
        assert_eq!(int::<i64>(b"1234567890123456789"), Some(1_234_567_890_123_456_789));
        assert_eq!(int::<i64>(b"-9223372036854775808"), Some(i64::MIN));
        assert_eq!(int::<i64>(b"+9223372036854775807"), Some(i64::MAX));
        assert_eq!(int::<i64>(b"9223372036854775808"), None);
        assert_eq!(int::<i64>(b"1234567890123456789x"), None);
        assert_eq!(int::<u32>(b"1234567890123456789"), None);
    }

    #[test]
    fn trimmed_numbers_read_like_str_trim_and_parse() {
        for s in [
            "1.5",
            " 1.5 ",
            "\t-2\r\n",
            "+.5",
            "5.",
            "1E+05",
            " inf ",
            "-infinity",
            "nan",
            "\u{a0}2.5",
            "3\u{3000}",
            "",
            "  ",
            "1 2",
            "1,5",
            "x",
        ] {
            assert_eq!(
                num(s.as_bytes()).map(f32::to_bits),
                s.trim().parse::<f32>().ok().map(f32::to_bits),
                "{s:?}"
            );
        }
        for s in [
            "42",
            " 42\t",
            "+7",
            "\u{a0}7",
            "0000000000000000000000009 ",
            "-1",
            "1.0",
            "",
            " ",
        ] {
            assert_eq!(whole::<u32>(s.as_bytes()), s.trim().parse().ok(), "{s:?}");
            assert_eq!(whole::<i64>(s.as_bytes()), s.trim().parse().ok(), "{s:?}");
        }
    }

    #[test]
    fn tokens_trims_and_lines() {
        let t: Vec<&[u8]> = tokens(b"  1 2\t\t3\r\n4\x005  ").collect();
        assert_eq!(t, [&b"1"[..], b"2", b"3", b"4", b"5"]);
        assert_eq!(tokens(b" \n ").count(), 0);
        assert_eq!(trim(b"\x00 a b\x1a\r\n"), b"a b");
        assert_eq!(trim(b" \t "), b"");
        let d = b"a\r\nb\rc\n\nd";
        let mut at = 0;
        let mut lines = Vec::new();
        while let Some(l) = next_line(d, &mut at) {
            lines.push(l);
        }
        assert_eq!(lines, [&b"a"[..], b"b", b"c", b"", b"d"]);
        assert_eq!(at, d.len());
        let mut at = 0;
        assert_eq!(next_line(b"", &mut at), None);
        assert_eq!(next_line(b"x\r", &mut at), Some(&b"x"[..]));
        assert_eq!(next_line(b"x\r", &mut at), None);
    }

    #[test]
    fn blocks_cut_on_boundaries() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("t.txt");
        let line = "abc def\n".repeat(100_000);
        std::fs::write(&p, &line).unwrap();
        let open = |p: &std::path::Path| {
            let f = std::fs::File::open(p).unwrap();
            let n = f.metadata().unwrap().len();
            Blocks::reader(f, n)
        };
        let mut b = open(&p);
        let mut all = Vec::new();
        while let Some(t) = b.text(lines).unwrap() {
            assert!(t.ends_with(b"\n"));
            all.extend_from_slice(t);
        }
        assert_eq!(all, line.as_bytes());
        // In memory: the same text, read in place.
        let mut b = Blocks::slice(line.as_bytes());
        assert_eq!(b.text(lines).unwrap(), Some(line.as_bytes()));
        assert_eq!(b.text(lines).unwrap(), None);
        // One line longer than a block.
        let long = format!("{}\nx", "y".repeat(BLOCK * 3));
        std::fs::write(&p, &long).unwrap();
        let mut b = open(&p);
        let mut n = 0;
        while let Some(t) = b.text(lines).unwrap() {
            assert!(t.ends_with(b"\n") || t.ends_with(b"x"));
            n += t.len();
        }
        assert_eq!(n, long.len());
    }
}