meshoptimizer-rs 0.2.5

Rust port of meshoptimizer 1.3 with byte-identical output. Covers mesh simplification, meshlets, cluster LOD, vertex/index compression analysis, remeshing and optional parallel batch APIs and audited SIMD codecs.
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
926
927
928
929
930
931
932
933
934
935
936
937
use crate::Error;
use alloc::vec::Vec;
use core::mem::size_of;

/// Per-call limits for crate-owned heap storage and counted work.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Limits {
    /// Maximum output plus retained scratch capacity, excluding caller buffers
    /// and allocator overhead. Defaults to 1 GiB. Scratch is reused when it fits;
    /// unused retained storage and excess active capacity are reclaimed under
    /// limit pressure.
    pub max_bytes: usize,
    /// Maximum counted record visits. Defaults to 2^34.
    pub max_work: u64,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            max_bytes: 1 << 30,
            max_work: 1 << 34,
        }
    }
}

/// Resource measurements for the most recent algorithm call.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Usage {
    /// Crate-owned output bytes plus retained heap scratch capacity.
    pub bytes: usize,
    /// Counted record visits actually performed, including validation.
    pub work: u64,
}

#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct CacheVertex {
    pub(crate) live: u32,
    pub(crate) offset: u32,
    pub(crate) score: f32,
}

/// Reusable fallibly allocated scratch storage and per-call resource limits.
///
/// Cache work counts topology/index validation, each adjacency initialization,
/// insertion, search and score update, and each cache/emission visit. Overdraw
/// work counts validation, cache simulation, geometry and counting-sort record
/// visits, and copied indices. Fixed scalar arithmetic inside a visit is not
/// counted separately. Simplification counts validation, position/hash and
/// adjacency visits, edge searches, classification, quadric and attribute
/// accumulation, collapse ranking/sorting/flip checks, and remapping visits.
/// Its typed scratch is allocated fallibly and retained after successful calls;
/// retained scratch is reused when it fits and released under limit pressure
/// including excess capacity in buffers the current call uses.
/// Usage reports peak storage including all retained workspace buffers. Scale
/// computation is allocation-free and has no workspace argument.
/// Limits never disable checked size arithmetic.
#[derive(Debug, Default)]
pub struct Workspace {
    limits: Limits,
    active: [bool; 5],
    usage: Usage,
    pub(crate) has_retained: bool,
    pub(crate) simplify: Option<crate::simplify::State>,
    pub(crate) sloppy: Option<crate::simplify::SloppyScratch>,
    pub(crate) vertices: Vec<CacheVertex>,
    pub(crate) integers: Vec<u32>,
    pub(crate) floats: Vec<f32>,
    pub(crate) flags: Vec<u8>,
    pub(crate) keys: Vec<u16>,
}

