Skip to main content

nativeview_codec/
flat_op_str.rs

1//! Canonical 4-byte-aligned (`u32`-word) UTF-8 string encoding, validation, and decoding helpers
2//! for [`crate::FlatOpFieldType::StrSlice`].
3//!
4//! Wire layout (byte-for-byte identical to `nativeview_store::write_str_words` / `validate_str_words`):
5//! ```text
6//! [byte_len: u32] [utf8_bytes: byte_len] [zero_pad: (4 - (byte_len & 3)) & 3]
7//! ```
8//! occupying `1 + byte_len.div_ceil(4)` little-endian `u32` words. Trailing padding bytes in the
9//! final word MUST be zero so identical payloads hash deterministically under `xxh64`.
10
11use core::fmt;
12
13/// Error returned when validating or decoding a word-padded UTF-8 [`crate::FlatOpFieldType::StrSlice`].
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum FlatOpStrError {
16    /// Input ended before the length prefix or padded payload words.
17    Truncated,
18    /// Encoded byte length exceeded the field's `max_bytes` bound.
19    ExceedsMaxBytes { len: u32, max_bytes: u32 },
20    /// Trailing padding byte(s) in the final 4-byte word were non-zero.
21    NonZeroPadding,
22    /// Payload bytes were not valid UTF-8.
23    InvalidUtf8,
24}
25
26impl fmt::Display for FlatOpStrError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Truncated => f.write_str("truncated flat-op string slice"),
30            Self::ExceedsMaxBytes { len, max_bytes } => {
31                write!(f, "flat-op string length {len} exceeds max_bytes {max_bytes}")
32            }
33            Self::NonZeroPadding => f.write_str("non-zero trailing padding byte in flat-op string slice"),
34            Self::InvalidUtf8 => f.write_str("invalid UTF-8 in flat-op string slice"),
35        }
36    }
37}
38
39impl std::error::Error for FlatOpStrError {}
40
41/// Number of `u32` payload words required for `byte_len` bytes (`ceil(byte_len / 4)`).
42#[inline]
43pub const fn flat_op_str_word_len(byte_len: usize) -> usize {
44    byte_len.div_ceil(4)
45}
46
47/// Bitmask of the trailing padding bytes in the final `u32` word for `byte_len` bytes
48/// (`0` when `byte_len` is already 4-byte aligned).
49#[inline]
50pub const fn flat_op_str_pad_mask(byte_len: usize) -> u32 {
51    let rem = byte_len & 3;
52    if rem == 0 {
53        0
54    } else {
55        !((1u32 << (rem * 8)) - 1)
56    }
57}
58
59/// Padded byte length (multiple of 4) required for `byte_len` bytes, or `None` on overflow.
60#[inline]
61pub const fn flat_op_str_padded_bytes(byte_len: usize) -> Option<usize> {
62    byte_len.div_ceil(4).checked_mul(4)
63}
64
65/// Appends `[byte_len: u32, zero_padded_le_words...]` for raw `bytes` to `out`.
66///
67/// Returns `false` (leaving `out` unchanged) if `bytes.len()` exceeds `max_bytes` or `u32::MAX`.
68#[inline]
69pub fn write_flat_op_bytes_words(out: &mut Vec<u32>, bytes: &[u8], max_bytes: usize) -> bool {
70    let len = bytes.len();
71    if len > max_bytes || len > u32::MAX as usize {
72        return false;
73    }
74    out.reserve(1 + flat_op_str_word_len(len));
75    out.push(len as u32);
76    for_each_padded_le_word(bytes, |w| out.push(w));
77    true
78}
79
80/// Visits `bytes` as little-endian `u32` words, zero-padding the final partial word
81/// (`flat_op_str_word_len(bytes.len())` calls; the payload half of a `StrSlice` block, e.g. for
82/// hashing it without materializing the words). Zero-allocation.
83#[inline]
84pub fn for_each_padded_le_word(bytes: &[u8], mut f: impl FnMut(u32)) {
85    let (chunks, rem) = bytes.as_chunks::<4>();
86    for &chunk in chunks {
87        f(u32::from_le_bytes(chunk));
88    }
89    if !rem.is_empty() {
90        let mut tail = [0u8; 4];
91        tail[..rem.len()].copy_from_slice(rem);
92        f(u32::from_le_bytes(tail));
93    }
94}
95
96/// Appends `[byte_len: u32, zero_padded_utf8_le_words...]` to `out`.
97///
98/// Returns `false` (leaving `out` unchanged) if `text.len()` exceeds `max_bytes`.
99#[inline]
100pub fn write_flat_op_str_words(out: &mut Vec<u32>, text: &str, max_bytes: u32) -> bool {
101    write_flat_op_bytes_words(out, text.as_bytes(), max_bytes as usize)
102}
103
104/// Appends `[byte_len: u32 LE, utf8_bytes..., zero_pad...]` to `out`.
105///
106/// Returns `false` (leaving `out` unchanged) if `text.len()` exceeds `max_bytes`.
107#[inline]
108pub fn write_flat_op_str_bytes(out: &mut Vec<u8>, text: &str, max_bytes: u32) -> bool {
109    let bytes = text.as_bytes();
110    let len = bytes.len();
111    if len > max_bytes as usize {
112        return false;
113    }
114    let Some(padded) = flat_op_str_padded_bytes(len) else {
115        return false;
116    };
117    let Some(total) = padded.checked_add(4) else {
118        return false;
119    };
120    out.reserve(total);
121    out.extend_from_slice(&(len as u32).to_le_bytes());
122    out.extend_from_slice(bytes);
123    let pad = padded - len;
124    if pad != 0 {
125        out.extend_from_slice(&[0u8; 3][..pad]);
126    }
127    true
128}
129
130/// Validates a word-padded UTF-8 string block at `words[*pos]` (enforcing `len <= max_bytes`,
131/// sufficient words, zeroed trailing padding bytes, and strict UTF-8) and advances `*pos` past it.
132///
133/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
134pub fn validate_flat_op_str_words(
135    words: &[u32],
136    pos: &mut usize,
137    max_bytes: u32,
138) -> Result<(), FlatOpStrError> {
139    let (start, end, len) = check_flat_op_bytes_words(words, *pos, max_bytes as usize)?;
140    if len > 0 && !visit_le_words_utf8(&words[start..end], len, |_| {}) {
141        return Err(FlatOpStrError::InvalidUtf8);
142    }
143    *pos = end;
144    Ok(())
145}
146
147/// Validates and decodes a word-padded UTF-8 string block at `words[*pos]` into `out` in a single
148/// pass, clearing `out` first and advancing `*pos` past the block on success.
149///
150/// Leaves `*pos` unchanged on error (clearing `out` if UTF-8 validation fails mid-stream).
151/// Zero-unsafe; allocates zero bytes when `out.capacity() >= byte_len`.
152pub fn read_flat_op_str_words_into(
153    words: &[u32],
154    pos: &mut usize,
155    max_bytes: u32,
156    out: &mut String,
157) -> Result<(), FlatOpStrError> {
158    let (start, end, len) = check_flat_op_bytes_words(words, *pos, max_bytes as usize)?;
159    out.clear();
160    if len > 0 {
161        out.reserve(len);
162        if !visit_le_words_utf8(&words[start..end], len, |chunk| out.push_str(chunk)) {
163            out.clear();
164            return Err(FlatOpStrError::InvalidUtf8);
165        }
166    }
167    *pos = end;
168    Ok(())
169}
170
171/// Validates and decodes a word-padded UTF-8 string block at `words[*pos]` into an owned `String`,
172/// advancing `*pos` past the block on success.
173#[inline]
174pub fn read_flat_op_str_words(
175    words: &[u32],
176    pos: &mut usize,
177    max_bytes: u32,
178) -> Result<String, FlatOpStrError> {
179    let mut out = String::new();
180    read_flat_op_str_words_into(words, pos, max_bytes, &mut out)?;
181    Ok(out)
182}
183
184/// Validates and borrows a zero-copy `&str` from a little-endian byte buffer at `bytes[*pos]`,
185/// advancing `*pos` past the 4-byte-padded block on success.
186///
187/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
188pub fn read_flat_op_str_bytes<'a>(
189    bytes: &'a [u8],
190    pos: &mut usize,
191    max_bytes: u32,
192) -> Result<&'a str, FlatOpStrError> {
193    let mut end = *pos;
194    let payload = read_flat_op_padded_bytes(bytes, &mut end, max_bytes)?;
195    let text = core::str::from_utf8(payload).map_err(|_| FlatOpStrError::InvalidUtf8)?;
196    *pos = end;
197    Ok(text)
198}
199
200/// Validates and borrows the raw payload of a `[byte_len: u32 LE, bytes..., zero_pad...]` block
201/// (the byte form of [`write_flat_op_bytes_words`]) at `bytes[*pos]`, advancing `*pos` past the
202/// 4-byte-padded block on success.
203///
204/// Leaves `*pos` unchanged on error. Zero-unsafe and zero-allocation.
205pub fn read_flat_op_padded_bytes<'a>(
206    bytes: &'a [u8],
207    pos: &mut usize,
208    max_bytes: u32,
209) -> Result<&'a [u8], FlatOpStrError> {
210    let len_end = pos.checked_add(4).ok_or(FlatOpStrError::Truncated)?;
211    let len_slice = bytes.get(*pos..len_end).ok_or(FlatOpStrError::Truncated)?;
212    let len_u32 = u32::from_le_bytes([len_slice[0], len_slice[1], len_slice[2], len_slice[3]]);
213    if len_u32 > max_bytes {
214        return Err(FlatOpStrError::ExceedsMaxBytes {
215            len: len_u32,
216            max_bytes,
217        });
218    }
219    let len = len_u32 as usize;
220    let padded = flat_op_str_padded_bytes(len).ok_or(FlatOpStrError::Truncated)?;
221    let end = len_end.checked_add(padded).ok_or(FlatOpStrError::Truncated)?;
222    let payload = bytes.get(len_end..end).ok_or(FlatOpStrError::Truncated)?;
223    if payload[len..].iter().any(|&b| b != 0) {
224        return Err(FlatOpStrError::NonZeroPadding);
225    }
226    *pos = end;
227    Ok(&payload[..len])
228}
229
230/// Validates a word-padded UTF-8 string block in a little-endian byte buffer at `bytes[*pos]`,
231/// advancing `*pos` past the 4-byte-padded block on success.
232#[inline]
233pub fn validate_flat_op_str_bytes(
234    bytes: &[u8],
235    pos: &mut usize,
236    max_bytes: u32,
237) -> Result<(), FlatOpStrError> {
238    read_flat_op_str_bytes(bytes, pos, max_bytes).map(|_| ())
239}
240
241/// Validates the framing, length bound, bounds, and zero trailing padding of a word-padded byte
242/// block starting at `words[pos]`, returning `(payload_start, block_end, byte_len)` on success.
243#[inline]
244pub fn check_flat_op_bytes_words(
245    words: &[u32],
246    pos: usize,
247    max_bytes: usize,
248) -> Result<(usize, usize, usize), FlatOpStrError> {
249    let &len_u32 = words.get(pos).ok_or(FlatOpStrError::Truncated)?;
250    let len = len_u32 as usize;
251    if len > max_bytes {
252        return Err(FlatOpStrError::ExceedsMaxBytes {
253            len: len_u32,
254            max_bytes: max_bytes.min(u32::MAX as usize) as u32,
255        });
256    }
257    let wc = flat_op_str_word_len(len);
258    let start = pos.checked_add(1).ok_or(FlatOpStrError::Truncated)?;
259    let end = start.checked_add(wc).ok_or(FlatOpStrError::Truncated)?;
260    if end > words.len() {
261        return Err(FlatOpStrError::Truncated);
262    }
263    let pad_mask = flat_op_str_pad_mask(len);
264    if pad_mask != 0 && (words[end - 1] & pad_mask) != 0 {
265        return Err(FlatOpStrError::NonZeroPadding);
266    }
267    Ok((start, end, len))
268}
269
270/// Zero-unsafe, zero-allocation strict UTF-8 streaming validation/decoding of the first
271/// `byte_len` little-endian bytes of `words` via `core::str::from_utf8` over a 256-byte stack
272/// chunk with a 3-byte carry buffer.
273fn visit_le_words_utf8(words: &[u32], byte_len: usize, mut on_chunk: impl FnMut(&str)) -> bool {
274    let mut buf = [0u8; 256];
275    let mut pending = 0usize;
276    let mut remaining = byte_len;
277    let mut word_idx = 0usize;
278
279    while remaining > 0 {
280        let mut filled = pending;
281        while remaining > 0 && filled + 4 <= buf.len() {
282            let w = words[word_idx].to_le_bytes();
283            word_idx += 1;
284            let take = remaining.min(4);
285            buf[filled..filled + take].copy_from_slice(&w[..take]);
286            filled += take;
287            remaining -= take;
288        }
289        match core::str::from_utf8(&buf[..filled]) {
290            Ok(s) => {
291                on_chunk(s);
292                pending = 0;
293            }
294            Err(err) => {
295                if err.error_len().is_some() || remaining == 0 {
296                    return false;
297                }
298                let valid = err.valid_up_to();
299                if valid > 0 {
300                    let Ok(prefix) = core::str::from_utf8(&buf[..valid]) else {
301                        return false;
302                    };
303                    on_chunk(prefix);
304                }
305                let tail = filled - valid;
306                buf.copy_within(valid..filled, 0);
307                pending = tail;
308            }
309        }
310    }
311    pending == 0
312}
313
314#[cfg(test)]
315mod tests {
316    use super::*;
317
318    fn words_to_le_bytes(words: &[u32]) -> Vec<u8> {
319        let mut out = Vec::with_capacity(words.len() * 4);
320        for &w in words {
321            out.extend_from_slice(&w.to_le_bytes());
322        }
323        out
324    }
325
326    #[test]
327    fn roundtrip_empty_ascii_multibyte_bom_and_chunk_boundaries() {
328        let cjk_cross_256 = format!("{}日本語🚀end", "a".repeat(253));
329        let emoji_cross_256_a = format!("{}🚀x", "b".repeat(254));
330        let emoji_cross_256_b = format!("{}🚀y", "c".repeat(255));
331        let long_mixed = "héllo wörld — 日本語 🚀 ".repeat(30);
332
333        let samples: &[&str] = &[
334            "",
335            "a",
336            "ab",
337            "abc",
338            "abcd",
339            "abcde",
340            "hello world",
341            "café",
342            "日本語テスト",
343            "🚀🎉🔥✨",
344            "\u{FEFF}leading bom",
345            &cjk_cross_256,
346            &emoji_cross_256_a,
347            &emoji_cross_256_b,
348            &long_mixed,
349        ];
350
351        for &sample in samples {
352            let max_bytes = sample.len() as u32;
353            let mut words = Vec::new();
354            assert!(write_flat_op_str_words(&mut words, sample, max_bytes));
355            assert_eq!(words.len(), 1 + flat_op_str_word_len(sample.len()));
356            assert_eq!(words[0], sample.len() as u32);
357
358            let mut bytes = Vec::new();
359            assert!(write_flat_op_str_bytes(&mut bytes, sample, max_bytes));
360            assert_eq!(bytes, words_to_le_bytes(&words));
361
362            let mut wpos = 0;
363            assert_eq!(validate_flat_op_str_words(&words, &mut wpos, max_bytes), Ok(()));
364            assert_eq!(wpos, words.len());
365
366            let mut wpos2 = 0;
367            assert_eq!(
368                read_flat_op_str_words(&words, &mut wpos2, max_bytes).as_deref(),
369                Ok(sample)
370            );
371            assert_eq!(wpos2, words.len());
372
373            let mut bpos = 0;
374            assert_eq!(read_flat_op_str_bytes(&bytes, &mut bpos, max_bytes), Ok(sample));
375            assert_eq!(bpos, bytes.len());
376        }
377    }
378
379    #[test]
380    fn max_bytes_exact_and_plus_one_rejected() {
381        let mut words = vec![0xDEAD_BEEF];
382        assert!(!write_flat_op_str_words(&mut words, "abcde", 4));
383        assert_eq!(words, vec![0xDEAD_BEEF], "failed write must leave output untouched");
384
385        let mut bytes = vec![0xAA];
386        assert!(!write_flat_op_str_bytes(&mut bytes, "abcde", 4));
387        assert_eq!(bytes, vec![0xAA], "failed byte write must leave output untouched");
388
389        let mut exact_words = Vec::new();
390        assert!(write_flat_op_str_words(&mut exact_words, "abcd", 4));
391        let exact_bytes = words_to_le_bytes(&exact_words);
392
393        let mut pos = 0;
394        assert_eq!(validate_flat_op_str_words(&exact_words, &mut pos, 4), Ok(()));
395        assert_eq!(pos, 2);
396
397        let mut pos_over = 0;
398        assert_eq!(
399            validate_flat_op_str_words(&exact_words, &mut pos_over, 3),
400            Err(FlatOpStrError::ExceedsMaxBytes { len: 4, max_bytes: 3 })
401        );
402        assert_eq!(pos_over, 0, "error must not advance pos");
403
404        let mut bpos_over = 0;
405        assert_eq!(
406            read_flat_op_str_bytes(&exact_bytes, &mut bpos_over, 3),
407            Err(FlatOpStrError::ExceedsMaxBytes { len: 4, max_bytes: 3 })
408        );
409        assert_eq!(bpos_over, 0);
410
411        // max_bytes == 0 accepts "" and rejects non-empty.
412        let mut empty_w = Vec::new();
413        assert!(write_flat_op_str_words(&mut empty_w, "", 0));
414        let mut p = 0;
415        assert_eq!(read_flat_op_str_words(&empty_w, &mut p, 0).as_deref(), Ok(""));
416        assert!(!write_flat_op_str_words(&mut empty_w, "a", 0));
417    }
418
419    #[test]
420    fn truncated_buffers_and_u32_max_overflow_rejected() {
421        // Empty buffers
422        let mut pos = 0;
423        assert_eq!(validate_flat_op_str_words(&[], &mut pos, 64), Err(FlatOpStrError::Truncated));
424        assert_eq!(read_flat_op_str_bytes(&[], &mut pos, 64), Err(FlatOpStrError::Truncated));
425        assert_eq!(read_flat_op_str_bytes(&[1, 0, 0], &mut pos, 64), Err(FlatOpStrError::Truncated));
426
427        // Length prefix claims 5 bytes (2 words = 8 bytes) but buffer is short
428        let mut words = Vec::new();
429        assert!(write_flat_op_str_words(&mut words, "hello", 64));
430        let bytes = words_to_le_bytes(&words);
431        assert_eq!(words.len(), 3);
432        assert_eq!(bytes.len(), 12);
433
434        for cut_w in 0..words.len() {
435            let mut p = 0;
436            assert_eq!(
437                validate_flat_op_str_words(&words[..cut_w], &mut p, 64),
438                Err(FlatOpStrError::Truncated),
439                "cut_w={cut_w}"
440            );
441            assert_eq!(p, 0);
442        }
443        for cut_b in 0..bytes.len() {
444            let mut p = 0;
445            assert_eq!(
446                read_flat_op_str_bytes(&bytes[..cut_b], &mut p, 64),
447                Err(FlatOpStrError::Truncated),
448                "cut_b={cut_b}"
449            );
450            assert_eq!(p, 0);
451        }
452
453        // u32::MAX overflow rejection (both bounded and max_bytes == u32::MAX)
454        let huge_words = [u32::MAX, 0u32];
455        let huge_bytes = words_to_le_bytes(&huge_words);
456
457        let mut p = 0;
458        assert_eq!(
459            validate_flat_op_str_words(&huge_words, &mut p, 1024),
460            Err(FlatOpStrError::ExceedsMaxBytes {
461                len: u32::MAX,
462                max_bytes: 1024,
463            })
464        );
465        assert_eq!(
466            validate_flat_op_str_words(&huge_words, &mut p, u32::MAX),
467            Err(FlatOpStrError::Truncated)
468        );
469        assert_eq!(
470            read_flat_op_str_bytes(&huge_bytes, &mut p, u32::MAX),
471            Err(FlatOpStrError::Truncated)
472        );
473
474        // pos near usize::MAX never overflows
475        let mut max_pos = usize::MAX;
476        assert_eq!(
477            validate_flat_op_str_words(&words, &mut max_pos, 64),
478            Err(FlatOpStrError::Truncated)
479        );
480        assert_eq!(
481            read_flat_op_str_bytes(&bytes, &mut max_pos, 64),
482            Err(FlatOpStrError::Truncated)
483        );
484    }
485
486    #[test]
487    fn non_zero_padding_rejected_for_every_remainder_slot() {
488        for text in ["a", "ab", "abc", "abcde", "abcdef", "abcdefg"] {
489            let mut words = Vec::new();
490            assert!(write_flat_op_str_words(&mut words, text, 64));
491            let rem = text.len() & 3;
492            assert_ne!(rem, 0);
493            for pad_byte_idx in rem..4 {
494                let mut corrupted = words.clone();
495                let last = corrupted.last_mut().unwrap();
496                *last |= 1u32 << (pad_byte_idx * 8);
497                let corrupted_bytes = words_to_le_bytes(&corrupted);
498
499                let mut wp = 0;
500                assert_eq!(
501                    validate_flat_op_str_words(&corrupted, &mut wp, 64),
502                    Err(FlatOpStrError::NonZeroPadding),
503                    "text={text:?} pad_byte_idx={pad_byte_idx}"
504                );
505                assert_eq!(wp, 0);
506
507                let mut bp = 0;
508                assert_eq!(
509                    read_flat_op_str_bytes(&corrupted_bytes, &mut bp, 64),
510                    Err(FlatOpStrError::NonZeroPadding),
511                    "text={text:?} pad_byte_idx={pad_byte_idx}"
512                );
513                assert_eq!(bp, 0);
514            }
515        }
516    }
517
518    #[test]
519    fn invalid_utf8_sequences_rejected_in_words_and_bytes() {
520        let mut bad_at_boundary = vec![b'a'; 255];
521        bad_at_boundary.extend_from_slice(&[0xE2, 0x28, 0xA1]);
522
523        let cases: &[&[u8]] = &[
524            &[0xFF],
525            &[0x80],
526            &[0xC0, 0xAF],             // overlong 2-byte '/'
527            &[0xC1, 0xBF],             // overlong 2-byte
528            &[0xE0, 0x80, 0xAF],       // overlong 3-byte
529            &[0xED, 0xA0, 0x80],       // UTF-16 high surrogate U+D800
530            &[0xED, 0xBF, 0xBF],       // UTF-16 low surrogate U+DFFF
531            &[0xF0, 0x80, 0x80, 0x80], // overlong 4-byte
532            &[0xF4, 0x90, 0x80, 0x80], // > U+10FFFF
533            &[0xC2],                   // truncated 2-byte
534            &[0xE2, 0x82],             // truncated 3-byte
535            &[0xF0, 0x9F, 0x9A],       // truncated 4-byte
536            &bad_at_boundary,
537        ];
538
539        for &bad in cases {
540            let mut words = vec![bad.len() as u32];
541            let (chunks, rem) = bad.as_chunks::<4>();
542            for &c in chunks {
543                words.push(u32::from_le_bytes(c));
544            }
545            if !rem.is_empty() {
546                let mut tail = [0u8; 4];
547                tail[..rem.len()].copy_from_slice(rem);
548                words.push(u32::from_le_bytes(tail));
549            }
550            let bytes = words_to_le_bytes(&words);
551
552            let mut wp = 0;
553            assert_eq!(
554                validate_flat_op_str_words(&words, &mut wp, 1024),
555                Err(FlatOpStrError::InvalidUtf8),
556                "bad={bad:02X?}"
557            );
558            assert_eq!(wp, 0);
559
560            let mut bp = 0;
561            assert_eq!(
562                read_flat_op_str_bytes(&bytes, &mut bp, 1024),
563                Err(FlatOpStrError::InvalidUtf8),
564                "bad={bad:02X?}"
565            );
566            assert_eq!(bp, 0);
567        }
568    }
569
570    #[test]
571    fn sequential_strings_advance_pos_cleanly() {
572        let mut words = Vec::new();
573        assert!(write_flat_op_str_words(&mut words, "Inter", 64));
574        assert!(write_flat_op_str_words(&mut words, "", 64));
575        assert!(write_flat_op_str_words(&mut words, "Hello 世界 🚀", 64));
576
577        let mut pos = 0;
578        let mut scratch = String::with_capacity(64);
579        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
580        assert_eq!(scratch, "Inter");
581        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
582        assert_eq!(scratch, "");
583        read_flat_op_str_words_into(&words, &mut pos, 64, &mut scratch).unwrap();
584        assert_eq!(scratch, "Hello 世界 🚀");
585        assert_eq!(pos, words.len());
586
587        // Single-pass decode clears partial UTF-8 output and leaves `pos` unchanged on failure.
588        let bad = [4u32, u32::from_le_bytes([b'o', b'k', 0xFF, 0x00])];
589        let mut bad_pos = 0;
590        let mut buf = String::from("stale");
591        assert_eq!(
592            read_flat_op_str_words_into(&bad, &mut bad_pos, 64, &mut buf),
593            Err(FlatOpStrError::InvalidUtf8)
594        );
595        assert_eq!(bad_pos, 0);
596        assert!(buf.is_empty());
597    }
598}