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
/*
SPDX-License-Identifier: GPL-3.0-or-later
Copyright © 2026 Mike Robeson [dijksterhuis]
*/
use crate::OtToolsIoError;
use serde::{Deserialize, Serialize};
use std::fmt::Debug;
use std::path::Path;
/// Convenience trait for types which directly correspond to Elektron Octatrack binary data files.
/// Associated functions and methods etc. for File I/O, plus a `repr` method for debugging.
pub trait OctatrackFileIO: Serialize + for<'a> Deserialize<'a> {
/// Read type from an Octatrack data file at path
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data").join("blank-project").join("bank01.work");
/// use ot_tools_io::{BankFile, OctatrackFileIO};
/// // no newlines
/// BankFile::from_data_file(&path).unwrap().repr(None);
/// // no newlines
/// BankFile::from_data_file(&path).unwrap().repr(Some(false));
/// // with newlines
/// BankFile::from_data_file(&path).unwrap().repr(Some(true));
/// ```
fn repr(&self, newlines: Option<bool>)
where
Self: Debug,
{
if newlines.unwrap_or(true) {
println!("{self:#?}")
} else {
println!("{self:?}")
};
}
// BYTES
/// Read type from an Octatrack data file at path
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data").join("blank-project").join("bank01.work");
/// use ot_tools_io::{BankFile, OctatrackFileIO};
/// let bank = BankFile::from_data_file(&path).unwrap();
/// assert_eq!(bank.datatype_version, 23);
/// ```
fn from_data_file(path: &Path) -> Result<Self, OtToolsIoError> {
let bytes = crate::read_bin_file(path)?;
let data = Self::from_bytes(&bytes)?;
Ok(data)
}
/// Read type from bytes
/// ```rust
/// // need to create everything from scratch in this example as many bytes otherwise
/// use serde::{Deserialize, Serialize};
/// use ot_tools_io::{OctatrackFileIO, OtToolsIoError};
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct Something {
/// value: u8,
/// }
///
/// impl OctatrackFileIO for Something {}
///
/// let x = [10];
///
/// let r = Something::from_bytes(&x);
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap(), Something { value: 10});
/// ```
fn from_bytes(bytes: &[u8]) -> Result<Self, OtToolsIoError>
where
Self: Sized,
Self: for<'a> Deserialize<'a>,
{
bincode::deserialize::<Self>(bytes).map_err(|e| e.into())
}
/// Write type to an Octatrack data file at path
/// ```rust
/// # use std::{path::PathBuf, fs::create_dir_all, env::temp_dir};
/// # let path = temp_dir()
/// # .join("ot-tools-io")
/// # .join("doctest")
/// # .join("to_bytes_file.bank.work");
/// # create_dir_all(&path.parent().unwrap()).unwrap();
/// #
/// use ot_tools_io::{OctatrackFileIO, BankFile};
/// let r = BankFile::default().to_data_file(&path);
/// assert!(r.is_ok());
/// assert!(path.exists());
/// ```
fn to_data_file(&self, path: &Path) -> Result<(), OtToolsIoError> {
let bytes = Self::to_bytes(self)?;
crate::write_bin_file(&bytes, path)?;
Ok(())
}
/// Create bytes from type
/// ```rust
/// // need to create everything from scratch in this example as many bytes otherwise
/// use serde::{Deserialize, Serialize};
/// use ot_tools_io::OctatrackFileIO;
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct Something {
/// value: u8,
/// }
///
/// impl OctatrackFileIO for Something {}
///
/// let x = Something { value: 10 };
/// let r = x.to_bytes();
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap(), [10]);
/// ```
fn to_bytes(&self) -> Result<Vec<u8>, OtToolsIoError>
where
Self: Serialize,
{
Ok(bincode::serialize(&self)?)
}
// YAML
/// Read type from a YAML file at path
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data").join("projects").join("default.yaml");
/// use ot_tools_io::{ProjectFile, OctatrackFileIO};
/// let project = ProjectFile::from_yaml_file(&path).unwrap();
/// assert_eq!(project.metadata.project_version, 19);
/// ```
fn from_yaml_file(path: &Path) -> Result<Self, OtToolsIoError> {
let string = crate::read_str_file(path)?;
let data = Self::from_yaml_str(&string)?;
Ok(data)
}
/// Read type from YAML string
/// ```rust
/// // need to create everything from scratch in this example
/// use serde::{Deserialize, Serialize};
/// use ot_tools_io::OctatrackFileIO;
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct Something {
/// value: u8,
/// }
///
/// impl OctatrackFileIO for Something {}
///
/// let r = Something::from_yaml_str("value: 10\n");
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap(), Something { value: 10 });
/// ```
fn from_yaml_str(yaml: &str) -> Result<Self, OtToolsIoError> {
let x = serde_norway::from_str(yaml)?;
Ok(x)
}
/// Write type to a YAML file at path
/// ```rust
/// # use std::{path::PathBuf, fs::create_dir_all, env::temp_dir};
/// # let path = temp_dir()
/// # .join("ot-tools-io")
/// # .join("doctest")
/// # .join("to_bytes_file.bank.yaml");
/// # create_dir_all(&path.parent().unwrap()).unwrap();
/// #
/// use ot_tools_io::{OctatrackFileIO, BankFile};
/// let r = BankFile::default().to_yaml_file(&path);
/// assert!(r.is_ok());
/// assert!(path.exists());
/// ```
fn to_yaml_file(&self, path: &Path) -> Result<(), OtToolsIoError> {
let yaml = Self::to_yaml_string(self)?;
crate::write_str_file(&yaml, path)?;
Ok(())
}
/// Create YAML string from type
/// ```rust
/// use ot_tools_io::{BankFile, OctatrackFileIO};
/// let bank = BankFile::default().to_yaml_string().unwrap();
/// assert_eq!(bank.len(), 12644761);
/// assert_eq!(bank[0..15], "header:\n- 70\n- ".to_string());
/// ```
fn to_yaml_string(&self) -> Result<String, OtToolsIoError> {
Ok(serde_norway::to_string(self)?)
}
// JSON
/// Read type from a JSON file at path
fn from_json_file(path: &Path) -> Result<Self, OtToolsIoError> {
let string = crate::read_str_file(path)?;
let data = Self::from_json_str(&string)?;
Ok(data)
}
/// Create type from JSON string
/// ```rust
/// // need to create everything from scratch in this example
/// use serde::{Deserialize, Serialize};
/// use ot_tools_io::OctatrackFileIO;
///
/// #[derive(Serialize, Deserialize, Debug, PartialEq)]
/// struct Something {
/// value: u8,
/// }
///
/// impl OctatrackFileIO for Something {}
///
/// let r = Something::from_json_str("{\"value\":10}");
/// assert!(r.is_ok());
/// assert_eq!(r.unwrap(), Something { value: 10 });
/// ```
fn from_json_str(json: &str) -> Result<Self, OtToolsIoError> {
Ok(serde_json::from_str::<Self>(json)?)
}
/// Write type to a JSON file at path
/// ```rust
/// # use std::{path::PathBuf, fs::create_dir_all, env::temp_dir};
/// # let path = temp_dir()
/// # .join("ot-tools-io")
/// # .join("doctest")
/// # .join("to_bytes_file.bank.json");
/// # create_dir_all(&path.parent().unwrap()).unwrap();
/// #
/// use ot_tools_io::{OctatrackFileIO, BankFile};
/// let r = BankFile::default().to_json_file(&path);
/// assert!(r.is_ok());
/// assert!(path.exists());
/// ```
fn to_json_file(&self, path: &Path) -> Result<(), OtToolsIoError> {
let yaml = Self::to_json_string(self)?;
crate::write_str_file(&yaml, path)?;
Ok(())
}
/// Create JSON string from type
/// ```rust
/// use ot_tools_io::{BankFile, OctatrackFileIO};
/// let json = BankFile::default().to_json_string().unwrap();
/// assert_eq!(json.len(), 8089045);
/// assert_eq!(json[0..15], "{\"header\":[70,7".to_string());
/// ```
fn to_json_string(&self) -> Result<String, OtToolsIoError> {
Ok(serde_json::to_string(&self)?)
}
}
/// Trait for adding a method which swaps the bytes on all fields of a struct.
///
/// Useful for handling file writes to a different endianness.
// ```
// use ot_tools_io::SwapBytes;
//
// #[derive(std::fmt::Debug, PartialEq)]
// struct SomeType {
// x: u8,
// y: u32,
// }
//
// impl SwapBytes for SomeType {
// fn swap_bytes(self) -> Self {
// Self {
// x: self.x.swap_bytes(),
// y: self.y.swap_bytes(),
// }
// }
// }
//
// let x = SomeType { x : 8, y: 32857983 };
// let swapped = x.swap_bytes();
// assert_eq!(
// SomeType { x: 8_u8.swap_bytes(), y: 32857983_u32.swap_bytes()},
// swapped,
// );
// ```
pub(crate) trait SwapBytes {
fn swap_bytes(self) -> Self
where
Self: Sized;
}
/// Create a 'default' container type `T` with `N` instances of `Self`.
/// Used when we need a collection of default type instances
/// e.g. when creating a default bank we need 16 default patterns.
///
/// Using the `ot_tools_io_derive::DefaultsAsArray, DefaultsAsArrayBoxed` proc_macro will automatically derive
/// implementations for
/// * `T: [Self; N]`
/// * `T: Box<serde_big_array::Array<Self, N>>`
///
/// If you need to handle incrementing id fields, see the existing examples for the following types
/// * [`crate::patterns::AudioTrackTrigs`],
/// * [`crate::patterns::MidiTrackTrigs`],
/// * [`crate::parts::Part`]
/// * [`crate::parts::AudioTrackMachineSlot`]
///
/// ```
/// use std::array::from_fn;
/// use serde_big_array::Array;
/// use ot_tools_io::Defaults;
///
/// struct SomeType {
/// x: u8,
/// }
///
/// impl Default for SomeType {
/// fn default() -> Self {
/// Self { x: 0 }
/// }
/// }
///
/// impl<const N: usize> Defaults<[SomeType; N]> for SomeType {
/// fn defaults() -> [Self; N] where Self: Default {
/// from_fn(|_| Self::default())
/// }
/// }
///
/// impl<const N: usize> Defaults<Box<Array<SomeType, N>>> for SomeType {
/// fn defaults() -> Box<Array<Self, N>> where Self: Defaults<[Self; N]> {
/// Box::new(Array(
/// // use the [Self; N] impl to generate values
/// <Self as Defaults<[Self; N]>>::defaults()
/// ))
/// }
/// }
///
/// impl<const N: usize> Defaults<Array<SomeType, N>> for SomeType {
/// fn defaults() -> Array<Self, N> where Self: Defaults<[Self; N]> {
/// Array(
/// // use the [Self; N] impl to generate values
/// <Self as Defaults<[Self; N]>>::defaults()
/// )
/// }
/// }
///
/// let xs: [SomeType; 20] = SomeType::defaults();
/// assert_eq!(xs.len(), 20);
///
/// let xs: [SomeType; 25] = SomeType::defaults();
/// assert_eq!(xs.len(), 25);
///
/// let xs: Box<Array<SomeType, 20>> = SomeType::defaults();
/// assert_eq!(xs.len(), 20);
///
/// let xs: Box<Array<SomeType, 25>> = SomeType::defaults();
/// assert_eq!(xs.len(), 25);
///
/// let xs: Array<SomeType, 20> = SomeType::defaults();
/// assert_eq!(xs.len(), 20);
///
/// let xs: Array<SomeType, 25> = SomeType::defaults();
/// assert_eq!(xs.len(), 25);
/// ```
pub trait Defaults<T> {
/// Create an default container type `T` containing `N` default instances of `Self`.
fn defaults() -> T
where
Self: Default;
}
/// Adds a method to check the current data structure matches the default for the type
/// ```rust
/// use ot_tools_io::{IsDefault, BankFile};
///
/// let mut bank = BankFile::default();
/// assert_eq!(bank.is_default(), true);
///
/// bank.datatype_version = 190;
/// assert_eq!(bank.is_default(), false);
/// ```
pub trait IsDefault {
fn is_default(&self) -> bool
where
Self: Default + PartialEq,
{
&Self::default() == self
}
}
/// A type has a checksum field which needs implementations to handle calculation and validation
pub trait HasChecksumField {
/// Method for calculating the checksum value for types that have a checksum field
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{HasChecksumField, OctatrackFileIO, BankFile};
/// let bank = BankFile::from_data_file(&path).unwrap();
/// assert_eq!(bank.checksum, bank.calculate_checksum().unwrap())
/// ```
fn calculate_checksum(&self) -> Result<u16, OtToolsIoError>;
/// Method for updating the checksum value for types that have a checksum field
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{HasChecksumField, OctatrackFileIO, BankFile};
/// let mut bank = BankFile::from_data_file(&path).unwrap();
/// let bank_original_checksum = bank.checksum.clone();
/// bank.parts_edited_bitmask = 2;
/// bank.update_checksum().unwrap();
/// assert_ne!(bank.checksum, bank_original_checksum);
/// ```
fn update_checksum(&mut self) -> Result<(), OtToolsIoError>;
/// Method to verify if checksum is valid in some data type.
/// [See this thread](https://www.elektronauts.com/t/bank-unavailable-octatrack/190647/27).
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{HasChecksumField, OctatrackFileIO, BankFile};
/// // true for valid checksum values
/// assert!(BankFile::from_data_file(&path).unwrap().check_checksum().unwrap())
/// ```
fn check_checksum(&self) -> Result<bool, OtToolsIoError>;
}
/// A type has a header field which needs implementations to handle validation
pub trait HasHeaderField {
/// Method to verify if header(s) are valid in some data.
/// [See this thread](https://www.elektronauts.com/t/bank-unavailable-octatrack/190647/27).
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{HasHeaderField, OctatrackFileIO, BankFile};
/// assert!(BankFile::from_data_file(&path).unwrap().check_header().unwrap()) // true for valid header values
/// ```
// NOTE: ot-tools-io does not validate headers on file read, which means it is
// possible to perform checks like this when a data file has been read.
// otherwise we'd have to do a complicated check to verify headers on every
// file we read, then throw out an error and probably do some complicated
// file (bad header, which patterns, which track within patterns etc.).
fn check_header(&self) -> Result<bool, OtToolsIoError>;
}
/// A type has a file patch version field which needs implementations to handle validation
pub trait HasFileVersionField {
/// Method to verify if the data file version field is valid for the given type.
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{HasFileVersionField, OctatrackFileIO, BankFile};
/// // true for valid version values
/// assert!(BankFile::from_data_file(&path).unwrap().check_file_version().unwrap())
/// ```
// NOTE: ot-tools-io does not validate headers on file read, which means it is
// possible to perform checks like this when a data file has been read.
// otherwise we'd have to do a complicated check to verify headers on every
// file we read, then throw out an error and probably do some complicated
// error handling to explain to the end user exactly why we couldn't load the
// file (bad header, which patterns, which track within patterns etc.).
fn check_file_version(&self) -> Result<bool, OtToolsIoError>;
}
/// Adds a single method using the [`HasHeaderField::check_header`],
/// [`HasChecksumField::check_checksum`] and [`HasFileVersionField::check_file_version`]
/// methods to run a full integrity check.
pub trait CheckFileIntegrity: HasHeaderField + HasChecksumField + HasFileVersionField {
/// ```rust
/// # use std::path::PathBuf;
/// # let path = PathBuf::from("test-data")
/// # .join("blank-project")
/// # .join("bank01.work");
/// use ot_tools_io::{CheckFileIntegrity, OctatrackFileIO, BankFile};
/// // true for valid checksum+header values
/// assert!(BankFile::from_data_file(&path).unwrap().check_integrity().unwrap())
/// ```
fn check_integrity(&self) -> Result<bool, OtToolsIoError> {
Ok(self.check_header()? && self.check_checksum()? && self.check_file_version()?)
}
}