impl Workspace {
    /// Create an empty workspace with explicit limits.
    pub fn new(limits: Limits) -> Self {
        Self {
            limits,
            ..Self::default()
        }
    }
    /// Current per-call limits.
    pub const fn limits(&self) -> Limits {
        self.limits
    }
    /// Set limits and release scratch so a lower budget is effective immediately.
    pub fn set_limits(&mut self, limits: Limits) {
        self.clear();
        self.limits = limits;
    }
    /// Release all retained scratch allocations and reset measurements.
    pub fn clear(&mut self) {
        self.simplify = None;
        self.sloppy = None;
        self.vertices = Vec::new();
        self.integers = Vec::new();
        self.floats = Vec::new();
        self.flags = Vec::new();
        self.keys = Vec::new();
        self.usage = Usage::default();
        self.has_retained = false;
    }
    /// Measurements for the most recent call, including a failed call's work.
    pub const fn usage(&self) -> Usage {
        self.usage
    }
    #[inline]
    pub(crate) fn begin(&mut self) -> Work {
        self.usage = Usage::default();
        self.active = [false; 5];
        Work {
            remaining: self.limits.max_work,
            limit: self.limits.max_work,
        }
    }
    #[inline]
    pub(crate) fn finish(&mut self, work: &Work) {
        self.usage.work = work.limit - work.remaining;
    }
    // Local budgets re-read capacities after pressure can evict unused buffers.
    #[inline]
    pub(crate) fn retained_bytes(&self) -> Result<usize, Error> {
        if !self.has_retained {
            debug_assert!(self.simplify.is_none() && self.sloppy.is_none());
            debug_assert_eq!(
                self.integers.capacity()
                    | self.floats.capacity()
                    | self.flags.capacity()
                    | self.keys.capacity()
                    | self.vertices.capacity(),
                0
            );
            return Ok(0);
        }
        total(
            [
                self.integers.capacity(),
                self.floats.capacity(),
                self.flags.capacity(),
                self.keys.capacity(),
            ],
            checked_bytes(self.vertices.capacity(), size_of::<CacheVertex>())?
                .checked_add(
                    self.simplify
                        .as_ref()
                        .map_or(Ok(0), |s| s.capacity_bytes())?,
                )
                .ok_or(Error::SizeOverflow)?
                .checked_add(self.sloppy.as_ref().map_or(Ok(0), |s| s.capacity_bytes())?)
                .ok_or(Error::SizeOverflow)?,
        )
    }
    #[inline]
    pub(crate) fn charge_owned(&mut self, owned: usize) -> Result<(), Error> {
        let mut bytes = self
            .retained_bytes()?
            .checked_add(owned)
            .ok_or(Error::SizeOverflow)?;
        if bytes > self.limits.max_bytes {
            // Local typed scratch has already been taken out of the workspace.
            // Buffers prepared by this call remain live and must stay charged.
            self.simplify = None;
            self.sloppy = None;
            if !self.active[0] {
                self.integers = Vec::new();
            }
            if !self.active[1] {
                self.floats = Vec::new();
            }
            if !self.active[2] {
                self.flags = Vec::new();
            }
            if !self.active[3] {
                self.keys = Vec::new();
            }
            if !self.active[4] {
                self.vertices = Vec::new();
            }
            bytes = self
                .retained_bytes()?
                .checked_add(owned)
                .ok_or(Error::SizeOverflow)?;
            if bytes > self.limits.max_bytes {
                self.shrink_active()?;
                bytes = self
                    .retained_bytes()?
                    .checked_add(owned)
                    .ok_or(Error::SizeOverflow)?;
            }
        }
        if bytes > self.limits.max_bytes {
            return Err(Error::LimitExceeded);
        }
        self.usage.bytes = self.usage.bytes.max(bytes);
        Ok(())
    }
    fn shrink_active(&mut self) -> Result<(), Error> {
        shrink(&mut self.integers, self.active[0])?;
        shrink(&mut self.floats, self.active[1])?;
        shrink(&mut self.flags, self.active[2])?;
        shrink(&mut self.keys, self.active[3])?;
        shrink(&mut self.vertices, self.active[4])
    }
    #[cfg(any(feature = "clusterlod", feature = "parallel"))]
    pub(crate) fn release_unused(&mut self) {
        self.simplify = None;
        self.sloppy = None;
        self.vertices = Vec::new();
        self.integers = Vec::new();
        self.floats = Vec::new();
        self.flags = Vec::new();
        self.keys = Vec::new();
    }
    #[inline]
    pub(crate) fn charge_retained(&mut self) -> Result<(), Error> {
        self.charge_owned(0)
    }
    pub(crate) fn prepare(&mut self, lengths: [usize; 4], output: usize) -> Result<(), Error> {
        self.prepare_cache(lengths, 0, output)
    }
    pub(crate) fn prepare_remap(&mut self, vertices: usize, output: usize) -> Result<(), Error> {
        let previous = self.integers.len();
        self.prepare_cache_value([vertices, 0, 0, 0], 0, output, u32::MAX)?;
        self.integers[..previous.min(vertices)].fill(u32::MAX);
        Ok(())
    }
    pub(crate) fn prepare_cache(
        &mut self,
        lengths: [usize; 4],
        vertices: usize,
        output: usize,
    ) -> Result<(), Error> {
        self.prepare_cache_value(lengths, vertices, output, 0)
    }
    #[inline(always)]
    pub(crate) fn prepare_timestamps(&mut self, count: usize) -> Result<(), Error> {
        self.prepare_cache_value([count, 0, 0, 0], 0, 0, 0)
    }
    #[inline(always)]
    fn prepare_cache_value(
        &mut self,
        lengths: [usize; 4],
        vertices: usize,
        output: usize,
        integer_value: u32,
    ) -> Result<(), Error> {
        let [i, f, b, k] = lengths;
        let mut simplify_bytes = self
            .simplify
            .as_ref()
            .map_or(Ok(0), |s| s.capacity_bytes())?
            .checked_add(self.sloppy.as_ref().map_or(Ok(0), |s| s.capacity_bytes())?)
            .ok_or(Error::SizeOverflow)?;
        let vertex_bytes = checked_bytes(
            vertices.max(self.vertices.capacity()),
            size_of::<CacheVertex>(),
        )?;
        let owned = output
            .checked_add(vertex_bytes)
            .and_then(|n| n.checked_add(simplify_bytes))
            .ok_or(Error::SizeOverflow)?;
        let bytes = total(
            [
                i.max(self.integers.capacity()),
                f.max(self.floats.capacity()),
                b.max(self.flags.capacity()),
                k.max(self.keys.capacity()),
            ],
            owned,
        )?;
        if bytes > self.limits.max_bytes {
            self.simplify = None;
            self.sloppy = None;
            if (!self.active[0] || i == 0) && self.integers.capacity() > i {
                self.integers = Vec::new();
            }
            if (!self.active[1] || f == 0) && self.floats.capacity() > f {
                self.floats = Vec::new();
            }
            if (!self.active[2] || b == 0) && self.flags.capacity() > b {
                self.flags = Vec::new();
            }
            if (!self.active[3] || k == 0) && self.keys.capacity() > k {
                self.keys = Vec::new();
            }
            if (!self.active[4] || vertices == 0) && self.vertices.capacity() > vertices {
                self.vertices = Vec::new();
            }
            simplify_bytes = 0;
            let minimum = total(
                [
                    i.max(self.integers.capacity()),
                    f.max(self.floats.capacity()),
                    b.max(self.flags.capacity()),
                    k.max(self.keys.capacity()),
                ],
                output
                    .checked_add(checked_bytes(
                        vertices.max(self.vertices.capacity()),
                        size_of::<CacheVertex>(),
                    )?)
                    .ok_or(Error::SizeOverflow)?,
            )?;
            if minimum > self.limits.max_bytes {
                let needed = total(
                    lengths,
                    output
                        .checked_add(checked_bytes(vertices, size_of::<CacheVertex>())?)
                        .ok_or(Error::SizeOverflow)?,
                )?;
                if needed > self.limits.max_bytes {
                    return Err(Error::LimitExceeded);
                }
                // These prefixes already contain this call's data. Shrink their
                // allocations in place instead of discarding still-live values.
                self.integers.truncate(i);
                self.floats.truncate(f);
                self.flags.truncate(b);
                self.keys.truncate(k);
                self.vertices.truncate(vertices);
                self.shrink_active()?;
                let minimum = total(
                    [
                        i.max(self.integers.capacity()),
                        f.max(self.floats.capacity()),
                        b.max(self.flags.capacity()),
                        k.max(self.keys.capacity()),
                    ],
                    output
                        .checked_add(checked_bytes(
                            vertices.max(self.vertices.capacity()),
                            size_of::<CacheVertex>(),
                        )?)
                        .ok_or(Error::SizeOverflow)?,
                )?;
                if minimum > self.limits.max_bytes {
                    return Err(Error::LimitExceeded);
                }
            }
        }
        self.active = [i != 0, f != 0, b != 0, k != 0, vertices != 0];
        self.has_retained |= i != 0 || f != 0 || b != 0 || k != 0 || vertices != 0;
        reserve(&mut self.vertices, vertices)?;
        reserve_value(&mut self.integers, i, integer_value)?;
        reserve(&mut self.floats, f)?;
        reserve(&mut self.flags, b)?;
        reserve(&mut self.keys, k)?;
        let actual = total(
            [
                self.integers.capacity(),
                self.floats.capacity(),
                self.flags.capacity(),
                self.keys.capacity(),
            ],
            output
                .checked_add(checked_bytes(
                    self.vertices.capacity(),
                    size_of::<CacheVertex>(),
                )?)
                .and_then(|n| n.checked_add(simplify_bytes))
                .ok_or(Error::SizeOverflow)?,
        )?;
        if actual > self.limits.max_bytes {
            self.clear();
            return Err(Error::LimitExceeded);
        }
        self.usage.bytes = self.usage.bytes.max(actual);
        Ok(())
    }
}

