draco-core 2.1.0

Pure Rust core encoder and decoder for Draco geometry compression
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
//! Integer sequential attribute decoder.
//!
//! [`SequentialIntegerAttributeDecoder`] decodes integer (and quantized
//! portable) attribute values, applying the inverse prediction scheme selected
//! by the bitstream to reconstruct each value from its predecessors. It is the
//! decode workhorse for positions, texture coordinates, and other quantized
//! attributes. Port of Draco's `sequential_integer_attribute_decoder.h`.

use crate::corner_table::CornerTable;
use crate::decoder_buffer::DecoderBuffer;
use crate::draco_types::DataType;
use crate::geometry_attribute::PointAttribute;
use crate::geometry_indices::{CornerIndex, INVALID_CORNER_INDEX};
use crate::mesh_prediction_scheme_data::MeshPredictionSchemeData;
use crate::point_cloud::PointCloud;
use crate::point_cloud_decoder::PointCloudDecoder;
use crate::portable_attribute::PredictionParent;
use crate::prediction_scheme::{
    EntryToPointIdMap, PredictionScheme, PredictionSchemeDecoder, PredictionSchemeMethod,
    PredictionSchemeTransformType,
};
use crate::prediction_scheme_constrained_multi_parallelogram::MeshPredictionSchemeConstrainedMultiParallelogramDecoder;
use crate::prediction_scheme_delta::PredictionSchemeDeltaDecoder;
use crate::prediction_scheme_geometric_normal::MeshPredictionSchemeGeometricNormalDecoder;
#[cfg(feature = "legacy_bitstream_decode")]
use crate::prediction_scheme_multi_parallelogram::MeshPredictionSchemeMultiParallelogramDecoder;
use crate::prediction_scheme_normal_octahedron_canonicalized_decoding_transform::PredictionSchemeNormalOctahedronCanonicalizedDecodingTransform;
use crate::prediction_scheme_parallelogram::MeshPredictionSchemeParallelogramDecoder;
#[cfg(feature = "legacy_bitstream_decode")]
use crate::prediction_scheme_tex_coords_deprecated::MeshPredictionSchemeTexCoordsDeprecatedDecoder;
use crate::prediction_scheme_tex_coords_portable::MeshPredictionSchemeTexCoordsPortableDecoder;
use crate::prediction_scheme_wrap::PredictionSchemeWrapDecodingTransform;
use crate::status::{DracoError, Status};
use crate::symbol_encoding::{decode_symbols, SymbolEncodingOptions};

/// How a portable attribute may be sized before a value has been read.
///
/// The two geometry decoders answer this differently and both are right: a
/// mesh's point-id list comes out of the decoded corner table, so its length is
/// backed by data, while a point cloud has only the count the header states.
pub enum PortableExtent {
    /// A count the connectivity already produced; reserve it in one go.
    Decoded(usize),
    /// A count nothing has backed yet; let the buffer grow as values arrive.
    Declared(usize),
}

impl PortableExtent {
    /// The extent of the values a point-id map describes.
    ///
    /// The two array variants are arrays: their length is a count something
    /// already produced, and reserving it costs what the array itself cost.
    /// The identity variant is a number the stream declared and nothing has
    /// backed -- it materializes no array precisely so that a claim of a
    /// billion points does not cost four bytes each, and sizing the portable
    /// attribute from its `len()` spends that claim anyway, one value at a
    /// time instead.
    pub fn of(map: crate::prediction_scheme::EntryToPointIdMap<'_>) -> Self {
        match map {
            crate::prediction_scheme::EntryToPointIdMap::Identity(num_points) => {
                PortableExtent::Declared(num_points)
            }
            other => PortableExtent::Decoded(other.len()),
        }
    }

    /// Initializes `portable` to hold values of this shape, reserving or
    /// deferring according to what backs the count.
    pub fn init(
        &self,
        portable: &mut crate::geometry_attribute::PointAttribute,
        attribute_type: crate::geometry_attribute::GeometryAttributeType,
        num_components: u8,
        data_type: crate::draco_types::DataType,
        normalized: bool,
    ) -> Status {
        match *self {
            PortableExtent::Decoded(size) => {
                portable.try_init(attribute_type, num_components, data_type, normalized, size)
            }
            PortableExtent::Declared(size) => {
                portable.init_deferred(attribute_type, num_components, data_type, normalized, size)
            }
        }
    }
}

pub struct SequentialIntegerAttributeDecoder {
    attribute: i32,
    prediction_scheme: Option<Box<dyn PredictionSchemeDecoder<'static, i32>>>,
    /// The bitstream version, captured at `init` the way upstream reads
    /// `decoder_->bitstream_version()` inside `InitPredictionScheme`. It
    /// decides which parent binding the fallback sites may make.
    bitstream_version: u16,
}

fn build_vertex_to_data_map_from_data_to_corner_map(
    corner_table: &CornerTable,
    data_to_corner_map: &[u32],
    vertex_to_data_map: &mut Vec<i32>,
) -> Status {
    vertex_to_data_map.resize(corner_table.num_vertices(), -1);
    for (data_id, &corner_u32) in data_to_corner_map.iter().enumerate() {
        let corner_id = CornerIndex(corner_u32);
        if corner_id == INVALID_CORNER_INDEX {
            continue;
        }
        if corner_id.0 as usize >= corner_table.num_corners() {
            return Err(DracoError::general(format!(
                "Entry {data_id} maps to corner {corner_u32}, past the {} in the table",
                corner_table.num_corners()
            )));
        }
        let v = corner_table.vertex(corner_id).0 as usize;
        let Some(slot) = vertex_to_data_map.get_mut(v) else {
            return Err(DracoError::general(format!(
                "Corner {corner_u32} maps to vertex {v}, past the {} in the table",
                corner_table.num_vertices()
            )));
        };
        *slot = data_id as i32;
    }
    Ok(())
}

