ot-tools-io 0.11.3

A library crate for reading/writing binary data files used by the Elektron Octatrack DPS-1.
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
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2026 Mike Robeson [dijksterhuis]
*/

//! All types and trait implementations related to [`SampleSettingsFile`]s.

use crate::generics::Slices;
use crate::markers::SlotMarkers;
use crate::projects::{SlotAttributes, DEFAULT_GAIN, DEFAULT_TEMPO};
use crate::settings::{LoopMode, SlotType, TimeStretchMode, TrigQuantizationMode};
use crate::slices::Slice;
use crate::traits::SwapBytes;
use crate::{
    HasChecksumField, HasFileVersionField, HasHeaderField, OctatrackFileIO, OtToolsIoError,
};
use ot_tools_io_derive::{AsMutDerive, AsRefDerive, IntegrityChecks};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;

#[cfg(test)]
mod test_utils {
    use super::{
        OtToolsIoError, SampleSettingsFile, SlotMarkers, SAMPLES_FILE_VERSION, SAMPLES_HEADER,
    };
    use crate::projects::DEFAULT_GAIN;
    pub(crate) fn create_mock_new_sample_settings(
        tempo: Option<u32>,
        gain: Option<u16>,
    ) -> Result<SampleSettingsFile, OtToolsIoError> {
        SampleSettingsFile::new(
            SlotMarkers::default(),
            gain,
            tempo,
            None,
            None,
            None,
            None,
            None,
        )
    }

    pub(crate) fn mock_0_slice_test_file() -> SampleSettingsFile {
        SampleSettingsFile {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: 1,
            tempo: 2281,
            trim_bar_len: 800,
            loop_bar_len: 800,
            stretch: 2,
            loop_mode: 0,
            gain: DEFAULT_GAIN as u16,
            quantization: 255,
            trim_start: 0,
            trim_end: 890839,
            loop_start: 0,
            slices: SlotMarkers::default().slices,
            slices_len: 0,
            checksum: 998,
        }
    }
}

/// Errors specific to [`SampleSettingsFile`]s.
///
/// Most of the time this will be casted into an [`OtToolsIoError`] instance in a return type.
#[derive(Debug, Error)]
pub enum SampleSettingsError {
    #[error("invalid gain, must be u16 in range 0 <= x <= 96: {value}")]
    GainOutOfBounds { value: u32 },
    #[error("invalid tempo value, must be u32 in range 720 <= x <= 7200: {value}")]
    TempoOutOfBounds { value: u32 },
    #[error("invalid slot_id value, must be 1 to 128 for Static slot type or 136 for Flex slot type: id: {id} type: {slot_type}")]
    SlotIdOutOfBounds { id: u8, slot_type: SlotType },
    #[error("invalid checksum value for sample settings file: {checksum}")]
    InvalidChecksum { checksum: u16 },
    #[error("invalid file version value for sample settings file: {version}")]
    InvalidFileVersion { version: u8 },
}

// in `hexdump -C` format:
// ```
// FORM....DPS1SMPA
// ......
// ```
/// Standard header bytes in a sample settings file
pub const SAMPLES_HEADER: [u8; 21] = [
    0x46, 0x4F, 0x52, 0x4D, 0x00, 0x00, 0x00, 0x00, 0x44, 0x50, 0x53, 0x31, 0x53, 0x4D, 0x50, 0x41,
    0x00, 0x00, 0x00, 0x00, 0x00,
];

/// Current/supported datatype version for a sample settings file
pub const SAMPLES_FILE_VERSION: u8 = 2;