// Vec shrinking preserves the live prefix and never grows the allocation.
// An allocator may refuse to shrink; do not misreport that as a byte-limit error.
pub(crate) fn shrink<T>(v: &mut Vec<T>, active: bool) -> Result<(), Error> {
    if active && v.capacity() > v.len() {
        v.shrink_to_fit();
        if v.capacity() > v.len() {
            return Err(Error::AllocationFailed);
        }
    }
    Ok(())
}

#[inline(always)]
fn total(lengths: [usize; 4], output: usize) -> Result<usize, Error> {
    let mut sum = output;
    for (len, size) in lengths.into_iter().zip([4, 4, 1, 2]) {
        let bytes = checked_bytes(len, size)?;
        sum = sum.checked_add(bytes).ok_or(Error::SizeOverflow)?;
    }
    Ok(sum)
}

// Codec-only wiring: account retained geometry scratch without resizing any
// vector. Raw decoding requires no heap scratch and preserves the workspace.
impl Workspace {
    #[inline]
    pub(crate) fn account_codec(&mut self, output: usize) -> Result<(), Error> {
        self.charge_owned(output)
    }
}

#[inline]
pub(crate) fn checked_bytes(len: usize, size: usize) -> Result<usize, Error> {
    let bytes = len.checked_mul(size).ok_or(Error::SizeOverflow)?;
    if bytes > isize::MAX as usize {
        return Err(Error::SizeOverflow);
    }
    Ok(bytes)
}

