nord-format 0.6.0

Read and write Nord keyboard files from Rust, byte for byte
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
//! The section chains that make up a sample instrument's body.
//!
//! Two framings, one shape. The v2 body is an `NWS` chain of 9-byte-header
//! [`Section`]s; the v3/v4 body is an `NSMP` chain of 12-byte-header
//! [`Section4`]s. Both are flat tag/version/length runs that must land exactly
//! on the end of the body.

use crate::error::{try_vec, ParseError};

/// Bytes of section header: 3-char tag, NUL, `u8` version, `u32` length.
pub const HEADER_LEN: usize = 9;

/// Opens the body. Its payload is empty; the first real section follows it.
pub const CONTAINER: &[u8; 3] = b"NWS";

pub const HDR: &[u8; 3] = b"hdr";
pub const CAT: &[u8; 3] = b"cat";
pub const MAP: &[u8; 3] = b"map";
pub const STK: &[u8; 3] = b"stk";
pub const STY: &[u8; 3] = b"sty";

/// One section of a sample instrument body.
///
/// ⚠️ `len` on the wire is **big-endian**, inside a CBIN header that is little-endian
/// throughout. Reading it the same way as the header's `u32`s yields a nonsense length
/// in the hundreds of millions.
///
/// The length counts the payload only — the 9 header bytes are not included.
#[derive(Clone, PartialEq, Eq)]
pub struct Section {
    pub tag: [u8; 3],
    /// Schema version of this section alone; sections revise independently.
    pub version: u8,
    pub payload: Vec<u8>,
}

impl Section {
    /// Length on disk, header included.
    pub fn encoded_len(&self) -> usize {
        HEADER_LEN + self.payload.len()
    }

    pub fn tag_str(&self) -> String {
        String::from_utf8_lossy(&self.tag).into_owned()
    }

    pub fn is(&self, tag: &[u8; 3]) -> bool {
        &self.tag == tag
    }

    pub fn write_to(&self, w: &mut impl std::io::Write) -> Result<(), ParseError> {
        let len = wire_len(self.payload.len())?;
        let head = |w: &mut dyn std::io::Write| -> std::io::Result<()> {
            w.write_all(&self.tag)?;
            w.write_all(&[0, self.version])?;
            w.write_all(&len.to_be_bytes())?;
            w.write_all(&self.payload)
        };
        head(w).map_err(|e| ParseError::AssertFail(format!("writing a section: {e}")))
    }
}

/// A chain whose first section is not the container that opens it — the leading
/// sections are missing, or the bytes are not a chain at all. Raised before the first
/// declared length is trusted; on a corrupt opener that length is arbitrary.
fn wrong_opener(expected: &[u8], found: &[u8]) -> ParseError {
    ParseError::AssertFail(format!(
        "the body does not open with the {} container section; found {}",
        expected.escape_ascii(),
        found.escape_ascii(),
    ))
}

/// A header whose tag is not NUL-padded. [`Section`] models no field there and
/// [`Section::write_to`] writes 0, so decoding one would drop the byte and
/// write the section back different. Raised with [`wrong_opener`], before the
/// declared length is trusted.
fn unpadded_tag(tag: &[u8], at: u64, found: u8) -> ParseError {
    ParseError::AssertFail(format!(
        "section {} at {at} holds {found} where its tag's padding NUL belongs",
        String::from_utf8_lossy(tag),
    ))
}

fn missing_opener(expected: &[u8]) -> ParseError {
    ParseError::AssertFail(format!(
        "the body does not open with the {} container section; found end of body",
        expected.escape_ascii(),
    ))
}

