audioadapter-sample 2.0.0

A library for making it easier to work with audio data
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
#![allow(non_camel_case_types)]

use num_traits::{Float, PrimInt};

#[cfg(feature = "audio")]
use audio_core::Sample;

// ------ 16-bit integer formats ------

/// 16 bit signed integer, little endian. Stored as 2 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I16_LE([u8; 2]);

/// 16 bit signed integer, big endian. Stored as 2 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I16_BE([u8; 2]);

/// 16 bit unsigned integer, little endian. Stored as 2 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U16_LE([u8; 2]);

/// 16 bit unsigned integer, big endian. Stored as 2 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U16_BE([u8; 2]);

// ----- 24-bit formats -----

/// 24 bit signed integer, little endian. Stored as 3 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I24_LE([u8; 3]);

/// 24 bit signed integer, little endian. Stored as 4 bytes left justified.
/// The 24 data bits are stored in the three most significant bytes,
/// while the least significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct I24_4LJ_LE([u8; 4]);

/// 24 bit signed integer, little endian. Stored as 4 bytes right justified.
/// The 24 data bits are stored in the three least significant bytes,
/// while the most significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct I24_4RJ_LE([u8; 4]);

/// 24 bit signed integer, big endian. Stored as 3 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I24_BE([u8; 3]);

/// 24 bit signed integer, big endian. Stored as 4 bytes left justified.
/// The 24 data bits are stored in the three most significant bytes,
/// while the least significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct I24_4LJ_BE([u8; 4]);

/// 24 bit signed integer, big endian. Stored as 4 bytes right justified.
/// The 24 data bits are stored in the three least significant bytes,
/// while the most significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct I24_4RJ_BE([u8; 4]);

/// 24 bit unsigned integer, little endian. Stored as 3 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U24_LE([u8; 3]);

/// 24 bit unsigned integer, little endian. Stored as 4 bytes left justified.
/// The 24 data bits are stored in the three most significant bytes,
/// while the least significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct U24_4LJ_LE([u8; 4]);

/// 24 bit unsigned integer, little endian. Stored as 4 bytes right justified.
/// The 24 data bits are stored in the three least significant bytes,
/// while the most significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct U24_4RJ_LE([u8; 4]);

/// 24 bit unsigned integer, big endian. Stored as 3 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U24_BE([u8; 3]);

/// 24 bit unsigned integer, big endian. Stored as 4 bytes left justified.
/// The 24 data bits are stored in the three most significant bytes,
/// while the least significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct U24_4LJ_BE([u8; 4]);

/// 24 bit unsigned integer, big endian. Stored as 4 bytes right justified.
/// The 24 data bits are stored in the three least significant bytes,
/// while the most significant byte is unused padding.
#[derive(Debug, Clone, Copy)]
pub struct U24_4RJ_BE([u8; 4]);

// ------ 32-bit integer formats ------

/// 32 bit signed integer, little endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I32_LE([u8; 4]);

/// 32 bit signed integer, big endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I32_BE([u8; 4]);

/// 32 bit unsigned integer, little endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U32_LE([u8; 4]);

/// 32 bit unsigned integer, big endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U32_BE([u8; 4]);

// ----- 64-bit integer formats ------

/// 64 bit signed integer, little endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I64_LE([u8; 8]);

/// 64 bit signed integer, big endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct I64_BE([u8; 8]);

/// 64 bit unsigned integer, little endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U64_LE([u8; 8]);

/// 64 bit unsigned integer, big endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct U64_BE([u8; 8]);

// ----- floating point formats -----

/// 32 bit floating point, little endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct F32_LE([u8; 4]);

/// 32 bit floating point, big endian. Stored as 4 bytes.
#[derive(Debug, Clone, Copy)]
pub struct F32_BE([u8; 4]);

/// 64 bit floating point, little endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct F64_LE([u8; 8]);

/// 64 bit floating point, big endian. Stored as 8 bytes.
#[derive(Debug, Clone, Copy)]
pub struct F64_BE([u8; 8]);