#[inline(always)]
fn reserve<T: Default + Clone>(v: &mut Vec<T>, len: usize) -> Result<(), Error> {
    reserve_value(v, len, T::default())
}
fn reserve_value<T: Clone>(v: &mut Vec<T>, len: usize, value: T) -> Result<(), Error> {
    checked_bytes(len, size_of::<T>())?;
    if len > v.capacity() {
        v.try_reserve_exact(len.saturating_sub(v.len()))
            .map_err(|_| Error::AllocationFailed)?;
    }
    v.resize(len, value);
    Ok(())
}

pub(crate) fn output(len: usize) -> Result<Vec<u32>, Error> {
    checked_bytes(len, 4)?;
    let mut v = Vec::new();
    reserve(&mut v, len)?;
    Ok(v)
}
pub(crate) fn output_sentinel(len: usize) -> Result<Vec<u32>, Error> {
    checked_bytes(len, 4)?;
    let mut v = Vec::new();
    reserve_value(&mut v, len, u32::MAX)?;
    Ok(v)
}

pub(crate) struct Work {
    remaining: u64,
    limit: u64,
}
impl Work {
    /// Upper bound after normal/tangent input validation: all hash probes,
    /// two adjacency visits per corner, all possible corner pairs, one face
    /// visit and one accumulation visit per corner. Overflow selects staging.
    pub(crate) fn covers_corner_generation(
        &self,
        vertices: usize,
        buckets: usize,
        corners: usize,
    ) -> bool {
        let bound = (|| {
            let vertices = u64::try_from(vertices).ok()?;
            let buckets = u64::try_from(buckets).ok()?;
            let corners = u64::try_from(corners).ok()?;
            vertices
                .checked_mul(buckets)?
                .checked_add(corners.checked_mul(corners.saturating_sub(1))? / 2)?
                .checked_add(corners.checked_mul(3)?)?
                .checked_add(corners / 3)
        })();
        bound.is_some_and(|visits| visits <= self.remaining)
    }

