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
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2026 Mike Robeson [dijksterhuis]
*/

//! Library crate for reading/writing data files for the [Elektron Octatrack][0].
//!
//! ```rust
//! // reading, mutating and writing a bank file
//!
//! use std::path::PathBuf;
//! use ot_tools_io::{OctatrackFileIO, BankFile};
//!
//! let path = PathBuf::from("test-data")
//!     .join("blank-project")
//!     .join("bank01.work");
//!
//! // read an editable version of the bank file
//! let mut bank = BankFile::from_data_file(&path).unwrap();
//!
//! // change active scenes on the working copy of Part 4
//! bank.parts_unsaved[3].active_scenes.scene_a = 2;
//! bank.parts_unsaved[3].active_scenes.scene_b = 6;
//!
//! // write to a new bank file
//! let outfpath = std::env::temp_dir()
//!     .join("ot-tools-io")
//!     .join("doctest")
//!     .join("main_example_1");
//!
//! # // when running in cicd env the /tmp/ot-tools-io directory doesn't exist yet
//! # let _ = std::fs::create_dir_all(outfpath.parent().unwrap());
//! bank.to_data_file(&outfpath).unwrap();
//! ```
//!
//! ## Brief Overview
//!
//! Important types and traits are re-exported or defined in the root of the crate's namespace for
//! your convenience -- everything you need to read and write Octatrack data files should be
//! available with `use ot_tools_io::*`. Less commonly used types and traits are public within their
//! specific modules and will require importing.
//! ```rust
//! // basic / common imports
//! use ot_tools_io::{SampleSettingsFile, OctatrackFileIO, HasHeaderField};
//!
//! // lower level / less common imports
//! use ot_tools_io::samples::{SAMPLES_HEADER, SAMPLES_FILE_VERSION};
//! use ot_tools_io::slices::{Slice, SLICE_LOOP_POINT_DISABLED};
//! use ot_tools_io::parts::{Part, AudioTrackMachineParamsSetupPickup};
//! ```
//!
//! #### The `OctatrackFileIO` Trait
//! You'll usually want to import the [`OctatrackFileIO`] trait if you're reading or writing files.
//! It adds the associated functions & methods for file I/O, including for file I/O for YAML and
//! JSON files.
//! ```rust
//! // write a sample settings file to yaml and json
//!
//! use std::path::PathBuf;
//! use ot_tools_io::{SampleSettingsFile, OctatrackFileIO, HasHeaderField};
//!
//! let path = PathBuf::from("test-data")
//!     .join("samples")
//!     .join("sample.ot");
//!
//! let otfile = SampleSettingsFile::from_data_file(&path).unwrap();
//!
//! let outdir = std::env::temp_dir()
//!     .join("ot-tools-io")
//!     .join("doctest")
//!     .join("write_yaml_and_json");
//!
//! # // when running in cicd env the /tmp/ot-tools-io directory doesn't exist yet
//! # let _ = std::fs::create_dir_all(&outdir);
//! &otfile.to_yaml_file(&outdir.join("sample.yaml")).unwrap();
//! &otfile.to_json_file(&outdir.join("sample.json")).unwrap();
//! ```
//!
//! #### The `HasSomeField` Traits
//! The `Has*Field` traits add methods to a type to perform integrity checks: checksum calculation
//! and validation, header validation and file patch version validation.
//! ```rust
//! // check the header of sample settings file
//!
//! use std::path::PathBuf;
//! use ot_tools_io::{SampleSettingsFile, OctatrackFileIO, HasHeaderField};
//!
//! let path = PathBuf::from("test-data")
//!     .join("samples")
//!     .join("sample.ot");
//!
//! let otfile = SampleSettingsFile::from_data_file(&path).unwrap();
//! assert!(otfile.check_header().unwrap())
//! ```
//!
//! #### The `OtToolsIoError` Type
//! The `OtToolsIoError` type should be used to catch any errors in normal use as it implements
//! `From` for all other internal errors
//! ```rust
//! // handling errors
//!
//! use ot_tools_io::OtToolsIoError;
//! use ot_tools_io::settings::ProgChMidiChannel;
//!
//! // always errors
//! fn try_from_err() -> Result<ProgChMidiChannel, OtToolsIoError> {
//!     Ok(ProgChMidiChannel::try_from(100_i8)?)
//! }
//!
//! assert!(try_from_err().is_err());
//! assert_eq!(
//!     try_from_err().unwrap_err().to_string(),
//!     "invalid setting value: invalid Program Change MIDI Channel value".to_string(),
//! );
//! ```
//!
//! #### `SomeFile` Types
//! Types directly related to some file used by the Octatrack are named as `SomeFile`, where
//! `Some` is the relevant file base name (`*.ot` files obviously don't have a basename we can
//! use).
//!
//! Only these `*File` types can be read from / written to the filesystem using this crate's
//! [`OctatrackFileIO`] trait methods / functions.
//!
//! | Type    | Filename Pattern | Description |
//! | ------------ | -------------------------- | ------------|
//! | [`ArrangementFile`] | `arr??.*` | data for arrangements |
//! | [`BankFile`] | `bank??.*` | data for parts and patterns |
//! | [`MarkersFile`] | `markers.*` | start trim/end trim/slices/loop points for sample slots |
//! | [`ProjectFile`] | `project.*` | project level settings; state; sample slots |
//! | [`SampleSettingsFile`] | `*.ot` | saved sample settings data, loops slices etc. |
//!
//! Read the relevant modules in this library for more detailed information on
//! the data contained in each file.
//!
//! ####
//!
//! ## Additional Details
//!
//! #### Octatrack File Relationships
//!
//! - Changing the sample loaded into a sample slot updates both the [`ProjectFile`] file (trig
//!   quantization settings, file path etc) and the [`MarkersFile`] file (trim settings, slices,
//!   loop points).
//!
//! - Slot data from [`ProjectFile`]s and [`MarkersFile`]s is written to an [`SampleSettingsFile`]
//!   file when saving sample attributes data from the Octatrack's audio editing menu.
//!
//! - Loading a sample into a project sample slot ([`ProjectFile`]s and [`MarkersFile`]s) reads
//!   any data in an [`SampleSettingsFile`] files and configures the sample slot accordingly.
//!
//! - A [`BankFile`]'s patterns and parts store zero-indexed sample slot IDs as flex
//!   and static slot references (machine data in a part and track p-lock trigs in a pattern). These
//!   references point to the relevant slot in **_both_** the [`MarkersFile`] and [`ProjectFile`]
//!   for a project.
//!
//! - [`ArrangementFile`]s store a `u8` which references a [`BankFile`]'s pattern, indicating
//!   the pattern should be played when the specific row in an arrangement is triggered.
//!   The field is zero-indexed, with the full range used for pattern references 0 (A01) ->
//!   256 (P16).
//!
//!
//! #### Octatrack Device File Modifications
//!
//! - `*.work` files are created when creating a new project
//!   `PROJECT MENU -> CHANGE PROJECT -> CREATE NEW`.
//! - `*.work` files are updated by using the `PROJECT MENU -> SYNC TO CARD` operation.
//! - `*.work` files are updated when the user performs a `PROJECT MENU -> SAVE PROJECT` operation.
//! - `*.strd` files are created/updated when the user performs a `PROJECT MENU -> SAVE PROJECT`
//!   operation.
//! - `*.strd` files are not changed by the `PROJECT -> SYNC TO CARD` operation.
//! - `arr??.strd` files can also be saved via the `ARRANGER MENU -> SAVE ARRANGEMENT` operation.
//!
//! #### Notable 'gotcha's
//!
//! ##### Sample Slot IDs
//!
//! Project Sample Slots store their slots with a **_one-indexed_** `slot_id` field.
//!
//! **_All other references to sample slots are zero-indexed_** (i.e. [`BankFile`] and
//! [`MarkersFile`] files).
//!
//! I'm using lots of italics and bold formatting here because it is super annoying but there's not
//! much i can do about it. Remember you will need to convert from one to zero indexed whenever you
//! deal with Sample Slots.
//!
//! ##### Default Loop Point Values Differ Between Types
//!
//! A 'Disabled' loop point in either a [`MarkersFile`] or a [`SampleSettingsFile`] is a
//! `0xFFFFFFFF` value, but the default loop point when creating new [`MarkersFile`] is always
//! `0_u32`. The 'Disabled' value setting is only set when a sample is loaded into a sample slot,
//! and a [`SampleSettingsFile`] is generated from that sample slot data.
//!
//! ####
// For Andrey.
//! ## Slava Ukraini
//!
//! I've worked with Ukrainian developers. What is happening to their country is abhorrent.
//!
//! [![Stand With Ukraine](https://raw.githubusercontent.com/vshymanskyy/StandWithUkraine/main/banner2-direct.svg)](https://stand-with-ukraine.pp.ua)
//! ##
//!
//! [0]: https://www.elektron.se/explore/octatrack-mkii
//!

