lc-framework 0.1.0+lc.2025

High-level Rust bindings to the LC compression framework
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
//! [![CI Status]][workflow] [![MSRV]][repo] [![Latest Version]][crates.io]
//! [![Rust Doc Crate]][docs.rs] [![Rust Doc Main]][docs]
//!
//! [CI Status]: https://img.shields.io/github/actions/workflow/status/juntyr/lc-framework-rs/ci.yml?branch=main
//! [workflow]: https://github.com/juntyr/lc-framework-rs/actions/workflows/ci.yml?query=branch%3Amain
//!
//! [MSRV]: https://img.shields.io/badge/MSRV-1.85.0-blue
//! [repo]: https://github.com/juntyr/lc-framework-rs
//!
//! [Latest Version]: https://img.shields.io/crates/v/lc-framework
//! [crates.io]: https://crates.io/crates/lc-framework
//!
//! [Rust Doc Crate]: https://img.shields.io/docsrs/lc-framework
//! [docs.rs]: https://docs.rs/lc-framework/
//!
//! [Rust Doc Main]: https://img.shields.io/badge/docs-main-blue
//! [docs]: https://juntyr.github.io/lc-framework-rs/lc_framework
//!
//! # lc-framework
//!
//! High-level Rust bindigs to the [LC] compression framework.
//!
//! [LC]: https://github.com/burtscher/LC-framework

use std::ffi::c_longlong;

/// Maximum number of components
pub const MAX_COMPONENTS: usize = lc_framework_sys::MAX_STAGES;

/// Maximum number of bytes
pub const MAX_BYTES: usize = const {
    #[allow(clippy::cast_possible_truncation)]
    if std::mem::size_of::<c_longlong>() <= std::mem::size_of::<usize>() {
        c_longlong::MAX as usize
    } else {
        usize::MAX
    }
};

/// Compress the `input` data with LC using zero or more `preprocessors` and
/// one or more `components`.
///
/// # Errors
///
/// Errors with
/// - [`Error::TooFewComponents`] if no `components` are given
/// - [`Error::TooManyComponents`] if too many `components` are given
/// - [`Error::ExcessiveInputData`] if the `input` data is too large
/// - [`Error::CompressionFailed`] if compression with LC failed
/// - [`Error::ExcessiveCompressedData`] if the compressed data is too large
pub fn compress(
    preprocessors: &[Preprocessor],
    components: &[Component],
    input: &[u8],
) -> Result<Vec<u8>, Error> {
    let mut preprocessor_ids = Vec::with_capacity(preprocessors.len());
    let mut preprocessor_params = Vec::new();
    let mut preprocessor_params_num = Vec::with_capacity(preprocessors.len());
    for preprocessor in preprocessors {
        preprocessor_ids.push(preprocessor.as_id());
        let preprocessor_nparams_sum = preprocessor_params.len();
        preprocessor.push_params(&mut preprocessor_params);
        preprocessor_params_num.push(preprocessor_params.len() - preprocessor_nparams_sum);
    }

    if components.is_empty() {
        return Err(Error::TooFewComponents);
    }

    if components.len() > MAX_COMPONENTS {
        return Err(Error::TooManyComponents);
    }

    let component_ids = components
        .iter()
        .copied()
        .map(Component::as_id)
        .collect::<Vec<_>>();

    let input_size: c_longlong = input
        .len()
        .try_into()
        .map_err(|_| Error::ExcessiveInputData)?;

    let mut encoded_ptr = std::ptr::null_mut();
    let mut encoded_size = 0;

    #[expect(unsafe_code)]
    // SAFETY: all pointers and lengths are valid
    let status = unsafe {
        lc_framework_sys::lc_compress(
            preprocessor_ids.len(),
            preprocessor_ids.as_ptr(),
            preprocessor_params_num.as_ptr(),
            preprocessor_params.as_ptr(),
            component_ids.len(),
            component_ids.as_ptr(),
            input.as_ptr(),
            input_size,
            &raw mut encoded_ptr,
            &raw mut encoded_size,
        )
    };

    if status != 0 {
        return Err(Error::CompressionFailed);
    }

    let encoded_len: usize = encoded_size
        .try_into()
        .map_err(|_| Error::ExcessiveCompressedData)?;

    #[expect(unsafe_code)]
    // SAFETY: all Vec elements are initialised via the copy
    let encoded = unsafe {
        let mut encoded = Vec::with_capacity(encoded_len);
        std::ptr::copy_nonoverlapping(encoded_ptr.cast_const(), encoded.as_mut_ptr(), encoded_len);
        encoded.set_len(encoded_len);
        encoded
    };

    #[expect(unsafe_code)]
    // SAFETY: encoded_ptr was allocated by LC
    unsafe {
        lc_framework_sys::lc_free_bytes(encoded_ptr);
    }

    Ok(encoded)
}