    #[inline]
    pub(crate) fn covers(&self, count: usize) -> Result<bool, Error> {
        Ok(u64::try_from(count).map_err(|_| Error::SizeOverflow)? <= self.remaining)
    }

    #[inline(always)]
    pub(crate) fn scan<T>(
        &mut self,
        values: impl ExactSizeIterator<Item = T>,
        visit: impl FnMut(T) -> Result<(), Error>,
    ) -> Result<(), Error> {
        self.scan_units(values, 1, visit)
    }
    /// Each callback has the same pre-visit charge. Keep that granularity on
    /// exhaustion, including callbacks that fail before completing their work.
    #[inline(always)]
    pub(crate) fn scan_units<T>(
        &mut self,
        values: impl ExactSizeIterator<Item = T>,
        units: usize,
        mut visit: impl FnMut(T) -> Result<(), Error>,
    ) -> Result<(), Error> {
        let count = u64::try_from(values.len()).map_err(|_| Error::SizeOverflow)?;
        let unit_count = u64::try_from(units).map_err(|_| Error::SizeOverflow)?;
        if let Some(visits) = count
            .checked_mul(unit_count)
            .filter(|&v| v <= self.remaining)
        {
            for (i, value) in values.enumerate() {
                if let Err(error) = visit(value) {
                    self.remaining -= (i as u64 + 1) * unit_count;
                    return Err(error);
                }
            }
            self.remaining -= visits;
            Ok(())
        } else {
            for value in values {
                self.add(units)?;
                visit(value)?;
            }
            Ok(())
        }
    }
    /// Precharge a fixed scan only when every visit fits. The caller must
    /// execute every visit without a fallible callback on this path.
    #[inline]
    pub(crate) fn precharge(&mut self, count: usize, units: usize) -> Result<bool, Error> {
        let count = u64::try_from(count).map_err(|_| Error::SizeOverflow)?;
        let units = u64::try_from(units).map_err(|_| Error::SizeOverflow)?;
        if let Some(visits) = count.checked_mul(units).filter(|&v| v <= self.remaining) {
            self.remaining -= visits;
            Ok(true)
        } else {
            Ok(false)
        }
    }
    /// Number of records whose full per-record search bound fits.
    #[inline]
    pub(crate) fn batch(&self, count: usize, units: usize) -> Result<usize, Error> {
        let units = u64::try_from(units).map_err(|_| Error::SizeOverflow)?;
        let count = u64::try_from(count).map_err(|_| Error::SizeOverflow)?;
        let allowed = self
            .remaining
            .min(usize::MAX as u64)
            .checked_div(units)
            .map_or(count, |n| count.min(n));
        usize::try_from(allowed).map_err(|_| Error::SizeOverflow)
    }
    /// Count a bounded search once when every possible visit fits. The limited
    /// path checks before each callback, preserving its observable prefix.
    #[inline(always)]
    pub(crate) fn search(
        &mut self,
        count: usize,
        mut found: impl FnMut(usize) -> bool,
    ) -> Result<Option<usize>, Error> {
        if self.covers(count)? {
            for i in 0..count {
                if found(i) {
                    self.add(i + 1)?;
                    return Ok(Some(i));
                }
            }
            self.add(count)?;
        } else {
            for i in 0..count {
                self.add(1)?;
                if found(i) {
                    return Ok(Some(i));
                }
            }
        }
        Ok(None)
    }
    /// Validate an index stream with a vectorizable fast path for valid data.
    /// Replay the scalar scan for the first invalid index or a tight fuel limit
    /// so the error and charged prefix stay unchanged.
    #[inline]
    pub(crate) fn indices(&mut self, indices: &[u32], vertices: usize) -> Result<(), Error> {
        if self.covers(indices.len())?
            && indices
                .iter()
                .copied()
                .max()
                .is_none_or(|index| (index as usize) < vertices)
        {
            self.add(indices.len())
        } else {
            self.scan(indices.iter().copied(), |index| {
                if index as usize >= vertices {
                    Err(Error::IndexOutOfBounds)
                } else {
                    Ok(())
                }
            })
        }
    }
    #[inline]
    pub(crate) fn add(&mut self, count: usize) -> Result<(), Error> {
        let count = u64::try_from(count).map_err(|_| Error::SizeOverflow)?;
        if count > self.remaining {
            return self.exhausted(count);
        }
        self.remaining -= count;
        Ok(())
    }
    #[cold]
    #[inline(never)]
    fn exhausted(&self, count: u64) -> Result<(), Error> {
        // Preserve both the failed visit's count and the overflow error.
        (self.limit - self.remaining)
            .checked_add(count)
            .ok_or(Error::SizeOverflow)?;
        Err(Error::LimitExceeded)
    }
}