/// Walks the chain from the reader's position to its end, `remaining` bytes away.
///
/// The chain must open with [`CONTAINER`] and land exactly on the end of the body. Both
/// are strong integrity checks — a wrong length anywhere puts every later section at the
/// wrong offset — so a short or overrunning walk is an error rather than a truncated
/// result.
pub fn read_chain(r: &mut impl std::io::Read, remaining: u64) -> Result<Vec<Section>, ParseError> {
    let mut sections = Vec::new();
    let mut pos: u64 = 0;
    loop {
        let mut head = [0u8; HEADER_LEN];
        if !read_exact_or_end(r, &mut head, pos)? {
            return if pos == 0 {
                Err(missing_opener(CONTAINER))
            } else {
                Ok(sections)
            };
        }
        if pos == 0 && &head[..3] != CONTAINER {
            return Err(wrong_opener(CONTAINER, &head[..3]));
        }
        if head[3] != 0 {
            return Err(unpadded_tag(&head[..3], pos, head[3]));
        }
        let len = u32::from_be_bytes([head[5], head[6], head[7], head[8]]) as usize;
        let end = section_end(pos, HEADER_LEN, len, remaining, &head[..3])?;
        let payload = read_payload(r, len, pos, &head[..3])?;
        pos = end;
        sections.push(Section {
            tag: [head[0], head[1], head[2]],
            version: head[4],
            payload,
        });
    }
}

/// Bytes of a v3/v4 section header: 4-byte tag, `u32` version, `u32` length —
/// the u32s big-endian like the v2 chain's length.
pub const HEADER4_LEN: usize = 12;

/// Opens a v3/v4 body. Its payload is 4 bytes — `0002000c` on every v3
/// specimen, `00020005` on every v4 — constant per generation and unrelated to
/// the stroke count. Meaning open; preserved verbatim.
pub const CONTAINER4: &[u8; 4] = b"NSMP";

/// ⚠️ Three-letter tags are NUL-padded on the *left* in this chain (`\0hdr`),
/// the opposite of the CBIN header's own three-letter tags (`nsp\0`).
pub const HDR4: &[u8; 4] = b"\0hdr";
pub const CAT4: &[u8; 4] = b"\0cat";
pub const MAP4: &[u8; 4] = b"\0map";
pub const STK4: &[u8; 4] = b"\0stk";
pub const STY4: &[u8; 4] = b"\0sty";
/// Trails every v3/v4 specimen, after `sty`.
pub const META4: &[u8; 4] = b"meta";

/// One section of a v3/v4 sample instrument body.
///
/// The `4` is the tag width. Same walk rules as [`Section`]: the length counts
/// the payload only, and the chain must land exactly on the end of the body.
#[derive(Clone, PartialEq, Eq)]
pub struct Section4 {
    pub tag: [u8; 4],
    /// Schema version of this section alone; sections revise independently.
    /// The `map` version — 12/14 on v3 specimens, 21 on v4 — is what selects a
    /// zone-record layout, not the file's content version.
    pub version: u32,
    pub payload: Vec<u8>,
}

impl Section4 {
    /// Length on disk, header included.
    pub fn encoded_len(&self) -> usize {
        HEADER4_LEN + self.payload.len()
    }

    /// The tag without its padding NUL.
    pub fn tag_str(&self) -> String {
        String::from_utf8_lossy(&self.tag)
            .trim_start_matches('\0')
            .to_owned()
    }

    pub fn is(&self, tag: &[u8; 4]) -> bool {
        &self.tag == tag
    }

    pub fn write_to(&self, w: &mut impl std::io::Write) -> Result<(), ParseError> {
        let len = wire_len(self.payload.len())?;
        let head = |w: &mut dyn std::io::Write| -> std::io::Result<()> {
            w.write_all(&self.tag)?;
            w.write_all(&self.version.to_be_bytes())?;
            w.write_all(&len.to_be_bytes())?;
            w.write_all(&self.payload)
        };
        head(w).map_err(|e| ParseError::AssertFail(format!("writing a section: {e}")))
    }
}