/// Dempress the `compressed` data with LC using zero or more `preprocessors`
/// and one or more `components`.
///
/// The `compressed` data must have been [`compress`]ed using the same
/// `preprocessors` and `components`.
///
/// # Errors
///
/// Errors with
/// - [`Error::TooFewComponents`] if no `components` are given
/// - [`Error::TooManyComponents`] if too many `components` are given
/// - [`Error::ExcessiveCompressedData`] if the `compressed` data is too large
/// - [`Error::DecompressionFailed`] if decompression with LC failed
/// - [`Error::ExcessiveDecompressedData`] if the decompressed data is too
///   large
pub fn decompress(
    preprocessors: &[Preprocessor],
    components: &[Component],
    compressed: &[u8],
) -> Result<Vec<u8>, Error> {
    let encoded = compressed;

    let mut preprocessor_ids = Vec::with_capacity(preprocessors.len());
    let mut preprocessor_params = Vec::new();
    let mut preprocessor_params_num = Vec::with_capacity(preprocessors.len());
    for preprocessor in preprocessors {
        preprocessor_ids.push(preprocessor.as_id());
        let preprocessor_nparams_sum = preprocessor_params.len();
        preprocessor.push_params(&mut preprocessor_params);
        preprocessor_params_num.push(preprocessor_params.len() - preprocessor_nparams_sum);
    }

    if components.is_empty() {
        return Err(Error::TooFewComponents);
    }

    if components.len() > MAX_COMPONENTS {
        return Err(Error::TooManyComponents);
    }

    let component_ids = components
        .iter()
        .copied()
        .map(Component::as_id)
        .collect::<Vec<_>>();

    let encoded_size: c_longlong = encoded
        .len()
        .try_into()
        .map_err(|_| Error::ExcessiveCompressedData)?;

    let mut decoded_ptr = std::ptr::null_mut();
    let mut decoded_size = 0;

    #[expect(unsafe_code)]
    // SAFETY: all pointers and lengths are valid
    let status = unsafe {
        lc_framework_sys::lc_decompress(
            preprocessor_ids.len(),
            preprocessor_ids.as_ptr(),
            preprocessor_params_num.as_ptr(),
            preprocessor_params.as_ptr(),
            component_ids.len(),
            component_ids.as_ptr(),
            encoded.as_ptr(),
            encoded_size,
            &raw mut decoded_ptr,
            &raw mut decoded_size,
        )
    };

    if status != 0 {
        return Err(Error::DecompressionFailed);
    }

    let decoded_len: usize = decoded_size
        .try_into()
        .map_err(|_| Error::ExcessiveDecompressedData)?;

    #[expect(unsafe_code)]
    // SAFETY: all Vec elements are initialised via the copy
    let decoded = unsafe {
        let mut decoded = Vec::with_capacity(decoded_len);
        std::ptr::copy_nonoverlapping(decoded_ptr.cast_const(), decoded.as_mut_ptr(), decoded_len);
        decoded.set_len(decoded_len);
        decoded
    };

    #[expect(unsafe_code)]
    // SAFETY: encoded_ptr was allocated by LC
    unsafe {
        lc_framework_sys::lc_free_bytes(decoded_ptr);
    }

    Ok(decoded)
}

#[derive(Debug, thiserror::Error)]
/// Errors that can occur during compression and decompression with LC
pub enum Error {
    /// at least one component must be given
    #[error("at least one component must be given")]
    TooFewComponents,
    /// too many components were given
    #[error("at most {MAX_COMPONENTS} components must be given")]
    TooManyComponents,
    /// input data is too large
    #[error("input data must not exceed {MAX_BYTES} bytes")]
    ExcessiveInputData,
    /// internal compression error
    #[error("internal compression error")]
    CompressionFailed,
    /// compressed data is too large
    #[error("compressed data must not exceed {MAX_BYTES} bytes")]
    ExcessiveCompressedData,
    /// internal decompression error
    #[error("internal decompression error")]
    DecompressionFailed,
    /// decompressed data is too large
    #[error("decompressed data must not exceed {MAX_BYTES} bytes")]
    ExcessiveDecompressedData,
}