/// Convert a float to an integer, clamp at the min and max limits of the integer.
fn to_clamped_int<T: Float, U: PrimInt>(value: T, converted: Option<U>) -> ConversionResult<U> {
    if let Some(val) = converted {
        return ConversionResult {
            clipped: false,
            value: val,
        };
    }
    if value.is_nan() {
        return ConversionResult {
            clipped: true,
            value: U::zero(),
        };
    }
    if value > T::zero() {
        return ConversionResult {
            clipped: true,
            value: U::max_value(),
        };
    }
    ConversionResult {
        clipped: true,
        value: U::min_value(),
    }
}

/// A conversion result, containing the resulting value as `value`
/// and a boolean `clipped` indicating if the value was clipped during conversion.
pub struct ConversionResult<T> {
    pub clipped: bool,
    pub value: T,
}

/// A trait for converting a given sample type to and from floating point values.
/// The floating point values use the range -1.0 to +1.0.
/// When converting to/from signed integers, the range does not include +1.0.
/// For example, an 8-bit signed integer supports the range -128 to +127.
/// When these values are converted to float, 0 becomes 0.0,
/// -128 becomes -1.0, and 127 becomes 127/128 ≈ 0.992.
/// Unsigned integers are also converted to the same -1.0 to +1.0 range.
/// For an 8-but unsigned integer, 128 is the center point and becomes 0.0.
/// The value 0 becomes -1.0, and 255 becomes 127/128 ≈ 0.992.
pub trait RawSample
where
    Self: Sized,
{
    /// Convert the sample value to a float in the range -1.0 .. +1.0.
    fn to_scaled_float<T: Float>(&self) -> T;

    /// Convert a float in the range -1.0 .. +1.0 to a sample value.
    /// Values outside the allowed range are clipped to the nearest limit.
    fn from_scaled_float<T: Float>(value: T) -> ConversionResult<Self>;
}

/// A trait for converting samples stored as raw bytes into a numerical type.
/// Each implementation defines the associated type `NumericType`,
/// which is the nearest matching numeric type for the original format.
/// If a direct match exists, this is used.
/// For example signed 16 bit integer samples use [i16].
/// For formats that don't have a direct match,
/// the next larger numeric type is used.
/// For example for 24 bit signed integers,
/// this means [i32].
/// The values are scaled to use the full range of the `NumericType`
/// associated type.
pub trait BytesSample {
    /// The closest matching numeric type.
    type NumericType: Copy;

    /// The number of bytes making up each sample value.
    const BYTES_PER_SAMPLE: usize;

    /// Create a new ByteSample from a slice of raw bytes.
    /// The slice length must be at least the number of bytes
    /// for a sample value.
    fn from_slice(bytes: &[u8]) -> Self;

    /// Return the raw bytes as a slice.
    fn as_slice(&self) -> &[u8];

    /// Return the raw bytes as a mutable slice.
    fn as_mut_slice(&mut self) -> &mut [u8];

    /// Convert the raw bytes to a numerical value.
    fn to_number(&self) -> Self::NumericType;

    /// Convert a numerical value to raw bytes.
    fn from_number(value: Self::NumericType) -> Self;
}

macro_rules! rawsample_for_int {
    ($type:ident, $to:ident) => {
        impl RawSample for $type {
            fn to_scaled_float<T: Float>(&self) -> T {
                T::from(*self).unwrap() / (T::from($type::MAX).unwrap() + T::one())
            }

            fn from_scaled_float<T: Float>(value: T) -> ConversionResult<Self> {
                let scaled = value * (T::from($type::MAX).unwrap() + T::one());
                let converted = scaled.$to();
                to_clamped_int(scaled, converted)
            }
        }
    };
}

rawsample_for_int!(i8, to_i8);
rawsample_for_int!(i16, to_i16);
rawsample_for_int!(i32, to_i32);
rawsample_for_int!(i64, to_i64);

macro_rules! rawsample_for_uint {
    ($type:ident, $to:ident) => {
        impl RawSample for $type {
            fn to_scaled_float<T: Float>(&self) -> T {
                let max_ampl = (T::from($type::MAX).unwrap() + T::one()) / T::from(2).unwrap();
                (T::from(*self).unwrap() - max_ampl) / max_ampl
            }

            fn from_scaled_float<T: Float>(value: T) -> ConversionResult<Self> {
                let max_ampl = (T::from($type::MAX).unwrap() + T::one()) / T::from(2).unwrap();
                let scaled = value * max_ampl + max_ampl;
                let converted = scaled.$to();
                to_clamped_int(scaled, converted)
            }
        }
    };
}