/// Walks a v3/v4 chain from the reader's position to its end, under the same
/// open-with-[`CONTAINER4`] and land-exactly rules as [`read_chain`].
pub fn read_chain4(
    r: &mut impl std::io::Read,
    remaining: u64,
) -> Result<Vec<Section4>, ParseError> {
    let mut sections = Vec::new();
    let mut pos: u64 = 0;
    loop {
        let mut head = [0u8; HEADER4_LEN];
        if !read_exact_or_end(r, &mut head, pos)? {
            return if pos == 0 {
                Err(missing_opener(CONTAINER4))
            } else {
                Ok(sections)
            };
        }
        if pos == 0 && &head[..4] != CONTAINER4 {
            return Err(wrong_opener(CONTAINER4, &head[..4]));
        }
        let len = u32::from_be_bytes([head[8], head[9], head[10], head[11]]) as usize;
        let end = section_end(pos, HEADER4_LEN, len, remaining, &head[..4])?;
        let payload = read_payload(r, len, pos, &head[..4])?;
        pos = end;
        sections.push(Section4 {
            tag: [head[0], head[1], head[2], head[3]],
            version: u32::from_be_bytes([head[4], head[5], head[6], head[7]]),
            payload,
        });
    }
}

/// Fills `buf` from `r`, `Ok(false)` on a clean end before the first byte.
/// Bytes that run out mid-buffer are a truncation, not an end.
fn read_exact_or_end(
    r: &mut impl std::io::Read,
    buf: &mut [u8],
    at: u64,
) -> Result<bool, ParseError> {
    let mut got = 0;
    while got < buf.len() {
        match r.read(&mut buf[got..]) {
            Ok(0) if got == 0 => return Ok(false),
            Ok(0) => {
                return Err(ParseError::AssertFail(format!(
                    "truncated section header at {at}"
                )))
            }
            Ok(n) => got += n,
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => continue,
            Err(e) => return Err(ParseError::AssertFail(format!("reading a section: {e}"))),
        }
    }
    Ok(true)
}

/// Where a section starting at `at` ends, refusing a declared length the body
/// cannot hold before it is allocated.
fn section_end(
    at: u64,
    header: usize,
    len: usize,
    remaining: u64,
    tag: &[u8],
) -> Result<u64, ParseError> {
    match at
        .checked_add(header as u64)
        .and_then(|end| end.checked_add(len as u64))
    {
        Some(end) if end <= remaining => Ok(end),
        _ => Err(body_ends_first(tag, at, len)),
    }
}

fn body_ends_first(tag: &[u8], at: u64, len: usize) -> ParseError {
    ParseError::AssertFail(format!(
        "section {} at {at} declares {len} bytes but the body ends first",
        String::from_utf8_lossy(tag),
    ))
}

fn read_payload(
    r: &mut impl std::io::Read,
    len: usize,
    at: u64,
    tag: &[u8],
) -> Result<Vec<u8>, ParseError> {
    let mut payload = try_vec(len)?;
    r.read_exact(&mut payload)
        .map_err(|_| body_ends_first(tag, at, len))?;
    Ok(payload)
}

fn wire_len(len: usize) -> Result<u32, ParseError> {
    u32::try_from(len).map_err(|_| ParseError::OutOfBounds {
        value: format!("{len} payload bytes"),
        bound: "a payload length that fits u32".into(),
    })
}

/// Finds the single v3/v4 section with `tag`.
///
/// ⚠️ The same repeat trap as [`find`]: `stk` repeats, one per stroke.
pub fn find4<'a>(sections: &'a [Section4], tag: &[u8; 4]) -> Option<&'a Section4> {
    sections.iter().find(|s| s.is(tag))
}

pub fn find_mut4<'a>(sections: &'a mut [Section4], tag: &[u8; 4]) -> Option<&'a mut Section4> {
    sections.iter_mut().find(|s| s.is(tag))
}

impl std::fmt::Debug for Section4 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Section4")
            .field("tag", &self.tag_str())
            .field("version", &self.version)
            .field("len", &self.payload.len())
            .finish()
    }
}