/// An Octatrack `.ot` file a.k.a. a sample settings file contains trim, slice and attribute
/// settings for a sample/slot.
/// Essentially the type is a combination of [`SlotAttributes`] and [`SlotMarkers`] data, excluding
/// the `slot_id`, `path` and `slot_type` fields from [`SlotAttributes`].
///
/// # The Type's Name
///
/// The Octatrack manual specifically refers to
/// > SAVE SAMPLE SETTINGS will save the trim, slice and attribute settings in a
/// > separate file and link it to the sample currently being edited.
/// >
/// > -- page 87.
///
/// So this is the settings file for a given sample.
///
/// # Missing [`Default`] trait
///
/// In practice, a [`SampleSettingsFile`] is usually paired with an audio file.
/// This library assumes we’re exclusively operating on Octatrack binary data files, that we have no
/// access to any audio sample files.
/// As such, there is no way to know what a "default" implementation of this type would like.
/// So there isn't one.
///
/// Instead of calling `default`, always create a new instance with [`SampleSettingsFile::new`].
///
/// # Converting to other data types
///
/// [`SampleSettingsFile`]s can be converted to/from [`SlotMarkers`] and/or [`SlotAttributes`] using
/// the information from the below table
///
/// | From | To | Via |
/// | ---- | ---- | ---- |
/// | [`SampleSettingsFile`] | [`SlotMarkers`] | [`SlotMarkers::from`] |
/// | [`SampleSettingsFile`] | [`SlotAttributes`] | [`SampleSettingsFile::to_slot_attr`] \* |
/// | `(SlotAttributes, SlotMarkers)` | [`SampleSettingsFile`] | [`SampleSettingsFile::from`] |
///
/// \* requires additional arguments
///
/// # Trim Bar Length and Loop Bar Length
///
/// These fields are not necessary to have a functional [`SampleSettingsFile`].
/// If both of these fields are set to zero, but the BPM/tempo field is populated,
/// then the Octatrack will load the sample using the BPM/tempo field.
///
/// To calculate an appropriate value for these two fields we would have to convert from number of
/// samples to number of bars.
/// This calculation requires the sample rate and length of the relevant audio sample file,
/// meaning this library would need access to such audio sample files.
///
/// This library assumes we're exclusively operating on Octatrack binary data files,
/// that we have no access to any audio files.
///
/// Therefore, these two fields are always set to zero when using any of the following methods
/// - [`SampleSettingsFile::new`]
/// - [`SampleSettingsFile::from`] \*
///
/// If you want to set these two values you have to do one of:
/// - Calculate the appropriate `tempo` value for your desired `trim_bar_len` or `loop_bar_len` and use that
///   when calling [`SampleSettingsFile::new`] or when creating a new struct from scratch
///   (leaving the `trim_bar_len` and `loop_bar_len` fields set to zero if creating a struct from scratch).
/// - Manually create the [`SampleSettingsFile`] from scratch and provide appropriate values for all
///   fields -- note that this means manually adding header etc. field values too.
///
/// Please note that the `trim_bar_len` and `loop_bar_len` fields are **NOT** set to zero during
/// deserialization.
/// A [`SampleSettingsFile`]s should be correctly represented when the file has been generated by
/// the Octatrack itself.
///
/// \* [`SampleSettingsFile::from`] will be able to convert it in the future,
/// but appropriate fields need to be added to the [`SlotAttributes`] type first.
///
/// # Little-endian systems
///
/// The bytes of this type are swapped during decoding on little-endian systems to ensure data is
/// written out correctly.
#[derive(
    Copy,
    Clone,
    Debug,
    Eq,
    Hash,
    Ord,
    PartialEq,
    PartialOrd,
    Serialize,
    Deserialize,
    AsMutDerive,
    AsRefDerive,
    IntegrityChecks,
)]
pub struct SampleSettingsFile {
    /// Header
    ///
    /// ## Validation
    ///
    /// Use the [`SampleSettingsFile::check_header`] method from the [`HasHeaderField`] trait.
    ///
    /// The [`SampleSettingsFile::validate`] method will call [`SampleSettingsFile::check_header`]
    /// to verify the current instance's header.
    pub header: [u8; 21],

    /// Datatype's version ID
    ///
    /// ## Validation
    ///
    /// Use the [`SampleSettingsFile::check_file_version`] method from the [`HasFileVersionField`] trait.
    ///
    /// The [`SampleSettingsFile::validate`] method will call [`SampleSettingsFile::check_file_version`]
    /// to verify the current instance's version.
    pub datatype_version: u8,

    /// Unknown data -- can sometimes be 1, usually 0.
    pub unknown: u8,

    /// Tempo determines the BPM of sample playback.
    /// In this field, the value is always the machine UI's BPM (human BPM) multiplied by 24.
    ///
    /// From page 86 of the Octatrack manual:
    /// > ORIGINAL TEMPO displays the calculated BPM of the sample.
    /// > If it is not correct, it can be changed using the LEVEL knob.
    /// > This setting will affect the sound of a timestretched sample.
    /// > For correct results it should be set to match the original BPM of the sample.
    /// > Altering this setting will alter the TRIM LEN (BARS) and LOOP LEN (BARS) settings.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether the field's current value is
    /// within appropriate bounds.
    ///
    /// Validating this field against the `trim_bar_len` and/or `loop_bar_len` fields is outside the scope
    /// of this library.
    pub tempo: u32,

    /// Number of bars for determining the BPM of sample playback.
    /// Should be an appropriate value which corresponds to the `tempo` field.
    ///
    /// From page 86 of the Octatrack manual:
    /// > TRIM LEN (BARS) shows the length of the sample in bars.
    /// > Altering this setting will alter the ORIGINAL TEMPO and LOOP LEN (BARS) settings.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method does not check this field for validity.
    ///
    /// Validating this field against the `trim_bar_len` and/or `loop_bar_len` fields is outside the scope
    /// of this library.
    pub trim_bar_len: u32,

    /// Number of bars for determining the BPM of sample playback.
    /// Should be an appropriate value which corresponds to the `tempo` field.
    ///
    /// From page 86 of the Octatrack manual:
    /// > LOOP LEN (BARS) displays the amount of bars the looped section of the sample consists of.
    /// > Altering this setting will alter the ORIGINAL TEMPO and TRIM LEN (BARS) settings.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method does not check this field for validity.
    ///
    /// Validating this field against the `trim_bar_len` and/or `loop_bar_len` fields is outside the scope
    /// of this library.
    pub loop_bar_len: u32,

    /// Time-stretching algorithm applied to the sample.
    /// See [`TimeStretchMode`] for suitable choices.
    ///
    /// ## No enum usage?
    ///
    /// [`TimeStretchMode`] has a base representation of `u8` but a [`SampleSettingsFile`] expects a
    /// `u32` value for this field.
    /// As such, we have to convert to `u32` values for this field via [`TimeStretchMode::try_from`]
    /// instead of the relevant variant.
    /// While it may be possible to change this in a future version via a custom implementation of
    /// [`Serialize`] and [`Deserialize`], it is currently out of scope.
    ///
    /// Use the [`SampleSettingsFile::new`] method to create a new instance with the appropriate
    /// enum variant.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field has an appropriate value.
    pub stretch: u32,