rawsample_for_uint!(u8, to_u8);
rawsample_for_uint!(u16, to_u16);
rawsample_for_uint!(u32, to_u32);
rawsample_for_uint!(u64, to_u64);

macro_rules! rawsample_for_float {
    ($type:ident, $to:ident) => {
        impl RawSample for $type {
            fn to_scaled_float<T: Float>(&self) -> T {
                T::from(*self).unwrap_or(T::zero())
            }

            fn from_scaled_float<T: Float>(value: T) -> ConversionResult<Self> {
                // TODO clip here
                ConversionResult {
                    clipped: false,
                    value: value.$to().unwrap_or(0.0),
                }
            }
        }
    };
}

rawsample_for_float!(f32, to_f32);
rawsample_for_float!(f64, to_f64);

// 24 bit formats, needs more work than others
// because they don't map directly to a normal numerical type,

/// 24 bit signed integer, little endian, stored as 4 bytes right justified.
/// The data is in the lower 3 bytes and the most significant byte is padding.
impl BytesSample for I24_4RJ_LE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[0], self.0[1], self.0[2]];
        i32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([bytes[1], bytes[2], bytes[3], 0])
    }
}

/// 24 bit signed integer, little endian, stored as 4 bytes left justified.
/// The data is in the upper 3 bytes and the least significant byte is padding.
impl BytesSample for I24_4LJ_LE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[1], self.0[2], self.0[3]];
        i32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([0, bytes[1], bytes[2], bytes[3]])
    }
}

/// 24 bit signed integer, little endian, stored as 3 bytes without padding.
impl BytesSample for I24_LE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..3].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[0], self.0[1], self.0[2]];
        i32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([bytes[1], bytes[2], bytes[3]])
    }
}

/// 24 bit signed integer, big endian, stored as 4 bytes right justified.
/// The data is in the lower 3 bytes and the most significant byte is padding.
impl BytesSample for I24_4RJ_BE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[1], self.0[2], self.0[3], 0];
        i32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([0, bytes[0], bytes[1], bytes[2]])
    }
}

/// 24 bit signed integer, big endian, stored as 4 bytes left justified.
/// The data is in the upper 3 bytes and the least significant byte is padding.
impl BytesSample for I24_4LJ_BE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[0], self.0[1], self.0[2], 0];
        i32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([bytes[0], bytes[1], bytes[2], 0])
    }
}

/// 24 bit signed integer, big endian, stored as 3 bytes without padding.
impl BytesSample for I24_BE {
    type NumericType = i32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..3].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[0], self.0[1], self.0[2], 0];
        i32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([bytes[0], bytes[1], bytes[2]])
    }
}

/// 24 bit unsigned integer, little endian, stored as 4 bytes right justified.
/// The data is in the lower 3 bytes and the most significant byte is padding.
impl BytesSample for U24_4RJ_LE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[0], self.0[1], self.0[2]];
        u32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([bytes[1], bytes[2], bytes[3], 0])
    }
}

/// 24 bit unsigned integer, little endian, stored as 4 bytes left justified.
/// The data is in the upper 3 bytes and the least significant byte is padding.
impl BytesSample for U24_4LJ_LE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[1], self.0[2], self.0[3]];
        u32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([0, bytes[1], bytes[2], bytes[3]])
    }
}

/// 24 bit unsigned integer, little endian, stored as 3 bytes without padding.
impl BytesSample for U24_LE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..3].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [0, self.0[0], self.0[1], self.0[2]];
        u32::from_le_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_le_bytes();
        Self([bytes[1], bytes[2], bytes[3]])
    }
}

/// 24 bit unsigned integer, big endian, stored as 4 bytes right justified.
/// The data is in the lower 3 bytes and the most significant byte is padding.
impl BytesSample for U24_4RJ_BE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[1], self.0[2], self.0[3], 0];
        u32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([0, bytes[0], bytes[1], bytes[2]])
    }
}

/// 24 bit unsigned integer, big endian, stored as 4 bytes left justified.
/// The data is in the upper 3 bytes and the least significant byte is padding.
impl BytesSample for U24_4LJ_BE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..4].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[0], self.0[1], self.0[2], 0];
        u32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([bytes[0], bytes[1], bytes[2], 0])
    }
}