/// The corner and vertex maps a mesh predictor reads, borrowed from the mesh
/// decoder's own traversal when it has already built them.
///
/// Both maps are read-only from here on, and on the EdgeBreaker path the
/// decoder hands down arrays it built itself. Copying those into owned
/// buffers costs two allocations the size of the point and vertex counts,
/// plus two `memcpy`s, per attribute -- for data nothing writes to. The owned
/// vectors are filled only for the cases with no override to borrow.
fn prediction_maps<'a>(
    corner_table: &CornerTable,
    num_points: usize,
    data_to_corner_map_override: Option<&'a [u32]>,
    vertex_to_data_map_override: Option<&'a [i32]>,
    data_to_corner_map: &'a mut Vec<u32>,
    vertex_to_data_map: &'a mut Vec<i32>,
) -> Result<(&'a [u32], &'a [i32]), DracoError> {
    let data_to_corner: &[u32] = match data_to_corner_map_override {
        Some(map) if map.len() == num_points => map,
        Some(_) => {
            return Err(DracoError::general(
                "Invalid data_to_corner_map_override length".to_string(),
            ))
        }
        // No override: the map stays empty of meaning, as it was when this
        // was a `resize(num_points, 0)` -- the vertex map below is what the
        // predictor actually reads in that case.
        None => {
            data_to_corner_map.clear();
            data_to_corner_map.resize(num_points, 0);
            data_to_corner_map
        }
    };

    let vertex_to_data: &[i32] = match vertex_to_data_map_override {
        Some(map) if map.len() == corner_table.num_vertices() => map,
        Some(_) => {
            return Err(DracoError::general(
                "Invalid vertex_to_data_map_override length".to_string(),
            ))
        }
        // The corner table may carry seam-split vertices with ids outside the
        // original point range, so this is derived rather than assumed.
        None => {
            build_vertex_to_data_map_from_data_to_corner_map(
                corner_table,
                data_to_corner,
                vertex_to_data_map,
            )?;
            vertex_to_data_map
        }
    };

    Ok((data_to_corner, vertex_to_data))
}

/// Runs `decode_prediction_data` on the selected predictor, logging and failing
/// when the slot is empty or the call fails. Collapses the identical
/// extract-and-check boilerplate that the apply matches repeat per method.
/// `?Sized` lets it accept both the concrete locally-built predictors and the
/// `dyn`-typed `self.prediction_scheme`.
fn run_decode_prediction_data<'a, P: PredictionSchemeDecoder<'a, i32> + ?Sized>(
    predictor: Option<&mut P>,
    buffer: &mut DecoderBuffer,
) -> Status {
    let Some(predictor) = predictor else {
        return Err(DracoError::general(
            "Predictor was selected but not initialized".to_string(),
        ));
    };
    predictor.decode_prediction_data(buffer)
}

/// Runs `compute_original_values` on the selected predictor, with the same
/// empty-slot / failure handling as [`run_decode_prediction_data`].
/// `values` holds the decoded corrections on entry and the reconstructed
/// values on return -- prediction runs in place on the one buffer.
fn run_compute_original_values<'a, P: PredictionSchemeDecoder<'a, i32> + ?Sized>(
    predictor: Option<&mut P>,
    values: &mut [i32],
    num_values: usize,
    num_components: usize,
    entry_to_point_id_map: Option<crate::prediction_scheme::EntryToPointIdMap<'_>>,
) -> Status {
    let Some(predictor) = predictor else {
        return Err(DracoError::general(
            "Predictor was selected but not initialized".to_string(),
        ));
    };
    predictor.compute_original_values(values, num_values, num_components, entry_to_point_id_map)
}

impl Default for SequentialIntegerAttributeDecoder {
    fn default() -> Self {
        Self::new()
    }
}

impl SequentialIntegerAttributeDecoder {
    pub fn new() -> Self {
        Self {
            attribute: -1,
            prediction_scheme: None,
            bitstream_version: 0,
        }
    }

    pub fn init(&mut self, decoder: &PointCloudDecoder, attribute_id: i32) {
        self.attribute = attribute_id;
        self.bitstream_version = decoder.bitstream_version();
    }

    pub fn attribute_id(&self) -> i32 {
        self.attribute
    }

    pub fn set_prediction_scheme(
        &mut self,
        scheme: Box<dyn PredictionSchemeDecoder<'static, i32>>,
    ) {
        self.prediction_scheme = Some(scheme);
    }