    /// Loop mode for the sample.
    /// See [`LoopMode`] for suitable choices.
    ///
    /// ## No enum usage?
    ///
    /// [`LoopMode`] has a base representation of `u8` but a [`SampleSettingsFile`] expects a
    /// `u32` value for this field.
    /// As such, we have to convert to `u32` values for this field via [`LoopMode::try_from`]
    /// instead of the relevant variant.
    /// While it may be possible to change this in a future version via a custom implementation of
    /// [`Serialize`] and [`Deserialize`], it is currently out of scope.
    ///
    /// Use the [`SampleSettingsFile::new`] method to create a new instance with the appropriate
    /// enum variant.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field has an appropriate value.
    pub loop_mode: u32,

    /// Gain of the sample.
    /// -24.0 db <= x <= +24 db range in the machine's UI, with increments of 0.5 db changes.
    /// 0 <= x <= 96 range in binary data file.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field has an appropriate
    /// value within the Octatrack's bounds for gain.
    pub gain: u16,

    /// Trig Quantization mode applied to the sample.
    /// See [`TrigQuantizationMode`] for suitable choices.
    ///
    /// ## No enum usage?
    ///
    /// [`TrigQuantizationMode`] has a base representation of `u8` but a [`SampleSettingsFile`]
    /// expects a `u32` value for this field.
    /// As such, we have to convert to `u32` values for this field via
    /// [`TrigQuantizationMode::try_from`] instead of the relevant variant.
    /// While it may be possible to change this in a future version via a custom implementation of
    /// [`Serialize`] and [`Deserialize`], it is currently out of scope.
    ///
    /// Use the [`SampleSettingsFile::new`] method to create a new instance with the appropriate
    /// enum variant.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field has an appropriate value.
    pub quantization: u8,

    /// Where the trim start marker is placed for the sample, measured in bars.
    /// Default is 0 (start of sample).
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field is less than `trim_end`
    pub trim_start: u32,

    /// Where the trim end marker is placed for the sample.
    /// When the sample is being played in normal mode (i.e. not using slices),
    /// the Octatrack will not play samples past this point.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field is greater than `trim_start`
    pub trim_end: u32,

    /// Start position for any loops.
    /// Default is the same as trim start.
    ///
    /// A note from the Octatrack manual on loop point/start behaviour:
    /// > If a loop point is set, the sample will play from the start point to the
    /// > end point, then loop from the loop point to the end point
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method checks whether this field is within the bounds
    /// of `trim_start` and `trim_end` values.
    pub loop_start: u32,

    /// 64 length array containing [`Slice`]s.
    /// See the [`Slice`] struct for more details.
    /// Any empty slice positions should have zero-valued struct fields.
    ///
    /// ## Validation
    ///
    /// The [`SampleSettingsFile::validate`] method calls [`Slice::validate`]
    pub slices: Slices<Slice>,

    /// Number of usable [`Slice`]s in this sample.
    /// Used by the Octatrack to ignore zero-valued [`Slice`]s in the `slices` array when loading the sample.
    pub slices_len: u32,

    /// Checksum value for the file.
    /// For now, this value must be calculated and added to the struct **after** the struct is created,
    /// via [`SampleSettingsFile::calculate_checksum`]
    ///
    /// # Example
    /// ```rust
    /// use ot_tools_io::types::{SampleSettingsFile, SlotMarkers};
    /// use ot_tools_io::HasChecksumField;
    ///
    /// # use ot_tools_io::OtToolsIoError;
    /// # fn main() -> Result<(), OtToolsIoError> {
    /// let mut ss_f = SampleSettingsFile::new(
    ///     SlotMarkers::default(),
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let checksum = ss_f.calculate_checksum()?;
    /// ss_f.checksum = checksum;
    ///
    /// # Ok(()) }
    /// ```
    /// ## Validation
    ///
    /// Use the [`SampleSettingsFile::check_checksum`] method to check the validity of the current
    /// checksum value.
    pub checksum: u16,
}