/// 24 bit unsigned integer, big endian, stored as 3 bytes without padding.
impl BytesSample for U24_BE {
    type NumericType = u32;
    const BYTES_PER_SAMPLE: usize = core::mem::size_of::<Self>();

    fn from_slice(bytes: &[u8]) -> Self {
        Self(bytes[0..3].try_into().unwrap())
    }

    fn as_slice(&self) -> &[u8] {
        &self.0
    }

    fn as_mut_slice(&mut self) -> &mut [u8] {
        &mut self.0
    }

    fn to_number(&self) -> Self::NumericType {
        let padded = [self.0[0], self.0[1], self.0[2], 0];
        u32::from_be_bytes(padded)
    }

    fn from_number(value: Self::NumericType) -> Self {
        let bytes = value.to_be_bytes();
        Self([bytes[0], bytes[1], bytes[2]])
    }
}

macro_rules! bytessample_for_newtype {
    ($type:ident, $newtype:ident, $from:ident, $to:ident) => {
        impl BytesSample for $newtype {
            type NumericType = $type;
            const BYTES_PER_SAMPLE: usize = core::mem::size_of::<$type>();

            fn from_slice(bytes: &[u8]) -> Self {
                Self(bytes.try_into().unwrap())
            }

            fn as_slice(&self) -> &[u8] {
                &self.0
            }

            fn as_mut_slice(&mut self) -> &mut [u8] {
                &mut self.0
            }

            fn to_number(&self) -> Self::NumericType {
                $type::$from(self.0)
            }

            fn from_number(value: Self::NumericType) -> Self {
                Self(value.$to())
            }
        }
    };
}

