nativeview-codec 0.1.0-rc.1

Zero-unsafe, zero-runtime-dependency Tier-2 little-endian binary codec primitives and #[derive(NvCodec)]
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
//! Canonical 4-byte-aligned (`u32`-word) UTF-8 string encoding, validation, and decoding helpers
//! for [`crate::FlatOpFieldType::StrSlice`].
//!
//! Wire layout (byte-for-byte identical to `nativeview_store::write_str_words` / `validate_str_words`):
//! ```text
//! [byte_len: u32] [utf8_bytes: byte_len] [zero_pad: (4 - (byte_len & 3)) & 3]
//! ```
//! occupying `1 + byte_len.div_ceil(4)` little-endian `u32` words. Trailing padding bytes in the
//! final word MUST be zero so identical payloads hash deterministically under `xxh64`.

use core::fmt;

/// Error returned when validating or decoding a word-padded UTF-8 [`crate::FlatOpFieldType::StrSlice`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum FlatOpStrError {
    /// Input ended before the length prefix or padded payload words.
    Truncated,
    /// Encoded byte length exceeded the field's `max_bytes` bound.
    ExceedsMaxBytes { len: u32, max_bytes: u32 },
    /// Trailing padding byte(s) in the final 4-byte word were non-zero.
    NonZeroPadding,
    /// Payload bytes were not valid UTF-8.
    InvalidUtf8,
}

impl fmt::Display for FlatOpStrError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Truncated => f.write_str("truncated flat-op string slice"),
            Self::ExceedsMaxBytes { len, max_bytes } => {
                write!(f, "flat-op string length {len} exceeds max_bytes {max_bytes}")
            }
            Self::NonZeroPadding => f.write_str("non-zero trailing padding byte in flat-op string slice"),
            Self::InvalidUtf8 => f.write_str("invalid UTF-8 in flat-op string slice"),
        }
    }
}

impl std::error::Error for FlatOpStrError {}

/// Number of `u32` payload words required for `byte_len` bytes (`ceil(byte_len / 4)`).
#[inline]
pub const fn flat_op_str_word_len(byte_len: usize) -> usize {
    byte_len.div_ceil(4)
}

/// Bitmask of the trailing padding bytes in the final `u32` word for `byte_len` bytes
/// (`0` when `byte_len` is already 4-byte aligned).
#[inline]
pub const fn flat_op_str_pad_mask(byte_len: usize) -> u32 {
    let rem = byte_len & 3;
    if rem == 0 {
        0
    } else {
        !((1u32 << (rem * 8)) - 1)
    }
}

/// Padded byte length (multiple of 4) required for `byte_len` bytes, or `None` on overflow.
#[inline]
pub const fn flat_op_str_padded_bytes(byte_len: usize) -> Option<usize> {
    byte_len.div_ceil(4).checked_mul(4)
}

/// Appends `[byte_len: u32, zero_padded_le_words...]` for raw `bytes` to `out`.
///
/// Returns `false` (leaving `out` unchanged) if `bytes.len()` exceeds `max_bytes` or `u32::MAX`.
#[inline]
pub fn write_flat_op_bytes_words(out: &mut Vec<u32>, bytes: &[u8], max_bytes: usize) -> bool {
    let len = bytes.len();
    if len > max_bytes || len > u32::MAX as usize {
        return false;
    }
    out.reserve(1 + flat_op_str_word_len(len));
    out.push(len as u32);
    for_each_padded_le_word(bytes, |w| out.push(w));
    true
}

/// Visits `bytes` as little-endian `u32` words, zero-padding the final partial word
/// (`flat_op_str_word_len(bytes.len())` calls; the payload half of a `StrSlice` block, e.g. for
/// hashing it without materializing the words). Zero-allocation.
#[inline]
pub fn for_each_padded_le_word(bytes: &[u8], mut f: impl FnMut(u32)) {
    let (chunks, rem) = bytes.as_chunks::<4>();
    for &chunk in chunks {
        f(u32::from_le_bytes(chunk));
    }
    if !rem.is_empty() {
        let mut tail = [0u8; 4];
        tail[..rem.len()].copy_from_slice(rem);
        f(u32::from_le_bytes(tail));
    }
}