#[expect(missing_docs)]
#[derive(Clone, Debug, PartialEq)]
/// LC preprocessor
pub enum Preprocessor {
    Noop,
    Lorenzo1D {
        dtype: LorenzoDtype,
    },
    QuantizeErrorBound {
        dtype: QuantizeDType,
        kind: ErrorKind,
        error_bound: f64,
        threshold: Option<f64>,
        decorrelation: Decorrelation,
    },
}

impl Preprocessor {
    const fn as_id(&self) -> lc_framework_sys::LC_CPUpreprocessor {
        match self {
            Self::Noop => lc_framework_sys::LC_CPUpreprocessor_NUL_CPUpreprocessor,
            Self::Lorenzo1D {
                dtype: LorenzoDtype::I32,
            } => lc_framework_sys::LC_CPUpreprocessor_LOR1D_i32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Abs,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_ABS_0_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Abs,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_ABS_R_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Noa,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_NOA_0_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Noa,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_NOA_R_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Rel,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_REL_0_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F32,
                kind: ErrorKind::Rel,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_REL_R_f32,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Abs,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_ABS_0_f64,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Abs,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_ABS_R_f64,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Noa,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_NOA_0_f64,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Noa,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_NOA_R_f64,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Rel,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Zero,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_REL_0_f64,
            Self::QuantizeErrorBound {
                dtype: QuantizeDType::F64,
                kind: ErrorKind::Rel,
                error_bound: _,
                threshold: _,
                decorrelation: Decorrelation::Random,
            } => lc_framework_sys::LC_CPUpreprocessor_QUANT_REL_R_f64,
        }
    }