/// Finds the single section with `tag`.
///
/// ⚠️ Only for tags that appear at most once. `stk` repeats — one per zone — so it must
/// be collected in order instead; a lookup by tag silently keeps one stroke and drops the
/// rest, and every single-zone file hides that completely.
pub fn find<'a>(sections: &'a [Section], tag: &[u8; 3]) -> Option<&'a Section> {
    sections.iter().find(|s| s.is(tag))
}

pub fn find_mut<'a>(sections: &'a mut [Section], tag: &[u8; 3]) -> Option<&'a mut Section> {
    sections.iter_mut().find(|s| s.is(tag))
}

impl std::fmt::Debug for Section {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Section")
            .field("tag", &self.tag_str())
            .field("version", &self.version)
            .field("len", &self.payload.len())
            .finish()
    }
}

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

    fn walk(body: &[u8]) -> Result<Vec<Section>, ParseError> {
        read_chain(&mut { body }, body.len() as u64)
    }

    fn walk4(body: &[u8]) -> Result<Vec<Section4>, ParseError> {
        read_chain4(&mut { body }, body.len() as u64)
    }

    fn section(tag: &[u8; 3], version: u8, payload: &[u8]) -> Vec<u8> {
        let mut v = tag.to_vec();
        v.push(0);
        v.push(version);
        v.extend_from_slice(&(payload.len() as u32).to_be_bytes());
        v.extend_from_slice(payload);
        v
    }

    #[test]
    fn chain_round_trips() {
        let mut bytes = section(CONTAINER, 11, &[]);
        bytes.extend(section(HDR, 9, &[1, 2, 3]));
        bytes.extend(section(STK, 9, &[4; 20]));

        let chain = walk(&bytes).unwrap();
        assert_eq!(chain.len(), 3);
        assert_eq!(chain[0].payload.len(), 0);
        assert_eq!(chain[1].payload, vec![1, 2, 3]);
        assert_eq!(chain[2].version, 9);

        let mut out = Vec::new();
        for s in &chain {
            s.write_to(&mut out).unwrap();
        }
        assert_eq!(out, bytes);
    }

    /// The empty `NWS` section every v2 body opens with.
    fn opener() -> Vec<u8> {
        section(CONTAINER, 11, &[])
    }

    #[test]
    fn length_is_big_endian() {
        // 0x00000102 = 258 read big-endian; little-endian would be 0x02010000.
        let mut bytes = opener();
        bytes.extend(section(HDR, 1, &[0; 258]));
        let chain = walk(&bytes).unwrap();
        assert_eq!(chain[1].payload.len(), 258);
    }

    #[test]
    fn a_length_past_the_end_of_the_body_is_refused_without_allocating_it() {
        let mut one_over = section(HDR, 1, &[7; 4]);
        one_over[5..9].copy_from_slice(&5u32.to_be_bytes());
        let mut bytes = opener();
        bytes.extend(one_over);
        assert_eq!(
            walk(&bytes).unwrap_err().to_string(),
            "section hdr at 9 declares 5 bytes but the body ends first"
        );

        let mut huge = section(HDR, 1, &[7; 4]);
        huge[5..9].copy_from_slice(&u32::MAX.to_be_bytes());
        let mut bytes = opener();
        bytes.extend(huge);
        assert_eq!(
            walk(&bytes).unwrap_err().to_string(),
            format!(
                "section hdr at 9 declares {} bytes but the body ends first",
                u32::MAX
            )
        );
    }

    #[test]
    fn trailing_bytes_are_an_error() {
        let mut bytes = opener();
        bytes.extend(section(HDR, 1, &[7; 4]));
        bytes.extend_from_slice(&[0, 0, 0]); // not enough for another header
        assert!(walk(&bytes).is_err());
    }

    #[test]
    fn a_chain_not_opening_with_its_container_names_the_expected_tag() {
        let bytes = section(HDR, 1, &[7; 4]);
        assert_eq!(
            walk(&bytes).unwrap_err().to_string(),
            "the body does not open with the NWS container section; found hdr"
        );

        let bytes = section4(HDR4, 1, &[7; 4]);
        assert_eq!(
            walk4(&bytes).unwrap_err().to_string(),
            "the body does not open with the NSMP container section; found \\x00hdr"
        );
    }

    #[test]
    fn an_empty_body_reports_its_missing_container() {
        assert_eq!(
            walk(&[]).unwrap_err().to_string(),
            "the body does not open with the NWS container section; found end of body"
        );
        assert_eq!(
            walk4(&[]).unwrap_err().to_string(),
            "the body does not open with the NSMP container section; found end of body"
        );
    }

    /// The byte behind the tag is modelled by no field, so a section carrying
    /// one cannot be written back as it came.
    #[test]
    fn a_tag_not_padded_with_a_nul_is_refused() {
        let mut hdr = section(HDR, 1, &[7; 4]);
        hdr[3] = 2;
        let mut bytes = opener();
        bytes.extend(hdr);
        assert_eq!(
            walk(&bytes).unwrap_err().to_string(),
            "section hdr at 9 holds 2 where its tag's padding NUL belongs"
        );
    }

    #[test]
    fn a_corrupt_opener_is_reported_before_its_length() {
        // A garbage tag's "length" is arbitrary: big-endian 0xfeffff3e here.
        let bytes = [0x00, 0x00, 0x00, 0x00, 0xff, 0xfe, 0xff, 0xff, 0x3e];
        assert_eq!(
            walk(&bytes).unwrap_err().to_string(),
            "the body does not open with the NWS container section; found \\x00\\x00\\x00"
        );
    }

    fn section4(tag: &[u8; 4], version: u32, payload: &[u8]) -> Vec<u8> {
        let mut v = tag.to_vec();
        v.extend_from_slice(&version.to_be_bytes());
        v.extend_from_slice(&(payload.len() as u32).to_be_bytes());
        v.extend_from_slice(payload);
        v
    }

    #[test]
    fn chain4_round_trips() {
        let mut bytes = section4(CONTAINER4, 30, &[0, 2, 0, 0x0c]);
        bytes.extend(section4(HDR4, 10, &[1; 112]));
        bytes.extend(section4(STK4, 11, &[4; 20]));

        let chain = walk4(&bytes).unwrap();
        assert_eq!(chain.len(), 3);
        assert_eq!(chain[0].payload.len(), 4);
        assert_eq!(chain[1].version, 10);
        assert_eq!(chain[2].tag_str(), "stk");

        let mut out = Vec::new();
        for s in &chain {
            s.write_to(&mut out).unwrap();
        }
        assert_eq!(out, bytes);
    }

    #[test]
    fn chain4_overrun_and_truncation_are_errors() {
        let opener4 = || section4(CONTAINER4, 30, &[0, 2, 0, 0x0c]);

        let mut hdr = section4(HDR4, 1, &[7; 4]);
        hdr[8..12].copy_from_slice(&u32::MAX.to_be_bytes());
        let mut bytes = opener4();
        bytes.extend(hdr);
        assert!(walk4(&bytes).is_err());

        let mut bytes = opener4();
        bytes.extend(section4(HDR4, 1, &[7; 4]));
        bytes.extend_from_slice(&[0; 5]); // not enough for another header
        assert!(walk4(&bytes).is_err());
    }

    #[cfg(target_pointer_width = "64")]
    #[test]
    fn a_section_writer_refuses_lengths_that_do_not_fit_the_wire() {
        assert_eq!(wire_len(u32::MAX as usize).unwrap(), u32::MAX);
        assert!(wire_len(u32::MAX as usize + 1).is_err());
    }

    #[test]
    fn repeated_tags_are_all_kept() {
        let mut bytes = opener();
        bytes.extend(section(STK, 9, &[1]));
        bytes.extend(section(STK, 9, &[2]));
        bytes.extend(section(STK, 9, &[3]));
        let chain = walk(&bytes).unwrap();
        assert_eq!(chain.len(), 4);
        assert_eq!(
            chain[1..].iter().map(|s| s.payload[0]).collect::<Vec<_>>(),
            vec![1, 2, 3]
        );
    }
}