impl SampleSettingsFile {
    /// Create a new `SampleSettingsFile`
    ///
    /// Values like `tempo` and `gain` need to be normalized to relevant Octatrack range bounds
    /// when using this method.
    ///
    /// # Trim Bar Length and Loop Bar Length
    ///
    /// If the `trim_bar_len` and `loop_bar_len` arguments are not provided then the corresponding
    /// field values are set to zero.
    ///
    /// When providing these values you should ensure that you have correctly calculated both of
    /// these values **AND** the tempo value.
    /// All three are used simultaneously by the Octatrack,
    /// and I haven't spent any time figuring out which one takes priority
    /// (I think it's BPM/tempo, but I cannot confirm yet).
    ///
    /// See the relevant documentation [here][SampleSettingsFile#trim-length-and-loop-length] for
    /// more information.
    /// ```rust
    /// use std::array::from_fn;
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::{Slices, SlotMarkers, SampleSettingsFile};
    /// use ot_tools_io::settings::{
    ///    TrigQuantizationMode,
    ///    LoopMode,
    ///    TimeStretchMode,
    /// };
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let marks = SlotMarkers {
    ///     trim_offset: 0,
    ///     trim_end: 100,
    ///     loop_point: 0,
    ///     slices: Slices::default(),
    ///     slice_count: 0,
    /// };
    /// let x = SampleSettingsFile::new(
    ///     marks,
    ///     Some(48),    // -24.0 <-> +24.0 (0 <-> 96)
    ///     Some(2880),  // bpm x 24 (720 <-> 7200)
    ///     None,        // trim_bar_len will be zero, see documentation explainer
    ///     None,        // loop_bar_len will be zero, see documentation explainer
    ///     Some(TimeStretchMode::default()),
    ///     Some(TrigQuantizationMode::default()),
    ///     Some(LoopMode::default()),
    /// )?;
    /// assert_eq!(x.trim_start, 0);
    /// assert_eq!(x.trim_end, 100);
    /// assert_eq!(x.loop_start, 0);
    /// assert_eq!(x.trim_bar_len, 0);
    /// assert_eq!(x.loop_bar_len, 0);
    /// assert_eq!(x.tempo, 2880);
    /// assert_eq!(x.gain, 48);
    /// assert_eq!(x.stretch, 2);  // converted to u32 repr
    /// assert_eq!(x.quantization, 255);  // converted to u32 repr
    /// assert_eq!(x.loop_mode, 0);  // converted to u32 repr
    /// # Ok(()) }
    /// ```
    /*
    can't help this much unless i start creating sub-types, and i'm not too keen on that
    just now considering what happened with TrimConfig and LoopConfig.

    however, with some upcoming changes to slots, it may be worth thinking about two extra sub-types

    for settings:
    ```
    struct SlotSettings {
        stretch: TimeStretchMode,
        quantization: TrigQuantizationMode,
        loop_mode: LoopMode,
    };
    ```

    for playback stretch control:
    (trim bar len, loop bar len and bpm affect the time stretch algorithm)
    ```
    struct SlotStretchControl {
        tempo: Option<u16>,
        trim_bar_len: Option<u32>,
        loop_bar_len: Option<u32>,
    };
    ```
    */
    #[allow(clippy::too_many_arguments)]
    pub fn new<M: AsRef<SlotMarkers>>(
        markers: M,
        gain: Option<u16>,
        tempo: Option<u32>,
        trim_bar_len: Option<u32>,
        loop_bar_len: Option<u32>,
        stretch: Option<TimeStretchMode>,
        quantization: Option<TrigQuantizationMode>,
        loop_mode: Option<LoopMode>,
    ) -> Result<Self, OtToolsIoError> {
        let marks = markers.as_ref();

        let mut new = Self {
            // markers values, required
            trim_start: marks.trim_offset,
            trim_end: marks.trim_end,
            loop_start: marks.loop_point,
            slices: marks.slices,
            slices_len: marks.slice_count,
            // constant values
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: 0,
            // optional values
            gain: gain.unwrap_or(DEFAULT_GAIN as u16),
            tempo: tempo.unwrap_or(DEFAULT_TEMPO as u32),
            stretch: stretch.unwrap_or_default().into(),
            quantization: quantization.unwrap_or_default().into(),
            loop_mode: loop_mode.unwrap_or_default().into(),
            trim_bar_len: trim_bar_len.unwrap_or(0), // see docs for explanation of why this is zero
            loop_bar_len: loop_bar_len.unwrap_or(0), // see docs for explanation of why this is zero
            // not set here
            checksum: 0, // set below
        };

        new.checksum = new.calculate_checksum()?;

        new.validate()?;

        Ok(new)
    }

    /// Runs a series of validation checks on the field values for an instance of the type.
    ///
    /// Will return an appropriate error if a problem is discovered with a field's value.
    ///
    /// Read through the fields on [`SampleSettingsFile`] to find out which ones are checked and how
    /// they are checked.
    ///
    /// # Invalid Gain Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::{SampleSettingsFile, SlotMarkers};
    /// use ot_tools_io::errors::SampleSettingsError;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let ss_f = SampleSettingsFile::new(
    ///     SlotMarkers::default(),
    ///     Some(100),
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None
    /// );
    ///
    /// assert_eq!(
    ///     ss_f.unwrap_err().to_string(),
    ///     OtToolsIoError::SampleSettings(
    ///         SampleSettingsError::GainOutOfBounds {value: 100}
    ///     ).to_string(),
    /// );
    /// # Ok(()) }
    /// ```
    ///
    /// # Invalid Tempo Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::{SampleSettingsFile, SlotMarkers};
    /// use ot_tools_io::errors::SampleSettingsError;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let ss_f = SampleSettingsFile::new(
    ///     SlotMarkers::default(),
    ///     None,
    ///     Some(120),
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None
    /// );
    ///
    /// assert_eq!(
    ///     ss_f.unwrap_err().to_string(),
    ///     OtToolsIoError::SampleSettings(
    ///         SampleSettingsError::TempoOutOfBounds {value: 120}
    ///     ).to_string(),
    /// );
    ///
    /// # Ok(()) }
    /// ```
    pub fn validate(&self) -> Result<(), OtToolsIoError> {
        #[allow(clippy::manual_range_contains)]
        if self.tempo < 720 || self.tempo > 7200 {
            return Err(SampleSettingsError::TempoOutOfBounds { value: self.tempo }.into());
        }

        if self.gain > 96 {
            return Err(SampleSettingsError::GainOutOfBounds {
                value: self.gain as u32,
            }
            .into());
        }

        SlotMarkers::from(self).validate()?;

        LoopMode::try_from(self.loop_mode)?;
        TimeStretchMode::try_from(self.stretch)?;
        TrigQuantizationMode::try_from(self.quantization)?;

        if !self.check_checksum()? {
            return Err(SampleSettingsError::InvalidChecksum {
                checksum: self.checksum,
            }
            .into());
        };

        if !self.check_header()? {
            return Err(OtToolsIoError::FileHeader);
        };

        if !self.check_file_version()? {
            return Err(SampleSettingsError::InvalidFileVersion {
                version: self.datatype_version,
            }
            .into());
        };

        if !self.check_checksum()? {
            return Err(SampleSettingsError::InvalidChecksum {
                checksum: self.checksum,
            }
            .into());
        };

        Ok(())
    }

    /// Create a new [`SlotAttributes`] instance from this [`SampleSettingsFile`].
    ///
    /// Will validate the `slot_id` argument depending on the [`SlotType`] variant provided to the
    /// `slot_type` argument.
    ///
    /// # Valid Example
    /// ```
    /// # use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::types::{SlotMarkers, SampleSettingsFile, SlotAttributes, SlotType};
    /// # use ot_tools_io::settings::{TimeStretchMode, LoopMode, TrigQuantizationMode};
    /// use std::path::PathBuf;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let ss_f = SampleSettingsFile::new(
    ///     SlotMarkers::default(),
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let attrs = ss_f.to_slot_attr(
    ///     SlotType::Static,
    ///     100,
    ///     Some(PathBuf::from("some/path"))
    /// )?;
    ///
    /// assert_eq!(
    ///     attrs,
    ///     SlotAttributes {
    ///         slot_id: 100,
    ///         slot_type: SlotType::Static,
    ///         path: Some(PathBuf::from("some/path")),
    ///         timestrech_mode: TimeStretchMode::default(),
    ///         loop_mode: LoopMode::default(),
    ///         trig_quantization_mode: TrigQuantizationMode::default(),
    ///         gain: 48,
    ///         bpm: 2880,
    ///     }
    /// );
    /// # Ok(()) }
    /// ```
    ///
    /// # Error Example
    /// ```
    /// use ot_tools_io::OtToolsIoError;
    /// use ot_tools_io::errors::SampleSettingsError;
    /// use ot_tools_io::types::{SlotMarkers, SampleSettingsFile, SlotAttributes, SlotType};
    /// use std::path::PathBuf;
    /// # fn main() -> Result<(), OtToolsIoError> {
    ///
    /// let ss_f = SampleSettingsFile::new(
    ///     SlotMarkers::default(),
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    ///     None,
    /// )?;
    ///
    /// let attrs_err = ss_f.to_slot_attr(
    ///     SlotType::Static,
    ///     200,  // bad slot id!
    ///     Some(PathBuf::from("some/path"))
    /// ).unwrap_err();
    ///
    /// assert_eq!(
    ///     attrs_err.to_string(),
    ///     OtToolsIoError::SampleSettings(
    ///         SampleSettingsError::SlotIdOutOfBounds { id: 200, slot_type: SlotType::Static }
    ///     ).to_string()
    /// );
    /// # Ok(()) }
    /// ```
    pub fn to_slot_attr(
        &self,
        slot_type: SlotType,
        slot_id: u8,
        slot_path: Option<PathBuf>,
    ) -> Result<SlotAttributes, OtToolsIoError> {
        // neither static nor flex slots cannot have id = 0
        if slot_id == 0 {
            return Err(SampleSettingsError::SlotIdOutOfBounds {
                id: slot_id,
                slot_type,
            }
            .into());
        }

        // static slots cannot have id > 128
        if slot_type == SlotType::Static && slot_id > 128 {
            return Err(SampleSettingsError::SlotIdOutOfBounds {
                id: slot_id,
                slot_type,
            }
            .into());
        }

        // flex slots cannot have id > 136
        if slot_type == SlotType::Flex && slot_id > 136 {
            return Err(SampleSettingsError::SlotIdOutOfBounds {
                id: slot_id,
                slot_type,
            }
            .into());
        }

        Ok(SlotAttributes {
            slot_type,
            slot_id,
            path: slot_path,
            timestrech_mode: TimeStretchMode::try_from(self.stretch)?,
            loop_mode: LoopMode::try_from(self.loop_mode)?,
            trig_quantization_mode: TrigQuantizationMode::try_from(self.quantization)?,
            gain: self.gain as u8,
            bpm: self.tempo as u16,
        })
    }

    /// Returns the `stretch` field as a variant of [`TimeStretchMode`].
    ///
    /// Essentially calls [`TimeStretchMode::try_from`]
    pub fn timestretch_mode_into_setting(&self) -> Result<TimeStretchMode, OtToolsIoError> {
        TimeStretchMode::try_from(self.stretch).map_err(OtToolsIoError::SettingValue)
    }

    /// Returns the `loop_mode` field as a variant of [`LoopMode`]
    ///
    /// Essentially calls [`LoopMode::try_from`]
    pub fn loop_mode_into_setting(&self) -> Result<LoopMode, OtToolsIoError> {
        LoopMode::try_from(self.loop_mode).map_err(OtToolsIoError::SettingValue)
    }

    /// Returns the `quantization` field as a variant of [`TrigQuantizationMode`]
    ///
    /// Essentially calls [`TrigQuantizationMode::try_from`]
    pub fn trig_quantization_into_setting(&self) -> Result<TrigQuantizationMode, OtToolsIoError> {
        TrigQuantizationMode::try_from(self.loop_mode).map_err(OtToolsIoError::SettingValue)
    }
}

#[cfg(test)]
mod new {
    use super::test_utils::create_mock_new_sample_settings;
    use super::SampleSettingsError;
    use crate::OtToolsIoError;

    #[test]
    fn invalid_oob_temp_high() -> Result<(), OtToolsIoError> {
        assert_eq!(
            create_mock_new_sample_settings(Some(7201), None)
                .unwrap_err()
                .to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::TempoOutOfBounds { value: 7201 })
                .to_string()
        );
        Ok(())
    }

    #[test]
    fn invalid_oob_temp_low() -> Result<(), OtToolsIoError> {
        let s_f = create_mock_new_sample_settings(Some(29), None);
        assert_eq!(
            s_f.unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::TempoOutOfBounds { value: 29 })
                .to_string()
        );
        Ok(())
    }