    fn push_params(&self, params: &mut Vec<f64>) {
        match self {
            Self::Noop | Self::Lorenzo1D { dtype: _ } => (),
            Self::QuantizeErrorBound {
                dtype: _,
                kind: _,
                error_bound,
                threshold,
                decorrelation: _,
            } => {
                params.push(*error_bound);
                if let Some(threshold) = threshold {
                    params.push(*threshold);
                }
            }
        }
    }
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC error bound kind
pub enum ErrorKind {
    /// pointwise absolute error bound
    Abs,
    /// pointwise normalised absolute / data-range-relative error bound
    Noa,
    /// pointwise relative error bound
    Rel,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC quantisation decorrelation mode
pub enum Decorrelation {
    Zero,
    Random,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC Lorenzo preprocessor dtype
pub enum LorenzoDtype {
    I32,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC quantization dtype
pub enum QuantizeDType {
    F32,
    F64,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC component
pub enum Component {
    Noop,
    // mutators
    TwosComplementToSignMagnitude { size: ElemSize },
    TwosComplementToNegaBinary { size: ElemSize },
    DebiasedExponentFractionSign { size: FloatSize },
    DebiasedExponentSignFraction { size: FloatSize },
    // shufflers
    BitShuffle { size: ElemSize },
    Tuple { size: TupleSize },
    // predictors
    Delta { size: ElemSize },
    DeltaAsSignMagnitude { size: ElemSize },
    DeltaAsNegaBinary { size: ElemSize },
    // reducers
    Clog { size: ElemSize },
    HClog { size: ElemSize },
    Rare { size: ElemSize },
    Raze { size: ElemSize },
    RunLengthEncoding { size: ElemSize },
    RepetitionRunBitmapEncoding { size: ElemSize },
    ZeroRunBitmapEncoding { size: ElemSize },
}

impl Component {
    #[expect(clippy::too_many_lines)]
    const fn as_id(self) -> lc_framework_sys::LC_CPUcomponents {
        match self {
            Self::Noop => lc_framework_sys::LC_CPUcomponents_NUL_CPUcomponents,
            // mutators
            Self::TwosComplementToSignMagnitude { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_TCMS_1
            }
            Self::TwosComplementToSignMagnitude { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_TCMS_2
            }
            Self::TwosComplementToSignMagnitude { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_TCMS_4
            }
            Self::TwosComplementToSignMagnitude { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_TCMS_8
            }
            Self::TwosComplementToNegaBinary { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_TCNB_1
            }
            Self::TwosComplementToNegaBinary { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_TCNB_2
            }
            Self::TwosComplementToNegaBinary { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_TCNB_4
            }
            Self::TwosComplementToNegaBinary { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_TCNB_8
            }
            Self::DebiasedExponentFractionSign {
                size: FloatSize::S4,
            } => lc_framework_sys::LC_CPUcomponents_DBEFS_4,
            Self::DebiasedExponentFractionSign {
                size: FloatSize::S8,
            } => lc_framework_sys::LC_CPUcomponents_DBEFS_8,
            Self::DebiasedExponentSignFraction {
                size: FloatSize::S4,
            } => lc_framework_sys::LC_CPUcomponents_DBESF_4,
            Self::DebiasedExponentSignFraction {
                size: FloatSize::S8,
            } => lc_framework_sys::LC_CPUcomponents_DBESF_8,
            // shuffle
            Self::BitShuffle { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_BIT_1,
            Self::BitShuffle { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_BIT_2,
            Self::BitShuffle { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_BIT_4,
            Self::BitShuffle { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_BIT_8,
            Self::Tuple {
                size: TupleSize::S1x2,
            } => lc_framework_sys::LC_CPUcomponents_TUPL2_1,
            Self::Tuple {
                size: TupleSize::S1x3,
            } => lc_framework_sys::LC_CPUcomponents_TUPL3_1,
            Self::Tuple {
                size: TupleSize::S1x4,
            } => lc_framework_sys::LC_CPUcomponents_TUPL4_1,
            Self::Tuple {
                size: TupleSize::S1x6,
            } => lc_framework_sys::LC_CPUcomponents_TUPL6_1,
            Self::Tuple {
                size: TupleSize::S1x8,
            } => lc_framework_sys::LC_CPUcomponents_TUPL8_1,
            Self::Tuple {
                size: TupleSize::S1x12,
            } => lc_framework_sys::LC_CPUcomponents_TUPL12_1,
            Self::Tuple {
                size: TupleSize::S2x2,
            } => lc_framework_sys::LC_CPUcomponents_TUPL2_2,
            Self::Tuple {
                size: TupleSize::S2x3,
            } => lc_framework_sys::LC_CPUcomponents_TUPL3_2,
            Self::Tuple {
                size: TupleSize::S2x4,
            } => lc_framework_sys::LC_CPUcomponents_TUPL4_2,
            Self::Tuple {
                size: TupleSize::S2x6,
            } => lc_framework_sys::LC_CPUcomponents_TUPL6_2,
            Self::Tuple {
                size: TupleSize::S4x2,
            } => lc_framework_sys::LC_CPUcomponents_TUPL2_4,
            Self::Tuple {
                size: TupleSize::S4x6,
            } => lc_framework_sys::LC_CPUcomponents_TUPL6_4,
            Self::Tuple {
                size: TupleSize::S8x3,
            } => lc_framework_sys::LC_CPUcomponents_TUPL3_8,
            Self::Tuple {
                size: TupleSize::S8x6,
            } => lc_framework_sys::LC_CPUcomponents_TUPL6_8,
            // predictors
            Self::Delta { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_DIFF_1,
            Self::Delta { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_DIFF_2,
            Self::Delta { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_DIFF_4,
            Self::Delta { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_DIFF_8,
            Self::DeltaAsSignMagnitude { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFMS_1
            }
            Self::DeltaAsSignMagnitude { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFMS_2
            }
            Self::DeltaAsSignMagnitude { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFMS_4
            }
            Self::DeltaAsSignMagnitude { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFMS_8
            }
            Self::DeltaAsNegaBinary { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFNB_1
            }
            Self::DeltaAsNegaBinary { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFNB_2
            }
            Self::DeltaAsNegaBinary { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFNB_4
            }
            Self::DeltaAsNegaBinary { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_DIFFNB_8
            }
            // reducers
            Self::Clog { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_CLOG_1,
            Self::Clog { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_CLOG_2,
            Self::Clog { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_CLOG_4,
            Self::Clog { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_CLOG_8,
            Self::HClog { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_HCLOG_1,
            Self::HClog { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_HCLOG_2,
            Self::HClog { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_HCLOG_4,
            Self::HClog { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_HCLOG_8,
            Self::Rare { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_RARE_1,
            Self::Rare { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_RARE_2,
            Self::Rare { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_RARE_4,
            Self::Rare { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_RARE_8,
            Self::Raze { size: ElemSize::S1 } => lc_framework_sys::LC_CPUcomponents_RAZE_1,
            Self::Raze { size: ElemSize::S2 } => lc_framework_sys::LC_CPUcomponents_RAZE_2,
            Self::Raze { size: ElemSize::S4 } => lc_framework_sys::LC_CPUcomponents_RAZE_4,
            Self::Raze { size: ElemSize::S8 } => lc_framework_sys::LC_CPUcomponents_RAZE_8,
            Self::RunLengthEncoding { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_RLE_1
            }
            Self::RunLengthEncoding { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_RLE_2
            }
            Self::RunLengthEncoding { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_RLE_4
            }
            Self::RunLengthEncoding { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_RLE_8
            }
            Self::RepetitionRunBitmapEncoding { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_RRE_1
            }
            Self::RepetitionRunBitmapEncoding { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_RRE_2
            }
            Self::RepetitionRunBitmapEncoding { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_RRE_4
            }
            Self::RepetitionRunBitmapEncoding { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_RRE_8
            }
            Self::ZeroRunBitmapEncoding { size: ElemSize::S1 } => {
                lc_framework_sys::LC_CPUcomponents_RZE_1
            }
            Self::ZeroRunBitmapEncoding { size: ElemSize::S2 } => {
                lc_framework_sys::LC_CPUcomponents_RZE_2
            }
            Self::ZeroRunBitmapEncoding { size: ElemSize::S4 } => {
                lc_framework_sys::LC_CPUcomponents_RZE_4
            }
            Self::ZeroRunBitmapEncoding { size: ElemSize::S8 } => {
                lc_framework_sys::LC_CPUcomponents_RZE_8
            }
        }
    }
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC component element size, in bytes
pub enum ElemSize {
    S1,
    S2,
    S4,
    S8,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC component float element size, in bytes
pub enum FloatSize {
    S4,
    S8,
}

#[expect(missing_docs)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// LC tuple component element size, in bytes x tuple length
pub enum TupleSize {
    S1x2,
    S1x3,
    S1x4,
    S1x6,
    S1x8,
    S1x12,
    S2x2,
    S2x3,
    S2x4,
    S2x6,
    S4x2,
    S4x6,
    S8x3,
    S8x6,
}

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

    #[test]
    fn bit4_rle4() {
        let preprocessors = &[];
        let components = &[
            Component::BitShuffle { size: ElemSize::S4 },
            Component::RunLengthEncoding { size: ElemSize::S4 },
        ];

        let data = b"abcd";

        let compressed = compress(preprocessors, components, data).unwrap();
        let decompressed = decompress(preprocessors, components, &compressed).unwrap();

        assert_eq!(decompressed, data);
    }

    #[test]
    fn abs_error() {
        let data = (0..100_u16)
            .map(|x| f32::from(x) / 100.0)
            .map(|x| std::f32::consts::PI * x)
            .map(f32::cos)
            .collect::<Vec<_>>();
        #[expect(unsafe_code)]
        // SAFETY:
        // - read-only access to the underlying bytes
        // - f32 is a plain-old data type
        let data_bytes = unsafe {
            std::slice::from_raw_parts(data.as_ptr().cast(), std::mem::size_of_val(data.as_slice()))
        };

        let error_bound = 0.1;

        let preprocessors = &[Preprocessor::QuantizeErrorBound {
            dtype: QuantizeDType::F32,
            kind: ErrorKind::Abs,
            error_bound,
            threshold: None,
            decorrelation: Decorrelation::Zero,
        }];
        let components = &[
            Component::BitShuffle { size: ElemSize::S4 },
            Component::RunLengthEncoding { size: ElemSize::S4 },
        ];

        let compressed = compress(preprocessors, components, data_bytes).unwrap();

        for i in 0..std::mem::size_of::<c_longlong>() {
            let mut compressed_unaligned = Vec::with_capacity(compressed.len() + i);
            compressed_unaligned.extend(std::iter::repeat_n(b'\0', i));
            compressed_unaligned.extend_from_slice(&compressed);

            let decompressed_bytes = decompress(
                preprocessors,
                components,
                compressed_unaligned.get(i..).unwrap(),
            )
            .unwrap();
            assert_eq!(decompressed_bytes.len(), data_bytes.len());

            #[expect(unsafe_code)]
            // SAFETY: initialise aligned f32s with unaligned bytes
            let decompressed = unsafe {
                let mut decompressed = Vec::<f32>::with_capacity(data.len());
                std::ptr::copy_nonoverlapping(
                    decompressed_bytes.as_ptr(),
                    decompressed.as_mut_ptr().cast(),
                    data_bytes.len(),
                );
                decompressed.set_len(data.len());
                decompressed
            };

            for (o, d) in data.iter().copied().zip(decompressed) {
                assert!(f64::from((o - d).abs()) <= error_bound);
            }
        }
    }
}