bytessample_for_newtype!(i64, I64_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(u64, U64_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(i64, I64_BE, from_be_bytes, to_be_bytes);
bytessample_for_newtype!(u64, U64_BE, from_be_bytes, to_be_bytes);

bytessample_for_newtype!(i16, I16_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(u16, U16_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(i16, I16_BE, from_be_bytes, to_be_bytes);
bytessample_for_newtype!(u16, U16_BE, from_be_bytes, to_be_bytes);

bytessample_for_newtype!(i32, I32_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(u32, U32_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(i32, I32_BE, from_be_bytes, to_be_bytes);
bytessample_for_newtype!(u32, U32_BE, from_be_bytes, to_be_bytes);

bytessample_for_newtype!(f32, F32_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(f32, F32_BE, from_be_bytes, to_be_bytes);
bytessample_for_newtype!(f64, F64_LE, from_le_bytes, to_le_bytes);
bytessample_for_newtype!(f64, F64_BE, from_be_bytes, to_be_bytes);

impl<V> RawSample for V
where
    V: BytesSample,
    <V as BytesSample>::NumericType: RawSample,
{
    fn to_scaled_float<T: Float>(&self) -> T {
        let value = self.to_number();
        value.to_scaled_float()
    }

    fn from_scaled_float<T: Float>(value: T) -> ConversionResult<Self> {
        let value = <V as BytesSample>::NumericType::from_scaled_float(value);
        ConversionResult {
            clipped: value.clipped,
            value: V::from_number(value.value),
        }
    }
}

// Implement Sample for the audioadapter types
#[cfg(feature = "audio")]
macro_rules! impl_sample_for_newtype {
    ($newtype:ident, $bytes:expr) => {
        unsafe impl Sample for $newtype {
            const ZERO: $newtype = $newtype([0; $bytes]);
        }
    };
}

#[cfg(feature = "audio")]
impl_sample_for_newtype!(I16_LE, 2);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U16_LE, 2);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I16_BE, 2);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U16_BE, 2);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_LE, 3);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_4LJ_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_4RJ_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_LE, 3);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_4LJ_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_4RJ_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_BE, 3);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_4LJ_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I24_4RJ_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_BE, 3);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_4LJ_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U24_4RJ_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I32_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U32_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I32_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U32_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I64_LE, 8);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U64_LE, 8);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(I64_BE, 8);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(U64_BE, 8);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(F32_LE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(F32_BE, 4);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(F64_LE, 8);
#[cfg(feature = "audio")]
impl_sample_for_newtype!(F64_BE, 8);

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

    macro_rules! assert_conversion_eq {
        ($result:expr, $value:expr, $clipped:expr, $desc:expr) => {
            assert_eq!($result.value, $value, $desc);
            assert_eq!($result.clipped, $clipped, $desc);
        };
    }

    macro_rules! test_to_signed_int {
        ($fname:ident, $float:ty, $int:ident, $bits:expr) => {
            #[test]
            fn $fname() {
                let val: $float = 0.25;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    1 << ($bits - 3),
                    false,
                    "check +0.25"
                );
                let val: $float = -0.25;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    -1 << ($bits - 3),
                    false,
                    "check -0.25"
                );
                let val: $float = 1.1;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    $int::MAX,
                    true,
                    "clipped positive"
                );
                let val: $float = -1.1;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    $int::MIN,
                    true,
                    "clipped negative"
                );
            }
        };
    }

    macro_rules! test_to_unsigned_int {
        ($fname:ident, $float:ty, $int:ident, $bits:expr) => {
            #[test]
            fn $fname() {
                let val: $float = -0.5;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    1 << ($bits - 2),
                    false,
                    "check -0.5"
                );
                let val: $float = 0.5;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    $int::MAX - (1 << ($bits - 2)) + 1,
                    false,
                    "check 0.5"
                );
                let val: $float = 1.1;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    $int::MAX,
                    true,
                    "clipped positive"
                );
                let val: $float = -1.1;
                assert_conversion_eq!(
                    $int::from_scaled_float(val),
                    $int::MIN,
                    true,
                    "clipped negative"
                );
            }
        };
    }

    test_to_signed_int!(convert_f32_to_i8, f32, i8, 8);
    test_to_signed_int!(convert_642_to_i8, f64, i8, 8);
    test_to_signed_int!(convert_f32_to_i16, f32, i16, 16);
    test_to_signed_int!(convert_f64_to_i16, f64, i16, 16);
    test_to_signed_int!(convert_f32_to_i32, f32, i32, 32);
    test_to_signed_int!(convert_f64_to_i32, f64, i32, 32);
    test_to_signed_int!(convert_f32_to_i64, f32, i64, 64);
    test_to_signed_int!(convert_f64_to_i64, f64, i64, 64);

    test_to_unsigned_int!(convert_f32_to_u8, f32, u8, 8);
    test_to_unsigned_int!(convert_f64_to_u8, f64, u8, 8);
    test_to_unsigned_int!(convert_f32_to_u16, f32, u16, 16);
    test_to_unsigned_int!(convert_f64_to_u16, f64, u16, 16);
    test_to_unsigned_int!(convert_f32_to_u32, f32, u32, 32);
    test_to_unsigned_int!(convert_f64_to_u32, f64, u32, 32);
    test_to_unsigned_int!(convert_f32_to_u64, f32, u64, 64);
    test_to_unsigned_int!(convert_f64_to_u64, f64, u64, 64);

    macro_rules! test_from_signed_int {
        ($fname:ident, $float:ty, $int:ident, $bits:expr) => {
            #[test]
            fn $fname() {
                let val: $int = -1 << ($bits - 2);
                assert_eq!(val.to_scaled_float::<$float>(), -0.5, "check -0.5");
                let val: $int = 1 << ($bits - 2);
                assert_eq!(val.to_scaled_float::<$float>(), 0.5, "check 0.5");
                let val: $int = $int::MIN;
                assert_eq!(val.to_scaled_float::<$float>(), -1.0, "negative limit");
            }
        };
    }

    macro_rules! test_from_unsigned_int {
        ($fname:ident, $float:ty, $int:ident, $bits:expr) => {
            #[test]
            fn $fname() {
                let val: $int = 1 << ($bits - 2);
                assert_eq!(val.to_scaled_float::<$float>(), -0.5, "check -0.5");
                let val: $int = $int::MAX - (1 << ($bits - 2)) + 1;
                assert_eq!(val.to_scaled_float::<$float>(), 0.5, "check 0.5");
                let val: $int = 0;
                assert_eq!(val.to_scaled_float::<$float>(), -1.0, "negative limit");
            }
        };
    }

    test_from_signed_int!(convert_f32_from_i8, f32, i8, 8);
    test_from_signed_int!(convert_f64_from_i8, f64, i8, 8);
    test_from_signed_int!(convert_f32_from_i16, f32, i16, 16);
    test_from_signed_int!(convert_f64_from_i16, f64, i16, 16);
    test_from_signed_int!(convert_f32_from_i32, f32, i32, 32);
    test_from_signed_int!(convert_f64_from_i32, f64, i32, 32);
    test_from_signed_int!(convert_f32_from_i64, f32, i64, 64);
    test_from_signed_int!(convert_f64_from_i64, f64, i64, 64);

    test_from_unsigned_int!(convert_f32_from_u8, f32, u8, 8);
    test_from_unsigned_int!(convert_f64_from_u8, f64, u8, 8);
    test_from_unsigned_int!(convert_f32_from_u16, f32, u16, 16);
    test_from_unsigned_int!(convert_f64_from_u16, f64, u16, 16);
    test_from_unsigned_int!(convert_f32_from_u32, f32, u32, 32);
    test_from_unsigned_int!(convert_f64_from_u32, f64, u32, 32);
    test_from_unsigned_int!(convert_f32_from_u64, f32, u64, 64);
    test_from_unsigned_int!(convert_f64_from_u64, f64, u64, 64);

    #[test]
    fn test_to_clamped_int() {
        let converted = to_clamped_int::<f32, i32>(12345.0, Some(12345));
        assert_conversion_eq!(converted, 12345, false, "in range f32 i32");

        let converted = to_clamped_int::<f32, i32>(1.0e10, None);
        assert_conversion_eq!(converted, i32::MAX, true, "above range f32 i32");

        let converted = to_clamped_int::<f32, i32>(-1.0e10, None);
        assert_conversion_eq!(converted, i32::MIN, true, "below range f32 i32");

        let converted = to_clamped_int::<f64, i32>(12345.0, Some(12345));
        assert_conversion_eq!(converted, 12345, false, "in range f64 i32");

        let converted = to_clamped_int::<f64, i32>(1.0e10, None);
        assert_conversion_eq!(converted, i32::MAX, true, "above range f64 i32");

        let converted = to_clamped_int::<f64, i32>(-1.0e10, None);
        assert_conversion_eq!(converted, i32::MIN, true, "below range f64 i32");
    }

    #[test]
    fn test_to_clamped_uint() {
        let converted = to_clamped_int::<f32, u32>(12345.0, Some(12345));
        assert_conversion_eq!(converted, 12345, false, "in range f32 u32");

        let converted = to_clamped_int::<f32, u32>(1.0e10, None);
        assert_conversion_eq!(converted, u32::MAX, true, "above range f32 u32");

        let converted = to_clamped_int::<f32, u32>(-1.0, None);
        assert_conversion_eq!(converted, u32::MIN, true, "below range f32 u32");

        let converted = to_clamped_int::<f64, u32>(12345.0, Some(12345));
        assert_conversion_eq!(converted, 12345, false, "in range f64 u32");

        let converted = to_clamped_int::<f64, u32>(1.0e10, None);
        assert_conversion_eq!(converted, u32::MAX, true, "above range f64 u32");

        let converted = to_clamped_int::<f64, u32>(-1.0, None);
        assert_conversion_eq!(converted, u32::MIN, true, "below range f64 u32");
    }

    macro_rules! test_simple_int_bytes {
        ($fname:ident, $number:ty, $wrapper:ident, $to_bytes_fn:ident) => {
            #[test]
            #[allow(non_snake_case)]
            fn $fname() {
                let number: $number = <$number>::MAX / 5 * 4;
                let wrapped = $wrapper(number.$to_bytes_fn());
                assert_eq!(number, wrapped.to_number());
            }
        };
    }

    macro_rules! test_float_bytes {
        ($fname:ident, $number:ty, $wrapper:ident, $to_bytes_fn:ident) => {
            #[test]
            #[allow(non_snake_case)]
            fn $fname() {
                let number: $number = 12345.0;
                let wrapped = $wrapper(number.$to_bytes_fn());
                assert_eq!(number, wrapped.to_number());
            }
        };
    }

    test_simple_int_bytes!(convert_i16_from_I16_LE, i16, I16_LE, to_le_bytes);
    test_simple_int_bytes!(convert_i16_from_I16_BE, i16, I16_BE, to_be_bytes);
    test_simple_int_bytes!(convert_i32_from_I32_LE, i32, I32_LE, to_le_bytes);
    test_simple_int_bytes!(convert_i32_from_I32_BE, i32, I32_BE, to_be_bytes);
    test_simple_int_bytes!(convert_i64_from_I64_LE, i64, I64_LE, to_le_bytes);
    test_simple_int_bytes!(convert_i64_from_I64_BE, i64, I64_BE, to_be_bytes);

    test_simple_int_bytes!(convert_u16_from_U16_LE, u16, U16_LE, to_le_bytes);
    test_simple_int_bytes!(convert_u16_from_U16_BE, u16, U16_BE, to_be_bytes);
    test_simple_int_bytes!(convert_u32_from_U32_LE, u32, U32_LE, to_le_bytes);
    test_simple_int_bytes!(convert_u32_from_U32_BE, u32, U32_BE, to_be_bytes);
    test_simple_int_bytes!(convert_u64_from_U64_LE, u64, U64_LE, to_le_bytes);
    test_simple_int_bytes!(convert_u64_from_U64_BE, u64, U64_BE, to_be_bytes);

    test_float_bytes!(convert_f32_fom_F32_LE, f32, F32_LE, to_le_bytes);
    test_float_bytes!(convert_f32_fom_F32_BE, f32, F32_BE, to_be_bytes);
    test_float_bytes!(convert_f64_fom_F64_LE, f64, F64_LE, to_le_bytes);
    test_float_bytes!(convert_f64_fom_F64_BE, f64, F64_BE, to_be_bytes);

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_LE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Drop the LSB!
        let bytes = [allbytes[1], allbytes[2], allbytes[3]];

        let wrapped = I24_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_BE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Drop the LSB!
        let bytes = [allbytes[0], allbytes[1], allbytes[2]];

        let wrapped = I24_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_4RJ_LE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Drop the LSB and insert padding at MSB!
        let bytes = [allbytes[1], allbytes[2], allbytes[3], 0];

        let wrapped = I24_4RJ_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_4RJ_BE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Drop the LSB and insert padding at MSB!
        let bytes = [0, allbytes[0], allbytes[1], allbytes[2]];

        let wrapped = I24_4RJ_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_4LJ_LE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Put a zero at LSB and keep the rest unchanged.
        let bytes = [0, allbytes[1], allbytes[2], allbytes[3]];

        let wrapped = I24_4LJ_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_I24_4LJ_BE() {
        let number = i32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Put a zero at LSB and keep the rest unchanged.
        let bytes = [allbytes[0], allbytes[1], allbytes[2], 0];

        let wrapped = I24_4LJ_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_LE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Drop the LSB!
        let bytes = [allbytes[1], allbytes[2], allbytes[3]];

        let wrapped = U24_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_BE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Drop the LSB!
        let bytes = [allbytes[0], allbytes[1], allbytes[2]];

        let wrapped = U24_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_4RJ_LE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Drop the LSB and insert padding at MSB!
        let bytes = [allbytes[1], allbytes[2], allbytes[3], 0];

        let wrapped = U24_4RJ_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_4RJ_BE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Drop the LSB and insert padding at MSB!
        let bytes = [0, allbytes[0], allbytes[1], allbytes[2]];

        let wrapped = U24_4RJ_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_4LJ_LE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_le_bytes();
        // Little-endian stores the LSB at the smallest address.
        // Put a zero at LSB and keep the rest unchanged.
        let bytes = [0, allbytes[1], allbytes[2], allbytes[3]];

        let wrapped = U24_4LJ_LE(bytes);
        assert_eq!(number, wrapped.to_number());
    }

    #[test]
    #[allow(non_snake_case)]
    fn test_U24_4LJ_BE() {
        let number = u32::MAX / 5 * 4;

        // make sure LSB is zero
        let number = number >> 8;
        let number = number << 8;

        let allbytes = number.to_be_bytes();
        // Big-endian stores the LSB at the largest address.
        // Put a zero at LSB and keep the rest unchanged.
        let bytes = [allbytes[0], allbytes[1], allbytes[2], 0];

        let wrapped = U24_4LJ_BE(bytes);
        assert_eq!(number, wrapped.to_number());
    }
}