/// Appends `[byte_len: u32, zero_padded_utf8_le_words...]` to `out`.
///
/// Returns `false` (leaving `out` unchanged) if `text.len()` exceeds `max_bytes`.
#[inline]
pub fn write_flat_op_str_words(out: &mut Vec<u32>, text: &str, max_bytes: u32) -> bool {
    write_flat_op_bytes_words(out, text.as_bytes(), max_bytes as usize)
}

/// Appends `[byte_len: u32 LE, utf8_bytes..., zero_pad...]` to `out`.
///
/// Returns `false` (leaving `out` unchanged) if `text.len()` exceeds `max_bytes`.
#[inline]
pub fn write_flat_op_str_bytes(out: &mut Vec<u8>, text: &str, max_bytes: u32) -> bool {
    let bytes = text.as_bytes();
    let len = bytes.len();
    if len > max_bytes as usize {
        return false;
    }
    let Some(padded) = flat_op_str_padded_bytes(len) else {
        return false;
    };
    let Some(total) = padded.checked_add(4) else {
        return false;
    };
    out.reserve(total);
    out.extend_from_slice(&(len as u32).to_le_bytes());
    out.extend_from_slice(bytes);
    let pad = padded - len;
    if pad != 0 {
        out.extend_from_slice(&[0u8; 3][..pad]);
    }
    true
}

/// Validates a word-padded UTF-8 string block at `words[*pos]` (enforcing `len <= max_bytes`,
/// sufficient words, zeroed trailing padding bytes, and strict UTF-8) and advances `*pos` past it.
///
/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
pub fn validate_flat_op_str_words(
    words: &[u32],
    pos: &mut usize,
    max_bytes: u32,
) -> Result<(), FlatOpStrError> {
    let (start, end, len) = check_flat_op_bytes_words(words, *pos, max_bytes as usize)?;
    if len > 0 && !visit_le_words_utf8(&words[start..end], len, |_| {}) {
        return Err(FlatOpStrError::InvalidUtf8);
    }
    *pos = end;
    Ok(())
}

/// Validates and decodes a word-padded UTF-8 string block at `words[*pos]` into `out` in a single
/// pass, clearing `out` first and advancing `*pos` past the block on success.
///
/// Leaves `*pos` unchanged on error (clearing `out` if UTF-8 validation fails mid-stream).
/// Zero-unsafe; allocates zero bytes when `out.capacity() >= byte_len`.
pub fn read_flat_op_str_words_into(
    words: &[u32],
    pos: &mut usize,
    max_bytes: u32,
    out: &mut String,
) -> Result<(), FlatOpStrError> {
    let (start, end, len) = check_flat_op_bytes_words(words, *pos, max_bytes as usize)?;
    out.clear();
    if len > 0 {
        out.reserve(len);
        if !visit_le_words_utf8(&words[start..end], len, |chunk| out.push_str(chunk)) {
            out.clear();
            return Err(FlatOpStrError::InvalidUtf8);
        }
    }
    *pos = end;
    Ok(())
}

/// Validates and decodes a word-padded UTF-8 string block at `words[*pos]` into an owned `String`,
/// advancing `*pos` past the block on success.
#[inline]
pub fn read_flat_op_str_words(
    words: &[u32],
    pos: &mut usize,
    max_bytes: u32,
) -> Result<String, FlatOpStrError> {
    let mut out = String::new();
    read_flat_op_str_words_into(words, pos, max_bytes, &mut out)?;
    Ok(out)
}

/// Validates and borrows a zero-copy `&str` from a little-endian byte buffer at `bytes[*pos]`,
/// advancing `*pos` past the 4-byte-padded block on success.
///
/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
pub fn read_flat_op_str_bytes<'a>(
    bytes: &'a [u8],
    pos: &mut usize,
    max_bytes: u32,
) -> Result<&'a str, FlatOpStrError> {
    let mut end = *pos;
    let payload = read_flat_op_padded_bytes(bytes, &mut end, max_bytes)?;
    let text = core::str::from_utf8(payload).map_err(|_| FlatOpStrError::InvalidUtf8)?;
    *pos = end;
    Ok(text)
}