    #[test]
    fn invalid_oob_gain() -> Result<(), OtToolsIoError> {
        assert_eq!(
            create_mock_new_sample_settings(None, Some(97))
                .unwrap_err()
                .to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::GainOutOfBounds { value: 97 })
                .to_string()
        );
        Ok(())
    }
}

#[cfg(test)]
mod validate {
    use super::test_utils::create_mock_new_sample_settings;
    use super::SampleSettingsError;
    use crate::settings::InvalidValueError;
    use crate::traits::HasChecksumField;
    use crate::OtToolsIoError;

    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let s_f = create_mock_new_sample_settings(None, None)?;
        assert!(s_f.validate().is_ok());
        Ok(())
    }

    // gain and tempo are tested above

    #[test]
    fn err_stretch() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.stretch = 255;
        s_f.checksum = s_f.calculate_checksum()?;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::SettingValue(InvalidValueError::TimeStretchMode).to_string()
        );
        Ok(())
    }

    #[test]
    fn err_loop() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.loop_mode = 255;
        s_f.checksum = s_f.calculate_checksum()?;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::SettingValue(InvalidValueError::LoopMode).to_string()
        );
        Ok(())
    }

    #[test]
    fn err_quant() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.quantization = 250; // 255 is an actual value for quantization!
        s_f.checksum = s_f.calculate_checksum()?;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::SettingValue(InvalidValueError::TrigQuantizationMode).to_string()
        );
        Ok(())
    }

    #[test]
    fn err_chksum() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.checksum = 1;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::InvalidChecksum {
                checksum: s_f.checksum
            })
            .to_string(),
        );
        Ok(())
    }

    #[test]
    fn err_header() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.header[0] = 255;
        s_f.checksum = s_f.calculate_checksum()?;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::FileHeader.to_string(),
        );
        Ok(())
    }

    #[test]
    fn err_file_version() -> Result<(), OtToolsIoError> {
        let mut s_f = create_mock_new_sample_settings(None, None)?;
        s_f.datatype_version = 255;
        s_f.checksum = s_f.calculate_checksum()?;
        assert_eq!(
            s_f.validate().unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::InvalidFileVersion {
                version: s_f.datatype_version
            })
            .to_string(),
        );
        Ok(())
    }
}