pub mod arrangements;
pub mod banks;
pub mod errors;
mod generics;
pub mod identifiers;
mod macros;
pub mod markers;
pub mod parts;
pub mod patterns;
pub mod projects;
pub mod samples;
pub mod settings;
pub mod slices;
#[cfg(test)]
#[allow(dead_code)]
mod test_utils;
mod traits;

pub use crate::arrangements::ArrangementFile;
pub use crate::banks::BankFile;
pub use crate::markers::MarkersFile;
pub use crate::projects::ProjectFile;
pub use crate::samples::SampleSettingsFile;

pub use crate::traits::{
    CheckFileIntegrity, Defaults, HasChecksumField, HasFileVersionField, HasHeaderField, IsDefault,
    OctatrackFileIO,
};

use crate::markers::SlotMarkersError;
use crate::projects::{ProjectError, ProjectParseError, ProjectSlotsError};
use crate::samples::SampleSettingsError;
use crate::settings::InvalidValueError;
use crate::slices::SliceError;
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use thiserror::Error;

/// Global error variant handling. All internally used error types and variants can cast to this
/// type.
#[derive(Debug, Error)]
pub enum OtToolsIoError {
    /// File could not be found / opened etc.
    #[error("File OS Error: {source} Path={path} (std::io::Error)")]
    FileOs {
        #[source]
        source: std::io::Error,
        path: PathBuf,
    },
    /// Some other FIle I/O error
    #[error("File I/O Error: {0} (std::io::Error)")]
    FileIo(#[from] std::io::Error),
    /// Bincode could not de/serialize the data
    #[error("error during binary data decoding / encoding: {0} (bincode::Error)")]
    Bincode(#[from] bincode::Error),
    /// Can't read project string data
    #[error("error reading utf8 string data: {0} (std::str::Utf8Error)")]
    ReadUtf8(#[from] std::str::Utf8Error),
    /// Can't parse project string data
    #[error("error parsing raw project data: {0} (ot_tools_io::projects::ProjectParseError)")]
    ProjectParse(#[from] ProjectParseError),
    /// Can't parse project string data
    #[error("error parsing project slots data: {0} (ot_tools_io::projects::ProjectSlotsError)")]
    ProjectSlots(#[from] ProjectSlotsError),
    /// [arrangements] parsing errors
    #[error("arrangement error: {0}")]
    Arrangement(#[from] arrangements::ArrangementError),
    /// Can't parse yaml data
    #[error("error processing yaml: {0} (serde_norway::Error)")]
    YamlParse(#[from] serde_norway::Error),
    /// Can't parse json data
    #[error("error processing json: {0} (serde_json::Error)")]
    JsonParse(#[from] serde_json::Error),
    /// [projects] specific errors
    #[error(
        "project files cannot be checked for integrity: {0} (ot_tools_io::projects::ProjectError)"
    )]
    ProjectFile(#[from] ProjectError),
    /// [samples] specific errors
    #[error("sample settings error: {0} (ot_tools_io::samples::SampleSettingsError)")]
    SampleSettings(#[from] SampleSettingsError),
    /// [markers] specific errors
    #[error("markers error: {0} (ot_tools_io::markers::MarkersErrors)")]
    Markers(#[from] SlotMarkersError),
    /// [slices] specific errors
    #[error("slices error: {0} (ot_tools_io::slices::SlicesErrors)")]
    Slice(#[from] SliceError),
    /// [settings] error handling
    #[error("invalid setting value: {0}")]
    SettingValue(#[from] InvalidValueError),
    /// Header for some file type is invalid
    #[error("invalid header(s) for file")]
    FileHeader,
    #[error("invalid index for identifier")]
    InvalidIndex,
}

/// Re-export of (most of) the useful types from the crate.
/// Allows you to use `use crate::types::*` if you want to be lazy.
pub mod types {
    /// Helper type to make working with slots *slightly* easier. A 'slot' is
    /// really the combined [`SlotAttributes`] and [`SlotMarkers`] structs.
    pub type SlotCombo = (SlotAttributes, SlotMarkers);
    pub use crate::arrangements::ArrangeRow;
    pub use crate::arrangements::ArrangementState;
    pub use crate::arrangements::LoopOrJumpOrHaltRow;
    pub use crate::arrangements::PatternRow;
    pub use crate::arrangements::ReminderRow;
    pub use crate::markers::SlotMarkers;
    pub use crate::parts::Part;
    pub use crate::patterns::Pattern;
    pub use crate::projects::SlotAttributes;
    pub use crate::settings::SlotType;
    pub use crate::slices::Slice;
    pub use crate::ArrangementFile;
    pub use crate::BankFile;
    pub use crate::MarkersFile;
    pub use crate::ProjectFile;
    pub use crate::SampleSettingsFile;

    // generic array new types
    pub use crate::generics::ActiveSlot;
    pub use crate::generics::ArrangeRows;
    pub use crate::generics::Arrangements;
    pub use crate::generics::Banks;
    pub use crate::generics::Parts;
    pub use crate::generics::Patterns;
    pub use crate::generics::PlaybackSlots;
    pub use crate::generics::RecordingBufferSlots;
    pub use crate::generics::Scenes;
    pub use crate::generics::Slices;
    pub use crate::generics::Slots;
    pub use crate::generics::Tracks;
    pub use crate::generics::Trigs;
}

/// The Elektron Octatrack OS project versions this library can be used with.
/// The `ProjectFile.metadata.os_version` field must contain one of these
/// string values, otherwise the project is not compatible.
///
/// See the [`ProjectFile::check_compatible_os_version`] method for usage
/// information.
pub const ALLOWED_OS_VERSIONS: [&str; 3] = ["1.40A", "1.40B", "1.40C"];

#[doc(hidden)]
/// Read bytes from a file at `path`.
/// ```compile_fail
/// let fpath = std::path::PathBuf::from("test-data")
///     .join("blank-project")
///     .join("bank01.work");
/// let r = ot_tools_io::read_bin_file(&fpath);
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap().len(), 636113);
///```
fn read_bin_file(path: &Path) -> Result<Vec<u8>, OtToolsIoError> {
    let mut infile = File::open(path).map_err(|e| OtToolsIoError::FileOs {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mut bytes: Vec<u8> = vec![];
    let _: usize = infile.read_to_end(&mut bytes)?;
    Ok(bytes)
}

#[cfg(test)]
mod read_bin_file {
    use crate::test_utils::*;
    use crate::{read_bin_file, OtToolsIoError};

    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("bank01.work");
        read_bin_file(&path)?;
        Ok(())
    }

    #[test]
    fn err_file_io() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("NOTNTONTONTNTOTNONT");

        #[cfg(target_os = "windows")]
        assert_eq!(
            read_bin_file(&path).unwrap_err().to_string(),
            format!["File OS Error: The system cannot find the file specified. (os error 2) Path={} (std::io::Error)", path.display()].to_string(),
            "should throw a OtToolsIoError::FileOS error when file does not exist"
        );

        #[cfg(target_os = "linux")]
        assert_eq!(
            read_bin_file(&path).unwrap_err().to_string(),
            format![
                "File OS Error: No such file or directory (os error 2) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when file does not exist"
        );

        Ok(())
    }
}

#[doc(hidden)]
/// Write bytes to a file at `path`.
/// ```compile_fail
/// use std::env::temp_dir;
/// use std::array::from_fn;
///
/// let arr: [u8; 27] = from_fn(|_| 0);
///
/// let fpath = temp_dir()
///    .join("ot-tools-io")
///    .join("doctest")
///    .join("write_bin_file.example");
///
/// # use std::fs::create_dir_all;
/// # create_dir_all(&fpath.parent().unwrap()).unwrap();
/// let r = ot_tools_io::write_bin_file(&arr, &fpath);
/// assert!(r.is_ok());
/// assert!(fpath.exists());
/// ```
fn write_bin_file(bytes: &[u8], path: &Path) -> Result<(), OtToolsIoError> {
    let mut file: File = File::create(path).map_err(|e| OtToolsIoError::FileOs {
        path: path.to_path_buf(),
        source: e,
    })?;
    file.write_all(bytes)?;
    Ok(())
}

#[cfg(test)]
mod write_bin_file {
    use crate::{write_bin_file, OtToolsIoError};
    use std::env::temp_dir;
    use std::fs::{create_dir_all, remove_file};

    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let path = temp_dir()
            .join("ot-tools-io")
            .join("write_bin_file")
            .join("ok.bin");
        create_dir_all(path.parent().unwrap())?;
        if path.exists() {
            remove_file(&path)?;
        };
        write_bin_file(&[1, 2, 3, 4], &path)?;
        Ok(())
    }

    // should fail: attempting to write a file to an existing directory
    #[test]
    fn err_file_io() -> Result<(), OtToolsIoError> {
        let path = temp_dir().join("ot-tools-io").join("write_bin_file");
        create_dir_all(&path)?;

        #[cfg(target_os = "windows")]
        assert_eq!(
            write_bin_file(&[1, 2, 3, 4], &path)
                .unwrap_err()
                .to_string(),
            format![
                "File OS Error: Access is denied. (os error 5) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when a file cannot be created"
        );

        #[cfg(target_os = "linux")]
        assert_eq!(
            write_bin_file(&[1, 2, 3, 4], &path)
                .unwrap_err()
                .to_string(),
            format![
                "File OS Error: Is a directory (os error 21) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when a file cannot be created"
        );
        Ok(())
    }
}

#[doc(hidden)]
/// Read a file at `path` as a string.
/// ```compile_fail
/// let fpath = std::path::PathBuf::from("test-data")
///     .join("blank-project")
///     .join("bank01.work");
/// let r = ot_tools_io::read_bin_file(&fpath);
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap().len(), 636113);
/// ```
fn read_str_file(path: &Path) -> Result<String, OtToolsIoError> {
    let mut file = File::open(path).map_err(|e| OtToolsIoError::FileOs {
        path: path.to_path_buf(),
        source: e,
    })?;
    let mut string = String::new();
    let _ = file.read_to_string(&mut string)?;
    Ok(string)
}

#[cfg(test)]
mod read_str_file {
    use crate::test_utils::*;
    use crate::{read_str_file, OtToolsIoError};

    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("project.work");
        read_str_file(&path)?;
        Ok(())
    }

    #[test]
    fn err_file_io() -> Result<(), OtToolsIoError> {
        let path = get_blank_proj_dirpath().join("NOTNTONTONTNTOTNONT");

        #[cfg(target_os = "windows")]
        assert_eq!(
            read_str_file(&path).unwrap_err().to_string(),
            format!["File OS Error: The system cannot find the file specified. (os error 2) Path={} (std::io::Error)", path.display()].to_string(),
            "should throw a OtToolsIoError::FileOS error when file does not exist"
        );

        #[cfg(target_os = "linux")]
        assert_eq!(
            read_str_file(&path).unwrap_err().to_string(),
            format![
                "File OS Error: No such file or directory (os error 2) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when file does not exist"
        );

        Ok(())
    }
}

#[doc(hidden)]
/// Write a string to a file at `path`.
/// ```compile_fail
/// use std::env::temp_dir;
///
/// let data = "abcd".to_string();
///
/// let fpath = temp_dir()
///    .join("ot-tools-io")
///    .join("doctest")
///    .join("write_str_file.example");
///
/// # use std::fs::create_dir_all;
/// # create_dir_all(&fpath.parent().unwrap()).unwrap();
/// let r = ot_tools_io::write_str_file(&data, &fpath);
/// assert!(r.is_ok());
/// assert!(fpath.exists());
/// ```
fn write_str_file(string: &str, path: &Path) -> Result<(), OtToolsIoError> {
    let mut file: File = File::create(path).map_err(|e| OtToolsIoError::FileOs {
        path: path.to_path_buf(),
        source: e,
    })?;
    write!(file, "{string}")?;
    Ok(())
}

#[cfg(test)]
mod write_str_file {
    use crate::{write_str_file, OtToolsIoError};
    use std::env::temp_dir;
    use std::fs::{create_dir_all, remove_file};

    #[test]
    fn ok() -> Result<(), OtToolsIoError> {
        let path = temp_dir()
            .join("ot-tools-io")
            .join("write_str_file")
            .join("ok.txt");
        create_dir_all(path.parent().unwrap())?;
        if path.exists() {
            remove_file(&path)?;
        };
        write_str_file("SOMETHING", &path)?;
        Ok(())
    }

    // should fail: attempting to write a file to an existing directory
    #[test]
    fn err_file_io() -> Result<(), OtToolsIoError> {
        let path = temp_dir().join("ot-tools-io").join("write_str_file");
        create_dir_all(&path)?;

        #[cfg(target_os = "windows")]
        assert_eq!(
            write_str_file("SOMETHING", &path).unwrap_err().to_string(),
            format![
                "File OS Error: Access is denied. (os error 5) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when a file cannot be created"
        );

        #[cfg(target_os = "linux")]
        assert_eq!(
            write_str_file("SOMETHING", &path).unwrap_err().to_string(),
            format![
                "File OS Error: Is a directory (os error 21) Path={} (std::io::Error)",
                path.display()
            ]
            .to_string(),
            "should throw a OtToolsIoError::FileOS error when a file cannot be created"
        );
        Ok(())
    }
}

fn loop_point_is_in_trim_range(loop_point: u32, trim_start: u32, trim_end: u32) -> bool {
    loop_point >= trim_start && loop_point < trim_end
}