/// Validates and borrows the raw payload of a `[byte_len: u32 LE, bytes..., zero_pad...]` block
/// (the byte form of [`write_flat_op_bytes_words`]) at `bytes[*pos]`, advancing `*pos` past the
/// 4-byte-padded block on success.
///
/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
pub fn read_flat_op_padded_bytes<'a>(
    bytes: &'a [u8],
    pos: &mut usize,
    max_bytes: u32,
) -> Result<&'a [u8], FlatOpStrError> {
    let len_end = pos.checked_add(4).ok_or(FlatOpStrError::Truncated)?;
    let len_slice = bytes.get(*pos..len_end).ok_or(FlatOpStrError::Truncated)?;
    let len_u32 = u32::from_le_bytes([len_slice[0], len_slice[1], len_slice[2], len_slice[3]]);
    if len_u32 > max_bytes {
        return Err(FlatOpStrError::ExceedsMaxBytes {
            len: len_u32,
            max_bytes,
        });
    }
    let len = len_u32 as usize;
    let padded = flat_op_str_padded_bytes(len).ok_or(FlatOpStrError::Truncated)?;
    let end = len_end.checked_add(padded).ok_or(FlatOpStrError::Truncated)?;
    let payload = bytes.get(len_end..end).ok_or(FlatOpStrError::Truncated)?;
    if payload[len..].iter().any(|&b| b != 0) {
        return Err(FlatOpStrError::NonZeroPadding);
    }
    *pos = end;
    Ok(&payload[..len])
}

/// Validates a word-padded UTF-8 string block in a little-endian byte buffer at `bytes[*pos]`,
/// advancing `*pos` past the 4-byte-padded block on success.
#[inline]
pub fn validate_flat_op_str_bytes(
    bytes: &[u8],
    pos: &mut usize,
    max_bytes: u32,
) -> Result<(), FlatOpStrError> {
    read_flat_op_str_bytes(bytes, pos, max_bytes).map(|_| ())
}

/// Validates the framing, length bound, bounds, and zero trailing padding of a word-padded byte
/// block starting at `words[pos]`, returning `(payload_start, block_end, byte_len)` on success.
#[inline]
pub fn check_flat_op_bytes_words(
    words: &[u32],
    pos: usize,
    max_bytes: usize,
) -> Result<(usize, usize, usize), FlatOpStrError> {
    let &len_u32 = words.get(pos).ok_or(FlatOpStrError::Truncated)?;
    let len = len_u32 as usize;
    if len > max_bytes {
        return Err(FlatOpStrError::ExceedsMaxBytes {
            len: len_u32,
            max_bytes: max_bytes.min(u32::MAX as usize) as u32,
        });
    }
    let wc = flat_op_str_word_len(len);
    let start = pos.checked_add(1).ok_or(FlatOpStrError::Truncated)?;
    let end = start.checked_add(wc).ok_or(FlatOpStrError::Truncated)?;
    if end > words.len() {
        return Err(FlatOpStrError::Truncated);
    }
    let pad_mask = flat_op_str_pad_mask(len);
    if pad_mask != 0 && (words[end - 1] & pad_mask) != 0 {
        return Err(FlatOpStrError::NonZeroPadding);
    }
    Ok((start, end, len))
}