pub(crate) fn topology(indices: &[u32], vertices: usize, work: &mut Work) -> Result<(), Error> {
    if !indices.len().is_multiple_of(3) {
        return Err(Error::InvalidTopology);
    }
    // Upstream adjacency offsets and triangle identifiers are u32.
    if vertices > u32::MAX as usize || indices.len() > u32::MAX as usize {
        return Err(Error::SizeOverflow);
    }
    checked_bytes(vertices, 4)?;
    checked_bytes(indices.len(), 4)?;
    work.indices(indices, vertices)
}

// Additive 0.3 accounting: processing modules use local typed scratch and do not
// resize the workspace's cache/overdraw buffers.
impl Workspace {
    #[inline]
    pub(crate) fn processing_storage(&mut self, bytes: usize) -> Result<(), Error> {
        self.charge_owned(bytes)
    }
}

// Child operation totals are u64 even on 32-bit targets.
#[cfg(any(feature = "clusterlod", feature = "parallel"))]
impl Work {
    #[inline]
    pub(crate) fn add_processing(&mut self, count: u64) -> Result<(), Error> {
        if count > self.remaining {
            return self.exhausted(count);
        }
        self.remaining -= count;
        Ok(())
    }
}

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

    #[test]
    fn active_capacity_reclamation_preserves_live_prefixes_and_fitting_reuse() {
        let mut ws = Workspace::new(Limits {
            max_bytes: 128,
            ..Limits::default()
        });
        for (lengths, vertices) in [
            ([16, 0, 0, 0], 0),
            ([0, 16, 0, 0], 0),
            ([0, 0, 64, 0], 0),
            ([0, 0, 0, 32], 0),
            ([0; 4], 5),
        ] {
            ws.clear();
            ws.begin();
            ws.prepare_cache(lengths, vertices, 0).unwrap();
            ws.begin();
            let needed = lengths.map(|n| usize::from(n != 0));
            ws.prepare_cache(needed, usize::from(vertices != 0), 0)
                .unwrap();
            let capacities = (
                ws.integers.capacity(),
                ws.floats.capacity(),
                ws.flags.capacity(),
                ws.keys.capacity(),
                ws.vertices.capacity(),
            );
            ws.integers.fill(17);
            ws.floats.fill(2.5);
            ws.flags.fill(19);
            ws.keys.fill(23);
            ws.vertices.fill(CacheVertex {
                live: 29,
                ..CacheVertex::default()
            });
            ws.prepare_cache(needed, usize::from(vertices != 0), 0)
                .unwrap();
            assert_eq!(
                capacities,
                (
                    ws.integers.capacity(),
                    ws.floats.capacity(),
                    ws.flags.capacity(),
                    ws.keys.capacity(),
                    ws.vertices.capacity()
                )
            );
            ws.charge_owned(116).unwrap();
            assert!(ws.usage().bytes <= 128);
            assert!(ws.integers.iter().all(|&v| v == 17));
            assert!(ws.floats.iter().all(|&v| v.to_bits() == 2.5f32.to_bits()));
            assert!(ws.flags.iter().all(|&v| v == 19));
            assert!(ws.keys.iter().all(|&v| v == 23));
            assert!(ws.vertices.iter().all(|v| v.live == 29));
            assert_eq!(ws.charge_owned(128), Err(Error::LimitExceeded));
        }
    }

    #[test]
    fn simplify_then_cache_releases_retained_scratch_under_pressure() {
        use crate::{
            optimize_vertex_cache_in_place, simplify, Positions, SimplifyOptions, SimplifySettings,
        };
        // Unshared triangles keep the simplified stream large, as in a082.
        let positions: Vec<_> = (0..4096)
            .flat_map(|i| {
                let x = i as f32 * 2.0;
                [[x, 0.0, 0.0], [x + 1.0, 0.0, 0.0], [x, 1.0, 0.0]]
            })
            .collect();
        let indices: Vec<_> = (0..positions.len() as u32).collect();
        let settings = SimplifySettings {
            target_index_count: indices.len() / 2,
            target_error: 0.01,
            options: SimplifyOptions::EMPTY,
        };
        let mut fresh = Workspace::default();
        let expected = simplify(
            &indices,
            Positions::from_packed(&positions),
            settings,
            &mut fresh,
        )
        .unwrap();
        let simplify_peak = fresh.usage().bytes;
        fresh.clear();
        let mut expected_cache = expected.indices.clone();
        optimize_vertex_cache_in_place(&mut expected_cache, positions.len(), &mut fresh).unwrap();
        let limits = Limits {
            max_bytes: simplify_peak.max(fresh.usage().bytes),
            ..Limits::default()
        };
        let mut reused = Workspace::new(limits);
        let actual = simplify(
            &indices,
            Positions::from_packed(&positions),
            settings,
            &mut reused,
        )
        .unwrap();
        assert_eq!(actual.indices, expected.indices);
        assert_eq!(actual.error.to_bits(), expected.error.to_bits());
        let retained = reused.retained_bytes().unwrap();
        // Establish the regression's premise rather than just exercise reuse.
        let cache_demand = fresh.usage().bytes;
        assert!(retained + cache_demand > limits.max_bytes);
        let mut actual_cache = actual.indices;
        optimize_vertex_cache_in_place(&mut actual_cache, positions.len(), &mut reused).unwrap();
        assert_eq!(actual_cache, expected_cache);
    }

    #[test]
    fn precharged_scans_and_batches_fit_their_counter_width() {
        for units in [0, 1, 3, 99] {
            for limit in 0..=units * 5 + 1 {
                let mut scalar = Work {
                    remaining: limit as u64,
                    limit: limit as u64,
                };
                let mut batched = Work {
                    remaining: limit as u64,
                    limit: limit as u64,
                };
                let mut expected_prefix = Vec::new();
                let mut actual_prefix = Vec::new();
                let expected: Result<(), Error> = (|| {
                    for i in 0..5 {
                        scalar.add(units)?;
                        expected_prefix.push(i);
                    }
                    Ok(())
                })();
                let actual: Result<(), Error> = (|| {
                    let charged = batched.precharge(5, units)?;
                    for i in 0..5 {
                        if !charged {
                            batched.add(units)?;
                        }
                        actual_prefix.push(i);
                    }
                    Ok(())
                })();
                assert_eq!(actual, expected);
                assert_eq!(actual_prefix, expected_prefix);
                assert_eq!(batched.remaining, scalar.remaining);
            }
        }
        let huge = Work {
            remaining: u64::MAX,
            limit: u64::MAX,
        };
        for units in [1, 2, 99, usize::MAX] {
            let count = huge.batch(usize::MAX, units).unwrap();
            assert!(count.checked_mul(units).is_some());
            assert!(count as u64 * units as u64 <= huge.remaining);
        }
    }

    #[test]
    fn fixed_charge_scans_preserve_failure_prefixes() {
        for units in [0, 1, 3, 99] {
            for limit in 0..=units * 5 + 1 {
                for failure in 0..=5 {
                    let mut scalar = Work {
                        remaining: limit as u64,
                        limit: limit as u64,
                    };
                    let mut batched = Work {
                        remaining: limit as u64,
                        limit: limit as u64,
                    };
                    let mut expected_prefix = Vec::new();
                    let mut actual_prefix = Vec::new();
                    let expected = (|| {
                        for i in 0..5 {
                            scalar.add(units)?;
                            expected_prefix.push(i);
                            if i == failure {
                                return Err(Error::InvalidParameter);
                            }
                        }
                        Ok(())
                    })();
                    let actual = batched.scan_units(0..5, units, |i| {
                        actual_prefix.push(i);
                        if i == failure {
                            Err(Error::InvalidParameter)
                        } else {
                            Ok(())
                        }
                    });
                    assert_eq!(actual, expected);
                    assert_eq!(batched.remaining, scalar.remaining);
                    assert_eq!(actual_prefix, expected_prefix);
                }
            }
        }
    }

    #[test]
    fn bounded_search_preserves_the_checked_callback_prefix() {
        for limit in 0..8 {
            for match_at in 0..8 {
                let mut scalar = Work {
                    remaining: limit,
                    limit,
                };
                let mut batched = Work {
                    remaining: limit,
                    limit,
                };
                let mut scalar_visits = Vec::new();
                let mut batched_visits = Vec::new();
                let expected = (|| {
                    for i in 0..5 {
                        scalar.add(1)?;
                        scalar_visits.push(i);
                        if i == match_at {
                            return Ok(Some(i));
                        }
                    }
                    Ok(None)
                })();
                let actual = batched.search(5, |i| {
                    batched_visits.push(i);
                    i == match_at
                });
                assert_eq!(actual, expected);
                assert_eq!(batched.remaining, scalar.remaining);
                assert_eq!(batched_visits, scalar_visits);
            }
        }
    }
    #[test]
    fn scan_preserves_failures_work_and_side_effects() {
        for limit in 0..=8 {
            for fail_at in 0usize..=5 {
                let mut scalar = Work {
                    remaining: limit,
                    limit,
                };
                let mut scanned = Work {
                    remaining: limit,
                    limit,
                };
                let mut scalar_sum = 0;
                let mut scanned_sum = 0;
                let visit = |i, sum: &mut usize| {
                    *sum += i + 1;
                    if i == fail_at {
                        Err(Error::NumericalFailure)
                    } else {
                        Ok(())
                    }
                };
                let expected = (|| {
                    for i in 0..5 {
                        scalar.add(1)?;
                        visit(i, &mut scalar_sum)?;
                    }
                    Ok(())
                })();
                let actual = scanned.scan(0..5, |i| visit(i, &mut scanned_sum));
                assert_eq!(actual, expected);
                assert_eq!(scanned.remaining, scalar.remaining);
                assert_eq!(scanned_sum, scalar_sum);
            }
        }
    }

    #[test]
    fn index_fast_path_preserves_first_error_and_fuel_prefix() {
        for values in [&[][..], &[0, 1, 2], &[0, 7, 1], &[7, 0, 1]] {
            for limit in 0..=8 {
                let mut scalar = Work {
                    remaining: limit,
                    limit,
                };
                let mut fast = Work {
                    remaining: limit,
                    limit,
                };
                let expected = (|| {
                    for &index in values {
                        scalar.add(1)?;
                        if index >= 3 {
                            return Err(Error::IndexOutOfBounds);
                        }
                    }
                    Ok(())
                })();
                assert_eq!(fast.indices(values, 3), expected);
                assert_eq!(fast.remaining, scalar.remaining);
            }
        }
    }
}