#[cfg(test)]
mod to_slot_attrs {
    use super::test_utils::create_mock_new_sample_settings;
    use crate::projects::SlotAttributes;
    use crate::samples::SampleSettingsError;
    use crate::settings::SlotType;
    use crate::OtToolsIoError;
    use std::path::PathBuf;

    #[test]
    fn basic_static() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs = settings.to_slot_attr(
            SlotType::Static,
            1,
            Some(PathBuf::from("../AUDIO/path.wav")),
        )?;

        assert_eq!(
            attrs,
            SlotAttributes {
                slot_type: SlotType::Static,
                slot_id: 1,
                path: Some(PathBuf::from("../AUDIO/path.wav")),
                timestrech_mode: Default::default(),
                loop_mode: Default::default(),
                trig_quantization_mode: Default::default(),
                gain: 48,
                bpm: 2880,
            },
        );
        Ok(())
    }

    #[test]
    fn invalid_static_slot_id_0() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs = settings.to_slot_attr(
            SlotType::Static,
            0,
            Some(PathBuf::from("../AUDIO/path.wav")),
        );

        assert_eq!(
            attrs.unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::SlotIdOutOfBounds {
                id: 0,
                slot_type: SlotType::Static
            })
            .to_string(),
        );
        Ok(())
    }

    #[test]
    fn invalid_static_slot_id_129() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs = settings.to_slot_attr(
            SlotType::Static,
            129,
            Some(PathBuf::from("../AUDIO/path.wav")),
        );

        assert_eq!(
            attrs.unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::SlotIdOutOfBounds {
                id: 129,
                slot_type: SlotType::Static
            })
            .to_string(),
        );
        Ok(())
    }

    #[test]
    fn basic_flex() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs =
            settings.to_slot_attr(SlotType::Flex, 1, Some(PathBuf::from("../AUDIO/path.wav")))?;

        assert_eq!(
            attrs,
            SlotAttributes {
                slot_type: SlotType::Flex,
                slot_id: 1,
                path: Some(PathBuf::from("../AUDIO/path.wav")),
                timestrech_mode: Default::default(),
                loop_mode: Default::default(),
                trig_quantization_mode: Default::default(),
                gain: 48,
                bpm: 2880,
            },
        );
        Ok(())
    }

    #[test]
    fn invalid_flex_slot_id_0() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs =
            settings.to_slot_attr(SlotType::Flex, 0, Some(PathBuf::from("../AUDIO/path.wav")));

        assert_eq!(
            attrs.unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::SlotIdOutOfBounds {
                id: 0,
                slot_type: SlotType::Flex
            })
            .to_string(),
        );
        Ok(())
    }

    #[test]
    fn invalid_flex_slot_id_137() -> Result<(), OtToolsIoError> {
        let settings = create_mock_new_sample_settings(None, None)?;

        let attrs = settings.to_slot_attr(
            SlotType::Flex,
            137,
            Some(PathBuf::from("../AUDIO/path.wav")),
        );

        assert_eq!(
            attrs.unwrap_err().to_string(),
            OtToolsIoError::SampleSettings(SampleSettingsError::SlotIdOutOfBounds {
                id: 137,
                slot_type: SlotType::Flex
            })
            .to_string(),
        );
        Ok(())
    }
}