/// Zero-unsafe, zero-allocation strict UTF-8 streaming validation/decoding of the first
/// `byte_len` little-endian bytes of `words` via `core::str::from_utf8` over a 256-byte stack
/// chunk with a 3-byte carry buffer.
fn visit_le_words_utf8(words: &[u32], byte_len: usize, mut on_chunk: impl FnMut(&str)) -> bool {
    let mut buf = [0u8; 256];
    let mut pending = 0usize;
    let mut remaining = byte_len;
    let mut word_idx = 0usize;

    while remaining > 0 {
        let mut filled = pending;
        while remaining > 0 && filled + 4 <= buf.len() {
            let w = words[word_idx].to_le_bytes();
            word_idx += 1;
            let take = remaining.min(4);
            buf[filled..filled + take].copy_from_slice(&w[..take]);
            filled += take;
            remaining -= take;
        }
        match core::str::from_utf8(&buf[..filled]) {
            Ok(s) => {
                on_chunk(s);
                pending = 0;
            }
            Err(err) => {
                if err.error_len().is_some() || remaining == 0 {
                    return false;
                }
                let valid = err.valid_up_to();
                if valid > 0 {
                    let Ok(prefix) = core::str::from_utf8(&buf[..valid]) else {
                        return false;
                    };
                    on_chunk(prefix);
                }
                let tail = filled - valid;
                buf.copy_within(valid..filled, 0);
                pending = tail;
            }
        }
    }
    pending == 0
}

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

    fn words_to_le_bytes(words: &[u32]) -> Vec<u8> {
        let mut out = Vec::with_capacity(words.len() * 4);
        for &w in words {
            out.extend_from_slice(&w.to_le_bytes());
        }
        out
    }

    #[test]
    fn roundtrip_empty_ascii_multibyte_bom_and_chunk_boundaries() {
        let cjk_cross_256 = format!("{}ζ—₯本θͺžπŸš€end", "a".repeat(253));
        let emoji_cross_256_a = format!("{}πŸš€x", "b".repeat(254));
        let emoji_cross_256_b = format!("{}πŸš€y", "c".repeat(255));
        let long_mixed = "hΓ©llo wΓΆrld β€” ζ—₯本θͺž πŸš€ ".repeat(30);

        let samples: &[&str] = &[
            "",
            "a",
            "ab",
            "abc",
            "abcd",
            "abcde",
            "hello world",
            "cafΓ©",
            "ζ—₯本θͺžγƒ†γ‚Ήγƒˆ",
            "πŸš€πŸŽ‰πŸ”₯✨",
            "\u{FEFF}leading bom",
            &cjk_cross_256,
            &emoji_cross_256_a,
            &emoji_cross_256_b,
            &long_mixed,
        ];

        for &sample in samples {
            let max_bytes = sample.len() as u32;
            let mut words = Vec::new();
            assert!(write_flat_op_str_words(&mut words, sample, max_bytes));
            assert_eq!(words.len(), 1 + flat_op_str_word_len(sample.len()));
            assert_eq!(words[0], sample.len() as u32);

            let mut bytes = Vec::new();
            assert!(write_flat_op_str_bytes(&mut bytes, sample, max_bytes));
            assert_eq!(bytes, words_to_le_bytes(&words));

            let mut wpos = 0;
            assert_eq!(validate_flat_op_str_words(&words, &mut wpos, max_bytes), Ok(()));
            assert_eq!(wpos, words.len());

            let mut wpos2 = 0;
            assert_eq!(
                read_flat_op_str_words(&words, &mut wpos2, max_bytes).as_deref(),
                Ok(sample)
            );
            assert_eq!(wpos2, words.len());

            let mut bpos = 0;
            assert_eq!(read_flat_op_str_bytes(&bytes, &mut bpos, max_bytes), Ok(sample));
            assert_eq!(bpos, bytes.len());
        }
    }

    #[test]
    fn max_bytes_exact_and_plus_one_rejected() {
        let mut words = vec![0xDEAD_BEEF];
        assert!(!write_flat_op_str_words(&mut words, "abcde", 4));
        assert_eq!(words, vec![0xDEAD_BEEF], "failed write must leave output untouched");

        let mut bytes = vec![0xAA];
        assert!(!write_flat_op_str_bytes(&mut bytes, "abcde", 4));
        assert_eq!(bytes, vec![0xAA], "failed byte write must leave output untouched");

        let mut exact_words = Vec::new();
        assert!(write_flat_op_str_words(&mut exact_words, "abcd", 4));
        let exact_bytes = words_to_le_bytes(&exact_words);

        let mut pos = 0;
        assert_eq!(validate_flat_op_str_words(&exact_words, &mut pos, 4), Ok(()));
        assert_eq!(pos, 2);

        let mut pos_over = 0;
        assert_eq!(
            validate_flat_op_str_words(&exact_words, &mut pos_over, 3),
            Err(FlatOpStrError::ExceedsMaxBytes { len: 4, max_bytes: 3 })
        );
        assert_eq!(pos_over, 0, "error must not advance pos");

        let mut bpos_over = 0;
        assert_eq!(
            read_flat_op_str_bytes(&exact_bytes, &mut bpos_over, 3),
            Err(FlatOpStrError::ExceedsMaxBytes { len: 4, max_bytes: 3 })
        );
        assert_eq!(bpos_over, 0);

        // max_bytes == 0 accepts "" and rejects non-empty.
        let mut empty_w = Vec::new();
        assert!(write_flat_op_str_words(&mut empty_w, "", 0));
        let mut p = 0;
        assert_eq!(read_flat_op_str_words(&empty_w, &mut p, 0).as_deref(), Ok(""));
        assert!(!write_flat_op_str_words(&mut empty_w, "a", 0));
    }

    #[test]
    fn truncated_buffers_and_u32_max_overflow_rejected() {
        // Empty buffers
        let mut pos = 0;
        assert_eq!(validate_flat_op_str_words(&[], &mut pos, 64), Err(FlatOpStrError::Truncated));
        assert_eq!(read_flat_op_str_bytes(&[], &mut pos, 64), Err(FlatOpStrError::Truncated));
        assert_eq!(read_flat_op_str_bytes(&[1, 0, 0], &mut pos, 64), Err(FlatOpStrError::Truncated));

        // Length prefix claims 5 bytes (2 words = 8 bytes) but buffer is short
        let mut words = Vec::new();
        assert!(write_flat_op_str_words(&mut words, "hello", 64));
        let bytes = words_to_le_bytes(&words);
        assert_eq!(words.len(), 3);
        assert_eq!(bytes.len(), 12);

        for cut_w in 0..words.len() {
            let mut p = 0;
            assert_eq!(
                validate_flat_op_str_words(&words[..cut_w], &mut p, 64),
                Err(FlatOpStrError::Truncated),
                "cut_w={cut_w}"
            );
            assert_eq!(p, 0);
        }
        for cut_b in 0..bytes.len() {
            let mut p = 0;
            assert_eq!(
                read_flat_op_str_bytes(&bytes[..cut_b], &mut p, 64),
                Err(FlatOpStrError::Truncated),
                "cut_b={cut_b}"
            );
            assert_eq!(p, 0);
        }

        // u32::MAX overflow rejection (both bounded and max_bytes == u32::MAX)
        let huge_words = [u32::MAX, 0u32];
        let huge_bytes = words_to_le_bytes(&huge_words);

        let mut p = 0;
        assert_eq!(
            validate_flat_op_str_words(&huge_words, &mut p, 1024),
            Err(FlatOpStrError::ExceedsMaxBytes {
                len: u32::MAX,
                max_bytes: 1024,
            })
        );
        assert_eq!(
            validate_flat_op_str_words(&huge_words, &mut p, u32::MAX),
            Err(FlatOpStrError::Truncated)
        );
        assert_eq!(
            read_flat_op_str_bytes(&huge_bytes, &mut p, u32::MAX),
            Err(FlatOpStrError::Truncated)
        );

        // pos near usize::MAX never overflows
        let mut max_pos = usize::MAX;
        assert_eq!(
            validate_flat_op_str_words(&words, &mut max_pos, 64),
            Err(FlatOpStrError::Truncated)
        );
        assert_eq!(
            read_flat_op_str_bytes(&bytes, &mut max_pos, 64),
            Err(FlatOpStrError::Truncated)
        );
    }

    #[test]
    fn non_zero_padding_rejected_for_every_remainder_slot() {
        for text in ["a", "ab", "abc", "abcde", "abcdef", "abcdefg"] {
            let mut words = Vec::new();
            assert!(write_flat_op_str_words(&mut words, text, 64));
            let rem = text.len() & 3;
            assert_ne!(rem, 0);
            for pad_byte_idx in rem..4 {
                let mut corrupted = words.clone();
                let last = corrupted.last_mut().unwrap();
                *last |= 1u32 << (pad_byte_idx * 8);
                let corrupted_bytes = words_to_le_bytes(&corrupted);

                let mut wp = 0;
                assert_eq!(
                    validate_flat_op_str_words(&corrupted, &mut wp, 64),
                    Err(FlatOpStrError::NonZeroPadding),
                    "text={text:?} pad_byte_idx={pad_byte_idx}"
                );
                assert_eq!(wp, 0);

                let mut bp = 0;
                assert_eq!(
                    read_flat_op_str_bytes(&corrupted_bytes, &mut bp, 64),
                    Err(FlatOpStrError::NonZeroPadding),
                    "text={text:?} pad_byte_idx={pad_byte_idx}"
                );
                assert_eq!(bp, 0);
            }
        }
    }

    #[test]
    fn invalid_utf8_sequences_rejected_in_words_and_bytes() {
        let mut bad_at_boundary = vec![b'a'; 255];
        bad_at_boundary.extend_from_slice(&[0xE2, 0x28, 0xA1]);

        let cases: &[&[u8]] = &[
            &[0xFF],
            &[0x80],
            &[0xC0, 0xAF],             // overlong 2-byte '/'
            &[0xC1, 0xBF],             // overlong 2-byte
            &[0xE0, 0x80, 0xAF],       // overlong 3-byte
            &[0xED, 0xA0, 0x80],       // UTF-16 high surrogate U+D800
            &[0xED, 0xBF, 0xBF],       // UTF-16 low surrogate U+DFFF
            &[0xF0, 0x80, 0x80, 0x80], // overlong 4-byte
            &[0xF4, 0x90, 0x80, 0x80], // > U+10FFFF
            &[0xC2],                   // truncated 2-byte
            &[0xE2, 0x82],             // truncated 3-byte
            &[0xF0, 0x9F, 0x9A],       // truncated 4-byte
            &bad_at_boundary,
        ];

        for &bad in cases {
            let mut words = vec![bad.len() as u32];
            let (chunks, rem) = bad.as_chunks::<4>();
            for &c in chunks {
                words.push(u32::from_le_bytes(c));
            }
            if !rem.is_empty() {
                let mut tail = [0u8; 4];
                tail[..rem.len()].copy_from_slice(rem);
                words.push(u32::from_le_bytes(tail));
            }
            let bytes = words_to_le_bytes(&words);

            let mut wp = 0;
            assert_eq!(
                validate_flat_op_str_words(&words, &mut wp, 1024),
                Err(FlatOpStrError::InvalidUtf8),
                "bad={bad:02X?}"
            );
            assert_eq!(wp, 0);

            let mut bp = 0;
            assert_eq!(
                read_flat_op_str_bytes(&bytes, &mut bp, 1024),
                Err(FlatOpStrError::InvalidUtf8),
                "bad={bad:02X?}"
            );
            assert_eq!(bp, 0);
        }
    }

    #[test]
    fn sequential_strings_advance_pos_cleanly() {
        let mut words = Vec::new();
        assert!(write_flat_op_str_words(&mut words, "Inter", 64));
        assert!(write_flat_op_str_words(&mut words, "", 64));
        assert!(write_flat_op_str_words(&mut words, "Hello δΈ–η•Œ πŸš€", 64));

        let mut pos = 0;
        let mut scratch = String::with_capacity(64);
        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
        assert_eq!(scratch, "Inter");
        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
        assert_eq!(scratch, "");
        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
        assert_eq!(scratch, "Hello δΈ–η•Œ πŸš€");
        assert_eq!(pos, words.len());

        // Single-pass decode clears partial UTF-8 output and leaves `pos` unchanged on failure.
        let bad = [4u32, u32::from_le_bytes([b'o', b'k', 0xFF, 0x00])];
        let mut bad_pos = 0;
        let mut buf = String::from("stale");
        assert_eq!(
            read_flat_op_str_words_into(&bad, &mut bad_pos, 64, &mut buf),
            Err(FlatOpStrError::InvalidUtf8)
        );
        assert_eq!(bad_pos, 0);
        assert!(buf.is_empty());
    }
}