    /// Binds the position parent the way the bitstream version demands.
    ///
    /// A registered portable copy wins, and it validates as one: upstream
    /// reaches the parent only through `GetPortableAttribute`, so the copy is
    /// what the portable pass wrote. Without one, the two eras part ways, as
    /// they do in upstream's `InitPredictionScheme`: below 2.0 it passes the
    /// attribute itself, which by then holds dequantized values at whatever
    /// type it declares -- the `legacy` binding. At 2.0 and above a missing
    /// portable copy leaves only the attribute this decoder's integer pass
    /// wrote, whose values are the portable `int32` bits verbatim for every
    /// declared type the pass can produce; `portable` validates exactly that,
    /// and a float or 64-bit position -- which no portable pass ever wrote --
    /// fails the decode the way upstream fails when `GetPortableAttribute`
    /// returns null.
    fn resolve_parent<'p>(
        &self,
        point_cloud: &'p PointCloud,
        portable_parent_attribute: Option<&'p PointAttribute>,
        pos_att_id: i32,
    ) -> Result<PredictionParent<'p>, DracoError> {
        if let Some(att) = portable_parent_attribute {
            return PredictionParent::portable(att);
        }
        let att = point_cloud.try_attribute(pos_att_id)?;
        if self.bitstream_version < 0x0200 {
            return Ok(PredictionParent::legacy(att));
        }
        PredictionParent::portable(att)
    }

    // Complex mesh decoding requires all 8 parameters: mesh data, traversal maps,
    // corner table for prediction, and optional portable attribute output.
    // Refactoring into a struct would obscure the data flow and break C++ API parity.
    #[allow(clippy::too_many_arguments)]
    pub fn decode_values(
        &mut self,
        point_cloud: &mut PointCloud,
        point_ids: EntryToPointIdMap<'_>,
        in_buffer: &mut DecoderBuffer,
        corner_table: Option<&CornerTable>,
        data_to_corner_map_override: Option<&[u32]>,
        vertex_to_data_map_override: Option<&[i32]>,
        portable_attribute: Option<&mut PointAttribute>,
        portable_parent_attribute: Option<&PointAttribute>,
        pre_integer_decode: Option<&mut dyn FnMut(&mut DecoderBuffer<'_>) -> bool>,
    ) -> Status {
        let att_id = self.attribute;
        if att_id < 0 {
            return Err(DracoError::invalid_parameter(
                "Integer attribute decoder was never given an attribute".to_string(),
            ));
        }

        let num_points = point_ids.len();
        // No shortcut for an empty attribute: the prediction header and the
        // entropy stream's own header are written whether or not a value
        // follows, and upstream reads them unconditionally. Returning early
        // left them in the buffer, and whatever the stream carries next -- the
        // octahedral transform's bit count, in the campaign's reproducer -- was
        // read out of the middle of them.

        let attribute = if let Some(ref pa) = portable_attribute {
            &**pa
        } else {
            point_cloud.try_attribute(att_id)?
        };

        let num_components = attribute.num_components() as usize;
        // Both factors come from the bitstream, and `usize` is 32 bits on the
        // wasm32 target this ships to, where the product of a large point count
        // and 255 components wraps rather than saturating.
        let Some(num_values) = num_points.checked_mul(num_components) else {
            return Err(DracoError::general(format!(
                "{num_points} points times {num_components} components overflows"
            )));
        };

        // 3. Decode Prediction Method and (optional) prepare predictor
        let method_byte = match in_buffer.decode_u8() {
            Ok(v) => v,
            Err(_) => {
                return Err(DracoError::general(
                    "Failed to decode prediction method".to_string(),
                ));
            }
        };

        // Draco stores prediction method as int8 (0xFE == -2 == None).
        // Accept 0xFF as None as well for older Rust-produced streams that used
        // the wrong sentinel before this decoder matched the C++ enum exactly.
        let selected_method = if method_byte == 0xFF || method_byte == 0xFE {
            PredictionSchemeMethod::None
        } else {
            match PredictionSchemeMethod::try_from(method_byte) {
                Ok(m) => m,
                Err(_) => {
                    return Err(DracoError::unsupported_feature(format!(
                        "Prediction method {method_byte}"
                    )));
                }
            }
        };

        let mut selected_transform: Option<PredictionSchemeTransformType> = None;
        if selected_method != PredictionSchemeMethod::None {
            // Draco stores prediction transform type as int8 (0xFF == -1 == None).
            let transform_byte = in_buffer.decode_u8().map_err(|_| {
                DracoError::buffer("Stream ends before the prediction transform type".to_string())
            })?;
            if transform_byte != 0xFF {
                match PredictionSchemeTransformType::try_from(transform_byte) {
                    Ok(t) => selected_transform = Some(t),
                    Err(_) => {
                        return Err(DracoError::unsupported_feature(format!(
                            "Prediction transform type {transform_byte}"
                        )));
                    }
                }
            }
        }

        if let Some(ref scheme) = self.prediction_scheme {
            if scheme.get_prediction_method() != selected_method {
                return Err(DracoError::general(format!(
                    "Prediction method mismatch. Stream: {selected_method:?}, Scheme: {:?}",
                    scheme.get_prediction_method()
                )));
            }
        }

        let mut predictor_opt: Option<
            PredictionSchemeDeltaDecoder<i32, PredictionSchemeWrapDecodingTransform<i32>>,
        > = None;
        let mut predictor_normal_octa_diff_opt: Option<
            PredictionSchemeDeltaDecoder<
                i32,
                PredictionSchemeNormalOctahedronCanonicalizedDecodingTransform,
            >,
        > = None;
        let mut predictor_parallelogram_opt: Option<
            MeshPredictionSchemeParallelogramDecoder<
                i32,
                PredictionSchemeWrapDecodingTransform<i32>,
            >,
        > = None;
        #[cfg(feature = "legacy_bitstream_decode")]
        let mut predictor_multi_parallelogram_opt: Option<
            MeshPredictionSchemeMultiParallelogramDecoder<
                '_,
                i32,
                PredictionSchemeWrapDecodingTransform<i32>,
            >,
        > = None;
        let mut predictor_constrained_multi_parallelogram_opt: Option<
            MeshPredictionSchemeConstrainedMultiParallelogramDecoder<
                '_,
                i32,
                PredictionSchemeWrapDecodingTransform<i32>,
            >,
        > = None;
        #[cfg(feature = "legacy_bitstream_decode")]
        let mut predictor_tex_coords_deprecated_opt: Option<
            MeshPredictionSchemeTexCoordsDeprecatedDecoder<
                '_,
                PredictionSchemeWrapDecodingTransform<i32>,
            >,
        > = None;
        let mut predictor_tex_coords_opt: Option<MeshPredictionSchemeTexCoordsPortableDecoder> =
            None;
        let mut predictor_geometric_normal_opt: Option<MeshPredictionSchemeGeometricNormalDecoder> =
            None;

        // Maps need to live long enough
        let mut vertex_to_data_map: Vec<i32> = Vec::new();
        let mut data_to_corner_map: Vec<u32> = Vec::new();
        match selected_method {
            _ if self.prediction_scheme.is_some() => {
                // Do nothing, scheme already set
            }
            PredictionSchemeMethod::Difference => match selected_transform {
                Some(PredictionSchemeTransformType::NormalOctahedronCanonicalized) => {
                    let transform =
                        PredictionSchemeNormalOctahedronCanonicalizedDecodingTransform::new();
                    let predictor = PredictionSchemeDeltaDecoder::new(transform);
                    predictor_normal_octa_diff_opt = Some(predictor);
                }
                // Pre-0.10.0 normals use the legacy non-canonicalized octahedron
                // transform (id 2). Without this case it fell through to Wrap below,
                // silently decoding to wrong normals.
                Some(PredictionSchemeTransformType::NormalOctahedron) => {
                    let mut transform =
                        PredictionSchemeNormalOctahedronCanonicalizedDecodingTransform::new();
                    transform.set_canonicalized(false);
                    let predictor = PredictionSchemeDeltaDecoder::new(transform);
                    predictor_normal_octa_diff_opt = Some(predictor);
                }
                _ => {
                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let predictor = PredictionSchemeDeltaDecoder::new(transform);
                    predictor_opt = Some(predictor);
                }
            },
            PredictionSchemeMethod::MeshPredictionParallelogram => {
                if let Some(corner_table) = corner_table {
                    // Generate maps
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let predictor = MeshPredictionSchemeParallelogramDecoder::new(
                        attribute, transform, mesh_data,
                    );
                    predictor_parallelogram_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "Parallelogram prediction requires corner table".to_string(),
                    ));
                }
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                if let Some(corner_table) = corner_table {
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let predictor =
                        MeshPredictionSchemeMultiParallelogramDecoder::new(transform, mesh_data);
                    predictor_multi_parallelogram_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "MultiParallelogram prediction requires corner table".to_string(),
                    ));
                }
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                return Err(DracoError::general(
                    "MultiParallelogram prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionConstrainedMultiParallelogram => {
                if let Some(corner_table) = corner_table {
                    // Generate maps
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let predictor = MeshPredictionSchemeConstrainedMultiParallelogramDecoder::new(
                        transform, mesh_data,
                    );
                    predictor_constrained_multi_parallelogram_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "ConstrainedMultiParallelogram prediction requires corner table"
                            .to_string(),
                    ));
                }
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                if let Some(corner_table) = corner_table {
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let mut predictor =
                        MeshPredictionSchemeTexCoordsDeprecatedDecoder::new(transform);
                    predictor.init(&mesh_data);

                    let pos_att_id = point_cloud.named_attribute_id(
                        crate::geometry_attribute::GeometryAttributeType::Position,
                    );
                    if pos_att_id >= 0 {
                        let parent = self.resolve_parent(
                            point_cloud,
                            portable_parent_attribute,
                            pos_att_id,
                        )?;
                        if predictor.set_parent_attribute(parent).is_err() {
                            return Err(DracoError::general(
                                "Failed to set parent attribute for TexCoordsDeprecated"
                                    .to_string(),
                            ));
                        }
                    } else {
                        return Err(DracoError::general(
                            "Position attribute not found for TexCoordsDeprecated".to_string(),
                        ));
                    }

                    predictor_tex_coords_deprecated_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "TexCoordsDeprecated prediction requires corner table".to_string(),
                    ));
                }
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                return Err(DracoError::general(
                    "TexCoordsDeprecated prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionTexCoordsPortable => {
                if let Some(corner_table) = corner_table {
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let transform = PredictionSchemeWrapDecodingTransform::<i32>::new();
                    let mut predictor =
                        MeshPredictionSchemeTexCoordsPortableDecoder::new(transform);
                    predictor.init(&mesh_data);

                    // Set parent attribute (Position)
                    let pos_att_id = point_cloud.named_attribute_id(
                        crate::geometry_attribute::GeometryAttributeType::Position,
                    );
                    if pos_att_id >= 0 {
                        let parent = self.resolve_parent(
                            point_cloud,
                            portable_parent_attribute,
                            pos_att_id,
                        )?;
                        if predictor.set_parent_attribute(parent).is_err() {
                            return Err(DracoError::general(
                                "Failed to set parent attribute for TexCoordsPortable".to_string(),
                            ));
                        }
                    } else {
                        return Err(DracoError::general(
                            "Position attribute not found for TexCoordsPortable".to_string(),
                        ));
                    }

                    predictor_tex_coords_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "TexCoordsPortable prediction requires corner table".to_string(),
                    ));
                }
            }
            PredictionSchemeMethod::MeshPredictionGeometricNormal => {
                if let Some(corner_table) = corner_table {
                    let (dcm, vdm) = prediction_maps(
                        corner_table,
                        num_points,
                        data_to_corner_map_override,
                        vertex_to_data_map_override,
                        &mut data_to_corner_map,
                        &mut vertex_to_data_map,
                    )?;

                    let mut mesh_data = MeshPredictionSchemeData::new();
                    mesh_data.set(corner_table, dcm, vdm);

                    let mut transform =
                        PredictionSchemeNormalOctahedronCanonicalizedDecodingTransform::new();
                    // Pre-0.10.0 streams use the legacy non-canonicalized octahedron
                    // transform (id 2); 0.10.0+ use the canonicalized one (id 3).
                    if matches!(
                        selected_transform,
                        Some(PredictionSchemeTransformType::NormalOctahedron)
                    ) {
                        transform.set_canonicalized(false);
                    }
                    let mut predictor = MeshPredictionSchemeGeometricNormalDecoder::new(transform);
                    predictor.init(&mesh_data);

                    // Provide mapping from decoded-entry index to original point id.
                    predictor.set_entry_to_point_id_map(point_ids);

                    // Set parent attribute (Position)
                    let pos_att_id = point_cloud.named_attribute_id(
                        crate::geometry_attribute::GeometryAttributeType::Position,
                    );
                    if pos_att_id >= 0 {
                        let parent = self.resolve_parent(
                            point_cloud,
                            portable_parent_attribute,
                            pos_att_id,
                        )?;
                        if predictor.set_parent_attribute(parent).is_err() {
                            return Err(DracoError::general(
                                "Failed to set parent attribute for GeometricNormal".to_string(),
                            ));
                        }
                    } else {
                        return Err(DracoError::general(
                            "Position attribute not found for GeometricNormal".to_string(),
                        ));
                    }

                    predictor_geometric_normal_opt = Some(predictor);
                } else {
                    return Err(DracoError::general(
                        "GeometricNormal prediction requires corner table".to_string(),
                    ));
                }
            }
            PredictionSchemeMethod::None => {}
            _ => {
                return Err(DracoError::unsupported_feature(format!(
                    "Prediction method {selected_method:?}"
                )));
            }
        }

        // 1. Decode correction symbols.
        // For v < 2.0, transform-specific parameters (quantization, octahedron)
        // are stored BEFORE the integer values. The caller provides a hook.
        if let Some(hook) = pre_integer_decode {
            if !hook(in_buffer) {
                return Err(DracoError::general(
                    "Failed to decode the pre-2.0 inline transform parameters".to_string(),
                ));
            }
        }
        // Draco supports both entropy-coded symbols (compressed=1) and raw symbols (compressed=0).
        let compressed = in_buffer.decode_u8().map_err(|_| {
            DracoError::buffer("Stream ends before the compression flag".to_string())
        })?;

        // Check if the prediction scheme produces positive corrections (no ZigZag needed)
        // Octahedron transforms (for normals) produce positive corrections
        let are_corrections_positive = match selected_transform {
            Some(PredictionSchemeTransformType::NormalOctahedron)
            | Some(PredictionSchemeTransformType::NormalOctahedronCanonicalized) => true,
            _ => {
                // Fallback: check self.prediction_scheme if it's set
                if let Some(ref scheme) = self.prediction_scheme {
                    scheme.are_corrections_positive()
                } else {
                    false
                }
            }
        };

        let needs_zigzag_conversion = !are_corrections_positive;
        // One buffer for the whole pipeline: it holds the decoded corrections
        // first, and the prediction pass below reconstructs the original
        // values over them in place. Upstream's sequential decoder does the
        // same (its `in_corr` and `out_data` are one pointer); a separate
        // zeroed `values` vector cost an allocation plus a memset per
        // attribute for data the prediction pass immediately overwrote.
        let mut values: Vec<i32> = if compressed > 0 {
            // Entropy-coded symbols are zigzag encoded UNLESS the prediction scheme
            // guarantees positive corrections (e.g., normal octahedron transform)
            // Empty on purpose. `num_values` comes from the header, and the
            // header is the attacker's: reserving for it here is what let a
            // 9 KB stream ask for gigabytes before decoding a single symbol.
            // `decode_symbols` grows this as symbols actually arrive.
            let mut symbols = Vec::new();
            let options = SymbolEncodingOptions::default();
            decode_symbols(
                num_values,
                num_components,
                &options,
                in_buffer,
                &mut symbols,
            )
            .map_err(|err| err.context("Failed to decode the entropy-coded symbols"))?;
            symbols_to_corrections(symbols, needs_zigzag_conversion)
        } else {
            // Raw uncompressed integers. Read directly as bytes.
            // ZigZag conversion is needed unless the scheme guarantees positive corrections.
            let num_bytes = match in_buffer.decode_u8() {
                Ok(v) => v as usize,
                Err(_) => {
                    return Err(DracoError::buffer(
                        "Stream ends before the raw correction byte width".to_string(),
                    ))
                }
            };
            if num_bytes > 4 {
                return Err(DracoError::general(format!(
                    "Raw corrections declare {num_bytes} bytes per value, at most 4 fit an i32"
                )));
            }

            // Raw corrections are copied out of the stream a fixed number of
            // bytes at a time, so the stream is an exact bound on how many
            // there can be -- the one rung above any ratio.
            //
            // `num_bytes == 0` reads nothing: "every correction is zero" is a
            // claim in the header, and the buffer it sizes is the attribute's
            // own output. Nothing backs the count, so this is the one place in
            // the decoder where the allocation budget is load-bearing rather
            // than a backstop -- and, since the budget is charged nowhere else,
            // its entire practical surface. What it permits, exactly: below a
            // 256-byte stream the ratio binds at `262,144` values per input
            // byte, above it the absolute ceiling binds at `67,108,864` values,
            // which is 22.4 million vec3 points. This crate never writes such a
            // stream -- its encoder always emits entropy-coded corrections --
            // so reaching either bound means a file from elsewhere whose
            // corrections are uniformly zero and whose point count is past
            // that.
            if num_bytes == 0 {
                in_buffer.charge_elements(num_values, std::mem::size_of::<i32>())?;
            } else {
                let Some(byte_len) = num_values.checked_mul(num_bytes) else {
                    return Err(DracoError::general(format!(
                        "{num_values} {num_bytes}-byte corrections overflow a byte count"
                    )));
                };
                if byte_len > in_buffer.remaining_size() {
                    return Err(DracoError::buffer(format!(
                        "declared {num_values} raw corrections of {num_bytes} bytes, more than the \n                         {} bytes left in the stream",
                        in_buffer.remaining_size()
                    )));
                }
            }

            let Some(mut raw_corrections) = try_reserved::<i32>(num_values) else {
                return Err(DracoError::general(format!(
                    "Failed to allocate {num_values} raw corrections"
                )));
            };
            if num_bytes == 0 {
                // All values are zero — nothing to read from the buffer.
                raw_corrections.resize(num_values, 0);
            } else if num_bytes == 4 {
                let Some(byte_len) = num_values.checked_mul(4) else {
                    return Err(DracoError::general(format!(
                        "{num_values} four-byte corrections overflow a byte count"
                    )));
                };
                let bytes = in_buffer.decode_slice(byte_len).map_err(|_| {
                    DracoError::buffer(format!(
                        "Stream holds fewer than the {byte_len} bytes of raw corrections it declares"
                    ))
                })?;
                for chunk in bytes.as_chunks::<4>().0 {
                    let symbol = u32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
                    raw_corrections.push(symbol_to_correction(symbol, needs_zigzag_conversion));
                }
            } else {
                for _ in 0..num_values {
                    let mut tmp = [0u8; 4];
                    if in_buffer.decode_bytes(&mut tmp[..num_bytes]).is_err() {
                        return Err(DracoError::buffer(
                            "Stream ends inside the raw corrections".to_string(),
                        ));
                    }
                    let symbol = u32::from_le_bytes(tmp);
                    raw_corrections.push(symbol_to_correction(symbol, needs_zigzag_conversion));
                }
            }
            raw_corrections
        };

        // 3. Decode prediction scheme data (if any).
        match selected_method {
            _ if self.prediction_scheme.is_some() => {
                run_decode_prediction_data(self.prediction_scheme.as_deref_mut(), in_buffer)?;
            }
            PredictionSchemeMethod::Difference => {
                let ok = if predictor_normal_octa_diff_opt.is_some() {
                    run_decode_prediction_data(predictor_normal_octa_diff_opt.as_mut(), in_buffer)
                } else {
                    run_decode_prediction_data(predictor_opt.as_mut(), in_buffer)
                };
                ok?;
            }
            PredictionSchemeMethod::MeshPredictionParallelogram => {
                run_decode_prediction_data(predictor_parallelogram_opt.as_mut(), in_buffer)?;
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                run_decode_prediction_data(predictor_multi_parallelogram_opt.as_mut(), in_buffer)?;
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                return Err(DracoError::general(
                    "MultiParallelogram prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionConstrainedMultiParallelogram => {
                run_decode_prediction_data(
                    predictor_constrained_multi_parallelogram_opt.as_mut(),
                    in_buffer,
                )?;
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                run_decode_prediction_data(
                    predictor_tex_coords_deprecated_opt.as_mut(),
                    in_buffer,
                )?;
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                return Err(DracoError::general(
                    "TexCoordsDeprecated prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionTexCoordsPortable => {
                run_decode_prediction_data(predictor_tex_coords_opt.as_mut(), in_buffer)?;
            }
            PredictionSchemeMethod::MeshPredictionGeometricNormal => {
                run_decode_prediction_data(predictor_geometric_normal_opt.as_mut(), in_buffer)?;
            }
            PredictionSchemeMethod::None => {}
            _ => {
                return Err(DracoError::unsupported_feature(format!(
                    "Prediction method {selected_method:?}"
                )));
            }
        }

        // 4. Apply Inverse Prediction. Nothing to revert without a value:
        // every predictor starts by computing the first entry, which an empty
        // buffer does not have. Upstream guards the same call the same way.
        // Returning here rather than skipping to step 5 costs nothing -- with
        // no values there is nothing to store.
        if num_values == 0 {
            return Ok(());
        }
        match selected_method {
            _ if self.prediction_scheme.is_some() => {
                let map_opt = match selected_method {
                    PredictionSchemeMethod::MeshPredictionParallelogram
                    | PredictionSchemeMethod::MeshPredictionMultiParallelogram
                    | PredictionSchemeMethod::MeshPredictionConstrainedMultiParallelogram
                    | PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated
                    | PredictionSchemeMethod::MeshPredictionTexCoordsPortable
                    | PredictionSchemeMethod::MeshPredictionGeometricNormal => Some(point_ids),
                    _ => None,
                };
                run_compute_original_values(
                    self.prediction_scheme.as_deref_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    map_opt,
                )?;
            }
            PredictionSchemeMethod::Difference => {
                let ok = if predictor_normal_octa_diff_opt.is_some() {
                    run_compute_original_values(
                        predictor_normal_octa_diff_opt.as_mut(),
                        &mut values,
                        num_values,
                        num_components,
                        None,
                    )
                } else {
                    run_compute_original_values(
                        predictor_opt.as_mut(),
                        &mut values,
                        num_values,
                        num_components,
                        None,
                    )
                };
                ok?;
            }
            PredictionSchemeMethod::MeshPredictionParallelogram => {
                run_compute_original_values(
                    predictor_parallelogram_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    None,
                )?;
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                run_compute_original_values(
                    predictor_multi_parallelogram_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    None,
                )?;
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionMultiParallelogram => {
                return Err(DracoError::general(
                    "MultiParallelogram prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionConstrainedMultiParallelogram => {
                run_compute_original_values(
                    predictor_constrained_multi_parallelogram_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    None,
                )?;
            }
            #[cfg(feature = "legacy_bitstream_decode")]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                let map = Some(point_ids);
                run_compute_original_values(
                    predictor_tex_coords_deprecated_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    map,
                )?;
            }
            #[cfg(not(feature = "legacy_bitstream_decode"))]
            PredictionSchemeMethod::MeshPredictionTexCoordsDeprecated => {
                return Err(DracoError::general(
                    "TexCoordsDeprecated prediction is disabled".to_string(),
                ));
            }
            PredictionSchemeMethod::MeshPredictionTexCoordsPortable => {
                let map = Some(point_ids);
                run_compute_original_values(
                    predictor_tex_coords_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    map,
                )?;
            }
            PredictionSchemeMethod::MeshPredictionGeometricNormal => {
                let map = Some(point_ids);
                run_compute_original_values(
                    predictor_geometric_normal_opt.as_mut(),
                    &mut values,
                    num_values,
                    num_components,
                    map,
                )?;
            }
            PredictionSchemeMethod::None => {}
            _ => {
                return Err(DracoError::unsupported_feature(format!(
                    "Prediction method {selected_method:?}"
                )));
            }
        }

        #[cfg(feature = "debug_logs")]
        {
            if num_points > 0 {
                debug_log!(
                    "Sequential Decoded: Point 0 ID = {:?}, Value[0] = {}",
                    crate::geometry_indices::PointIndex(point_ids.get(0).unwrap_or(u32::MAX)),
                    values[0]
                );
                // Debug: print all decoded values (quantized) and where they go
                debug_log!("DEBUG decoded values (first 25 x/y/z):");
                if num_components >= 3 {
                    for i in 0..std::cmp::min(25, num_points) {
                        let x = values[i * num_components];
                        let y = values[i * num_components + 1];
                        let z = values[i * num_components + 2];
                        debug_log!(
                            "  data_id={} -> point_ids[{}]={:?}: quantized({}, {}, {})",
                            i,
                            i,
                            crate::geometry_indices::PointIndex(
                                point_ids.get(i).unwrap_or(u32::MAX)
                            ),
                            x,
                            y,
                            z
                        );
                    }
                }
            }
        }

        // 5. Store values (+ optional inverse transform)
        if let Some(portable_att) = portable_attribute {
            if !store_i32_values_to_attribute(portable_att, &values, num_points, num_components) {
                return Err(DracoError::general(
                    "Decoded values do not fit the portable attribute".to_string(),
                ));
            }
        } else {
            let dst_attribute = point_cloud.try_attribute_mut(att_id)?;
            if !store_i32_values_to_attribute(dst_attribute, &values, num_points, num_components) {
                return Err(DracoError::general(
                    "Decoded values do not fit the destination attribute".to_string(),
                ));
            }
        }

        Ok(())
    }
}

/// Reserves room for `len` values, or reports failure instead of aborting.
///
/// `len` here is `num_points * num_components`, and both come out of the
/// bitstream, so it is as large as the file says. Every other allocation this
/// decoder makes from a declared count is already fallible; these were the last
/// infallible ones, and they are the largest — the corrections buffer is three
/// times the point-id vector that precedes it, so on a system that overcommits
/// it is the one that faults rather than the one that returns null.
fn try_reserved<T>(len: usize) -> Option<Vec<T>> {
    let mut values = Vec::new();
    values.try_reserve_exact(len).ok()?;
    Some(values)
}

#[inline]
fn symbol_to_correction(symbol: u32, needs_zigzag_conversion: bool) -> i32 {
    if needs_zigzag_conversion {
        ((symbol >> 1) as i32) ^ (-((symbol & 1) as i32))
    } else {
        symbol as i32
    }
}

#[inline]
fn symbols_to_corrections(symbols: Vec<u32>, needs_zigzag_conversion: bool) -> Vec<i32> {
    symbols
        .into_iter()
        .map(|symbol| symbol_to_correction(symbol, needs_zigzag_conversion))
        .collect()
}

/// Store decoded i32 values into an attribute buffer.
/// Uses bulk memcpy when the attribute layout matches i32/u32 tightly packed.
#[inline]
fn store_i32_values_to_attribute(
    attr: &mut PointAttribute,
    values: &[i32],
    num_points: usize,
    num_components: usize,
) -> bool {
    let Ok(byte_stride) = usize::try_from(attr.byte_stride()) else {
        return false;
    };
    let data_type = attr.data_type();
    let component_size = data_type.byte_length();
    let Some(packed_row) = num_components.checked_mul(component_size) else {
        return false;
    };
    let Some(num_values_required) = num_points.checked_mul(num_components) else {
        return false;
    };
    if values.len() < num_values_required {
        return false;
    }

    // Ensure buffer is large enough for num_points entries.
    let Some(required) = num_points.checked_mul(byte_stride) else {
        return false;
    };
    if attr.buffer().data_size() < required && attr.buffer_mut().try_resize(required).is_err() {
        return false;
    }

    // Fast path: i32/u32 tightly packed — bulk memcpy the entire values array.
    if (data_type == DataType::Int32 || data_type == DataType::Uint32) && byte_stride == packed_row
    {
        let src: &[u8] = bytemuck::cast_slice(&values[..num_values_required]);
        let dst = attr.buffer_mut().data_mut();
        let Some(dst) = dst.get_mut(..src.len()) else {
            return false;
        };
        dst.copy_from_slice(src);
        return true;
    }

    // Slow path: per-component write with type conversion.
    let dst_buffer = attr.buffer_mut();
    for i in 0..num_points {
        let Some(entry_offset) = i.checked_mul(byte_stride) else {
            return false;
        };
        for c in 0..num_components {
            let Some(component_byte_offset) = c.checked_mul(component_size) else {
                return false;
            };
            let Some(component_offset) = entry_offset.checked_add(component_byte_offset) else {
                return false;
            };
            if !write_value_from_i32(
                dst_buffer,
                component_offset,
                data_type,
                values[i * num_components + c],
            ) {
                return false;
            }
        }
    }
    true
}

#[inline(always)]
fn write_value_from_i32(
    buffer: &mut crate::data_buffer::DataBuffer,
    offset: usize,
    data_type: DataType,
    val: i32,
) -> bool {
    match data_type {
        DataType::Int8 => buffer.try_write(offset, &(val as i8).to_le_bytes()),
        DataType::Uint8 => buffer.try_write(offset, &(val as u8).to_le_bytes()),
        DataType::Int16 => buffer.try_write(offset, &(val as i16).to_le_bytes()),
        DataType::Uint16 => buffer.try_write(offset, &(val as u16).to_le_bytes()),
        DataType::Int32 => buffer.try_write(offset, &val.to_le_bytes()),
        DataType::Uint32 => buffer.try_write(offset, &(val as u32).to_le_bytes()),
        _ => true,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry_attribute::{GeometryAttributeType, PointAttribute};
    use crate::geometry_indices::{PointIndex, VertexIndex};
    use crate::point_cloud::PointCloud;

    #[test]
    fn store_i32_values_rejects_short_decoded_values() {
        let mut attr = PointAttribute::new();
        attr.init(GeometryAttributeType::Generic, 3, DataType::Int16, false, 2);

        assert!(!store_i32_values_to_attribute(&mut attr, &[1, 2, 3], 2, 3));
    }

    #[test]
    fn store_i32_values_rejects_impossible_required_size() {
        let mut attr = PointAttribute::new();
        attr.init(GeometryAttributeType::Generic, 1, DataType::Int32, false, 1);

        assert!(!store_i32_values_to_attribute(
            &mut attr,
            &[1],
            usize::MAX,
            1,
        ));
    }

    #[test]
    fn vertex_to_data_map_builder_accepts_valid_corners() {
        let mut corner_table = CornerTable::new(1);
        assert!(corner_table.init(&[[VertexIndex(0), VertexIndex(1), VertexIndex(2),]]));
        let mut vertex_to_data_map = Vec::new();

        assert!(build_vertex_to_data_map_from_data_to_corner_map(
            &corner_table,
            &[0, 1, 2],
            &mut vertex_to_data_map,
        )
        .is_ok());
        assert_eq!(vertex_to_data_map, vec![0, 1, 2]);
    }

    #[test]
    fn vertex_to_data_map_builder_rejects_out_of_range_corner() {
        let mut corner_table = CornerTable::new(1);
        assert!(corner_table.init(&[[VertexIndex(0), VertexIndex(1), VertexIndex(2),]]));
        let mut vertex_to_data_map = Vec::new();

        let error = build_vertex_to_data_map_from_data_to_corner_map(
            &corner_table,
            &[3],
            &mut vertex_to_data_map,
        )
        .expect_err("a corner past the table must be refused");
        assert!(
            error.to_string().contains("corner 3"),
            "the error should name the corner, got: {error}"
        );
    }

    #[test]
    fn decode_values_rejects_invalid_attribute_id() {
        let mut decoder = SequentialIntegerAttributeDecoder::new();
        decoder.init(&PointCloudDecoder::new(), 0);
        let mut point_cloud = PointCloud::new();
        let mut buffer = DecoderBuffer::new(&[]);
        let point_ids = [PointIndex(0)];

        assert!(decoder
            .decode_values(
                &mut point_cloud,
                EntryToPointIdMap::from_point_indices(&point_ids),
                &mut buffer,
                None,
                None,
                None,
                None,
                None,
                None,
            )
            .is_err());
    }

    #[test]
    fn decode_values_with_portable_attribute_allows_missing_destination_id() {
        let mut decoder = SequentialIntegerAttributeDecoder::new();
        decoder.init(&PointCloudDecoder::new(), 0);
        let mut point_cloud = PointCloud::new();
        let mut portable = PointAttribute::new();
        portable.init(GeometryAttributeType::Generic, 1, DataType::Int32, false, 1);
        let bytes = [0xfe, 0, 0, 0, 0];
        let mut buffer = DecoderBuffer::new(&bytes);
        let point_ids = [PointIndex(0)];

        assert!(decoder
            .decode_values(
                &mut point_cloud,
                EntryToPointIdMap::from_point_indices(&point_ids),
                &mut buffer,
                None,
                None,
                None,
                Some(&mut portable),
                None,
                None,
            )
            .is_ok());
    }
}