impl SwapBytes for SampleSettingsFile {
    fn swap_bytes(self) -> Self {
        let mut bswapped_slices = self.slices;

        for (i, slice) in self.slices.iter().enumerate() {
            bswapped_slices[i] = slice.swap_bytes();
        }

        Self {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: self.unknown,
            tempo: self.tempo.swap_bytes(),
            trim_bar_len: self.trim_bar_len.swap_bytes(),
            loop_bar_len: self.loop_bar_len.swap_bytes(),
            stretch: self.stretch.swap_bytes(),
            loop_mode: self.loop_mode.swap_bytes(),
            gain: self.gain.swap_bytes(),
            quantization: self.quantization.swap_bytes(),
            trim_start: self.trim_start.swap_bytes(),
            trim_end: self.trim_end.swap_bytes(),
            loop_start: self.loop_start.swap_bytes(),
            slices: bswapped_slices,
            slices_len: self.slices_len.swap_bytes(),
            checksum: self.checksum.swap_bytes(),
        }
    }
}

impl OctatrackFileIO for SampleSettingsFile {
    /// Encodes struct data to binary representation, after some pre-processing.
    ///
    /// Before serializing, will:
    /// 1. generate checksum value
    /// 2. swap bytes of values (when current system is little-endian)
    fn to_bytes(&self) -> Result<Vec<u8>, OtToolsIoError> {
        // todo: figure out a non-clone version of this
        #[allow(clippy::clone_on_copy)]
        let mut chkd = self.clone();
        chkd.checksum = self.calculate_checksum()?;

        let encoded = if cfg!(target_endian = "little") {
            bincode::serialize(&chkd.swap_bytes())?
        } else {
            bincode::serialize(&chkd)?
        };
        Ok(encoded)
    }

    /// Decode raw bytes of a `.ot` data file into a new struct,
    /// swapping byte values if system is little-endian.
    fn from_bytes(bytes: &[u8]) -> Result<Self, OtToolsIoError> {
        let decoded: Self = bincode::deserialize(bytes)?;

        // todo: figure out a non-clone version of this
        #[allow(clippy::clone_on_copy)]
        let mut bswapd = decoded.clone();

        // swapping bytes is one required when running on little-endian systems
        if cfg!(target_endian = "little") {
            bswapd = decoded.swap_bytes();
        }

        Ok(bswapd)
    }
}

#[cfg(test)]
mod from_bytes {
    use crate::read_bin_file;
    use crate::samples::test_utils::mock_0_slice_test_file;
    use crate::test_utils::get_samples_dirpath;
    use crate::{OctatrackFileIO, OtToolsIoError, SampleSettingsFile};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let path = get_samples_dirpath().join("checksum").join("0slices.ot");
        let bytes = read_bin_file(&path)?;
        let s = SampleSettingsFile::from_bytes(&bytes)?;
        assert_eq!(s, mock_0_slice_test_file());
        Ok(())
    }
}

#[cfg(test)]
mod to_bytes {
    use crate::read_bin_file;
    use crate::samples::test_utils::mock_0_slice_test_file;
    use crate::test_utils::get_samples_dirpath;
    use crate::{OctatrackFileIO, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let path = get_samples_dirpath().join("checksum").join("0slices.ot");
        let bytes = read_bin_file(&path)?;
        let b = mock_0_slice_test_file().to_bytes()?;
        assert_eq!(b, bytes);
        Ok(())
    }
}

impl HasChecksumField for SampleSettingsFile {
    // tests for this are in the main tests directory -- `samples_settings_files.rs`
    fn calculate_checksum(&self) -> Result<u16, OtToolsIoError> {
        let bytes = bincode::serialize(&self)?;

        // skip header and checksum byte values
        let checksum_bytes = &bytes[16..bytes.len() - 2];

        let chk: u32 = checksum_bytes
            .iter()
            .map(|x| *x as u32)
            .sum::<u32>()
            .rem_euclid(u16::MAX as u32 + 1);

        Ok(chk as u16)
    }

    fn update_checksum(&mut self) -> Result<(), OtToolsIoError> {
        self.checksum = self.calculate_checksum()?;
        Ok(())
    }

    fn check_checksum(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.checksum == self.calculate_checksum()?)
    }
}

#[cfg(test)]
mod checksum_field {
    use super::test_utils::create_mock_new_sample_settings;
    use crate::{HasChecksumField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        let mut x = create_mock_new_sample_settings(None, None)?;
        x.checksum = x.calculate_checksum()?;
        assert!(x.check_checksum()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut x = create_mock_new_sample_settings(None, None)?;
        x.checksum = x.calculate_checksum()?;
        x.checksum = 0;
        assert!(!x.check_checksum()?);
        Ok(())
    }

    mod files {
        use crate::test_utils::get_samples_dirpath;
        use crate::{HasChecksumField, OctatrackFileIO, OtToolsIoError, SampleSettingsFile};

        fn helper(test_name: String) -> Result<(u16, u16), OtToolsIoError> {
            let mut src_path = get_samples_dirpath().join("checksum").join(&test_name);
            src_path.set_extension("ot");

            let valid = SampleSettingsFile::from_data_file(&src_path)?;

            #[allow(clippy::clone_on_copy)] // want a full deep copy / clone
            let mut x = valid.clone();
            x.checksum = 0;

            Ok((x.calculate_checksum()?, valid.checksum))
        }

        #[test]
        fn zero_slices_trig_quant_one_step() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("0slices-tq1step".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn zero_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("0slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn one_slice() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("1slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("2slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn four_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("4slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn eight_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("8slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixteen_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("16slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn thirty_two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("32slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn forty_eight_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("48slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_two_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("62slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_three_slices() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("63slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }

        #[test]
        fn sixty_four_slices_correct() -> Result<(), OtToolsIoError> {
            let (test, valid) = helper("64slices".to_string())?;
            assert_eq!(test, valid);
            Ok(())
        }
    }
}

impl HasHeaderField for SampleSettingsFile {
    fn check_header(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.header == SAMPLES_HEADER)
    }
}

#[cfg(test)]
mod header_field {
    use super::test_utils::create_mock_new_sample_settings;
    use crate::{HasHeaderField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        assert!(create_mock_new_sample_settings(None, None)?.check_header()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut mutated = create_mock_new_sample_settings(None, None)?;
        mutated.header[0] = 0x00;
        mutated.header[20] = 111;
        assert!(!mutated.check_header()?);
        Ok(())
    }
}

impl HasFileVersionField for SampleSettingsFile {
    fn check_file_version(&self) -> Result<bool, OtToolsIoError> {
        Ok(self.datatype_version == SAMPLES_FILE_VERSION)
    }
}

#[cfg(test)]
mod file_version_field {
    use super::test_utils::create_mock_new_sample_settings;
    use crate::{HasFileVersionField, OtToolsIoError};
    #[test]
    fn valid() -> Result<(), OtToolsIoError> {
        assert!(create_mock_new_sample_settings(None, None)?.check_file_version()?);
        Ok(())
    }

    #[test]
    fn invalid() -> Result<(), OtToolsIoError> {
        let mut mutated = create_mock_new_sample_settings(None, None)?;
        mutated.datatype_version = 0;
        assert!(!mutated.check_file_version()?);
        Ok(())
    }
}

impl<A, M> From<(A, M)> for SampleSettingsFile
where
    A: AsRef<SlotAttributes>,
    M: AsRef<SlotMarkers>,
{
    fn from(value: (A, M)) -> Self {
        let attrs = value.0.as_ref();
        let markers = value.1.as_ref();

        SampleSettingsFile {
            header: SAMPLES_HEADER,
            datatype_version: SAMPLES_FILE_VERSION,
            unknown: 0,
            tempo: attrs.bpm as u32,
            // todo: does not currently exist as a field in `SlotAttributes`
            trim_bar_len: 0,
            // todo: does not currently exist as a field in `SlotAttributes`
            loop_bar_len: 0,
            stretch: attrs.timestrech_mode.into(),
            loop_mode: attrs.loop_mode.into(),
            gain: attrs.gain as u16,
            quantization: attrs.trig_quantization_mode.into(),
            trim_start: markers.trim_offset,
            trim_end: markers.trim_end,
            loop_start: markers.loop_point,
            slices: markers.slices,
            slices_len: markers.slice_count,
            checksum: 0,
        }
    }
}

#[cfg(test)]
mod sample_settings_from {
    use crate::generics::Slots;
    use crate::projects::SlotAttributes;
    use crate::MarkersFile;
    use crate::OtToolsIoError;
    use crate::SampleSettingsFile;

    #[test]
    fn from_owned_valid() -> Result<(), OtToolsIoError> {
        let slots = Slots::<Option<SlotAttributes>>::default();
        let slot = slots.recording_buffers[0].clone();
        let markers = MarkersFile::default().flex_slots[0];
        let _ = SampleSettingsFile::from((slot.unwrap(), markers));
        Ok(())
    }

    #[test]
    fn from_borrowed_valid() -> Result<(), OtToolsIoError> {
        let slots = Slots::<Option<SlotAttributes>>::default();
        let slot = slots.recording_buffers[0].clone();
        let markers = MarkersFile::default().flex_slots[0];
        let _ = SampleSettingsFile::from((&slot.unwrap(), &markers));
        Ok(())
    }
}