ctb_formats_wtf8/
wtf8.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later AND MIT
2// SPDX-License-Identifier for parts derived from mathiasbynens/wtf-8: MIT
3/*
4This file is part of Collective Toolbox, a database and document workspace and utilities.
5Copyright (C) 2026 Collective Toolbox Developers
6Contact: info@collectivetoolbox.com
7
8This program is free software: you can redistribute it and/or modify it under
9the terms of the GNU Affero General Public License as published by the Free
10Software Foundation, either version 3 of the License, or (at your option) any
11later version.
12
13This program is distributed in the hope that it will be useful, but WITHOUT ANY
14WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
16
17You should have received a copy of the GNU Affero General Public License along
18with this program.  If not, see <https://www.gnu.org/licenses/>.
19*/
20
21/* Copyright © Mathias Bynens <https://mathiasbynens.be/> */
22
23// Based on <https://web.archive.org/web/20190305073920/https://github.com/mathiasbynens/wtf-8/blob/58c6b976c6678144d180b2307bee5615457e2cc7/wtf-8.js>
24// This code for wtf8 is included under the following license (from https://web.archive.org/web/20190305074047/https://github.com/mathiasbynens/wtf-8/blob/58c6b976c6678144d180b2307bee5615457e2cc7/LICENSE-MIT.txt):
25/*
26Copyright Mathias Bynens <https://mathiasbynens.be/>
27
28Permission is hereby granted, free of charge, to any person obtaining
29a copy of this software and associated documentation files (the
30"Software"), to deal in the Software without restriction, including
31without limitation the rights to use, copy, modify, merge, publish,
32distribute, sublicense, and/or sell copies of the Software, and to
33permit persons to whom the Software is furnished to do so, subject to
34the following conditions:
35
36The above copyright notice and this permission notice shall be
37included in all copies or substantial portions of the Software.
38
39THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
40EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
41MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
42NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
43LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
44OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
45WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
46*/
47
48//! Utilities for WTF-8 encoding and decoding.
49//! Reference: <https://simonsapin.github.io/wtf-8>/
50//! See also the standard library version:
51//! <https://doc.rust-lang.org/src/std/sys_common/wtf8.rs.html>
52//!
53//! TODO?: This could have some more optional features added for other uses:
54//! - Allow encoding of values above U+10FFFF (up to U+7FFFFFFF) as 6-byte
55//!   sequences.
56//! - Allow retaining surrogates unpaired when encoding, in which case it would
57//!   be CESU-8 implementation.
58
59#[allow(
60    unused_imports,
61    clippy::wildcard_imports,
62    reason = "Standard workspace crate prelude"
63)]
64pub(crate) use ctb_utilities::*;
65
66use anyhow::{Context, Result, ensure};
67use ctb_utilities::circular_dep_unicode::{
68    ucs2decode, ucs2encode, unpaired_surrogates_to_scalars,
69};
70
71/// Encode a single Unicode codepoint as WTF-8 byte array.
72/// Returns a `Vec<u8>` containing the WTF-8 encoding of the codepoint.
73/// Surrogates and non-scalar values are encoded as WTF-8 allows.
74/// Values higher than 0x10FFFF are not supported.
75pub fn encode_wtf8_single(int_value: u32) -> Result<Vec<u8>> {
76    ensure!(
77        int_value <= 0x10FFFF,
78        format!("WTF-8: Codepoint {int_value} out of range")
79    );
80    fn create_byte(int_value: u32, shift: u32) -> Result<u8> {
81        u8::try_from(((int_value >> shift) & 0x3F) | 0x80)
82            .context("Failed to create byte")
83    }
84
85    let mut symbol = Vec::new();
86    if (int_value & 0xFFFFFF80) == 0 {
87        // 1-byte sequence
88        symbol.push(u8::try_from(int_value).context("Failed to create byte")?);
89    } else {
90        if (int_value & 0xFFFFF800) == 0 {
91            // 2-byte sequence
92            symbol.push(
93                u8::try_from((int_value >> 6) & 0x1F | 0xC0)
94                    .context("Failed to create byte")?,
95            );
96        } else if (int_value & 0xFFFF0000) == 0 {
97            // 3-byte sequence
98            symbol.push(
99                u8::try_from((int_value >> 12) & 0x0F | 0xE0)
100                    .context("Failed to create byte")?,
101            );
102            symbol.push(create_byte(int_value, 6)?);
103        } else if (int_value & 0xFFE00000) == 0 {
104            // 4-byte sequence
105            symbol.push(
106                u8::try_from((int_value >> 18) & 0x07 | 0xF0)
107                    .context("Failed to create byte")?,
108            );
109            symbol.push(create_byte(int_value, 12)?);
110            symbol.push(create_byte(int_value, 6)?);
111        }
112        symbol.push(
113            u8::try_from((int_value & 0x3F) | 0x80)
114                .context("Failed to create byte")?,
115        );
116    }
117    Ok(symbol)
118}
119
120/// More concise `encode_wtf8` using `ucs2decode/encode_wtf8_single` logic.
121/// Encodes a slice of Unicode scalar codepoints to WTF-8 bytes.
122/// Surrogate pairs are combined and encoded as a single codepoint.
123/// Unpaired surrogates are encoded as 3-byte WTF-8 sequences.
124/// Values higher than 0x10FFFF are not supported.
125pub fn encode_wtf8_from_scalars(codepoints: &[u32]) -> Result<Vec<u8>> {
126    let mut out = Vec::new();
127    let mut i = 0;
128    while i < codepoints.len() {
129        let cp = *codepoints.get(i).context("Invalid codepoint index")?;
130        // Check for surrogate pair
131        if (0xD800..=0xDBFF).contains(&cp)
132            && i.saturating_add(1) < codepoints.len()
133        {
134            let next = *codepoints
135                .get(i.saturating_add(1))
136                .context("Invalid surrogate pair index")?;
137            if (0xDC00..=0xDFFF).contains(&next) {
138                // Combine surrogate pair
139                let high = cp;
140                let low = next;
141                let full = 0x10000u32.saturating_add(
142                    ((high.saturating_sub(0xD800)) << 10)
143                        | (low.saturating_sub(0xDC00)),
144                );
145                out.extend(encode_wtf8_single(full)?);
146                i = i.saturating_add(2);
147                continue;
148            }
149        }
150        // Otherwise, encode as single codepoint
151        out.extend(encode_wtf8_single(cp)?);
152        i = i.saturating_add(1);
153    }
154    Ok(out)
155}
156
157/// WTF-8 encode a UTF-16/UCS-2/JS string (as &[u16]) into `Vec<u8>`.
158/// Uses ucs2decode to convert to codepoints, then encodes as WTF-8.
159pub fn encode_wtf8_from_ucs2(ucs2: &[u16]) -> Result<Vec<u8>> {
160    let codepoints = ucs2decode(ucs2);
161    encode_wtf8_from_scalars(codepoints.as_slice())
162}
163
164fn read_continuation_byte(input: &[u8], byte_index: &mut usize) -> Result<u8> {
165    if *byte_index >= input.len() {
166        return Err(anyhow::anyhow!("WTF-8: Invalid byte index"));
167    }
168    let continuation_byte = *input
169        .get(*byte_index)
170        .context("WTF-8: Invalid byte index")?;
171    *byte_index = byte_index.saturating_add(1);
172    if (continuation_byte & 0xC0) == 0x80 {
173        Ok(continuation_byte & 0x3F)
174    } else {
175        // If we end up here, it’s not a continuation byte.
176        Err(anyhow::anyhow!("WTF-8: Invalid continuation byte"))
177    }
178}
179
180/// Decode one WTF-8 codepoint from a byte array slice.
181/// Returns Ok((codepoint, length)) or Err on error.
182pub fn decode_wtf8_single(
183    byte_array_input: &[u8],
184) -> anyhow::Result<(u32, usize), anyhow::Error> {
185    let mut byte_index = 0;
186    let byte_count = byte_array_input.len();
187
188    if byte_index > byte_count {
189        return Err(anyhow::anyhow!("Invalid WTF-8 sequence"));
190    }
191    if byte_index == byte_count {
192        return Err(anyhow::anyhow!(
193            "The original WTF-8 returned false here, not sure why"
194        ));
195    }
196
197    let byte1 = *byte_array_input
198        .get(byte_index)
199        .context("Invalid WTF-8 sequence")?;
200    byte_index = byte_index.saturating_add(1);
201
202    // 1-byte sequence (no continuation bytes)
203    if (byte1 & 0x80) == 0 {
204        return Ok((u32::from(byte1), 1));
205    }
206
207    // 2-byte sequence
208    if (byte1 & 0xE0) == 0xC0 {
209        let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
210        let int_value = (u32::from(byte1 & 0x1F) << 6) | u32::from(byte2);
211        if int_value >= 0x80 {
212            return Ok((int_value, 2));
213        }
214        return Err(anyhow::anyhow!("WTF-8: Invalid 2-byte sequence"));
215    }
216
217    // 3-byte sequence (may include unpaired surrogates)
218    if (byte1 & 0xF0) == 0xE0 {
219        let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
220        let byte3 = read_continuation_byte(byte_array_input, &mut byte_index)?;
221        let int_value = (u32::from(byte1 & 0x0F) << 12)
222            | (u32::from(byte2) << 6)
223            | u32::from(byte3);
224        if int_value >= 0x0800 {
225            return Ok((int_value, 3));
226        }
227        return Err(anyhow::anyhow!("WTF-8: Invalid 3-byte sequence"));
228    }
229
230    // 4-byte sequence
231    if (byte1 & 0xF8) == 0xF0 {
232        let byte2 = read_continuation_byte(byte_array_input, &mut byte_index)?;
233        let byte3 = read_continuation_byte(byte_array_input, &mut byte_index)?;
234        let byte4 = read_continuation_byte(byte_array_input, &mut byte_index)?;
235        let int_value = (u32::from(byte1 & 0x0F)) << 18
236            | (u32::from(byte2)) << 12
237            | (u32::from(byte3)) << 6
238            | u32::from(byte4);
239        if (0x010000..=0x10FFFF).contains(&int_value) {
240            return Ok((int_value, 4));
241        }
242    }
243
244    Err(anyhow::anyhow!("WTF-8: Invalid 4-byte sequence"))
245}
246
247/// Decode a WTF-8 byte array into a `Vec<u16>` (UCS-2).
248pub fn decode_wtf8_to_ucs2(byte_array_input: &[u8]) -> Result<Vec<u16>> {
249    let mut codepoints_with_unpaired_surrogates: Vec<u16> = Vec::new();
250    let mut byte_index = 0;
251    while byte_index < byte_array_input.len() {
252        let sub_slice = byte_array_input
253            .get(byte_index..)
254            .context("WTF-8: Invalid byte index")?;
255        let (cp, len) = decode_wtf8_single(sub_slice).context(format!(
256            "WTF-8: Invalid byte sequence at index {byte_index}"
257        ))?;
258        if cp > 0xFFFF {
259            let surrogates = ucs2encode(&[cp]).context(format!(
260                "WTF-8: Failed to convert codepoint to unpaired surrogates: {cp:?}"
261            ))?;
262            codepoints_with_unpaired_surrogates.extend(surrogates);
263        } else {
264            codepoints_with_unpaired_surrogates
265                .push(u16::try_from(cp).context("Failed to create u16")?);
266        }
267        byte_index = byte_index.saturating_add(len);
268    }
269
270    Ok(codepoints_with_unpaired_surrogates)
271}
272
273/// Decode a WTF-8 byte array into a `Vec<u16>` (UCS-2).
274pub fn decode_wtf8_to_scalars(byte_array_input: &[u8]) -> Result<Vec<u32>> {
275    let codepoints_with_unpaired_surrogates =
276        decode_wtf8_to_ucs2(byte_array_input)
277            .context("WTF-8: Failed to decode to UCS-2")?;
278    let codepoints_as_u32: Vec<u32> = codepoints_with_unpaired_surrogates
279        .iter()
280        .map(|&cp| u32::from(cp))
281        .collect();
282    Ok(unpaired_surrogates_to_scalars(&codepoints_as_u32))
283}
284
285/// Returns true if the given slice is a valid WTF-8 single codepoint sequence.
286pub fn is_unpackable_wtf8(byte_array_input: &[u8]) -> bool {
287    decode_wtf8_single(byte_array_input).is_ok()
288}
289
290#[cfg(test)]
291#[allow(
292    clippy::panic,
293    clippy::expect_used,
294    clippy::unwrap_used,
295    clippy::unwrap_in_result,
296    clippy::panic_in_result_fn,
297    clippy::indexing_slicing,
298    clippy::arithmetic_side_effects,
299    reason = "Standard repository test boilerplate"
300)]
301mod tests {
302    use ctb_utilities::circular_dep_unicode::{
303        UNICODE_HISTORIC_MAX, UNICODE_MAX,
304    };
305
306    use super::*;
307
308    // Based on https://github.com/mathiasbynens/wtf-8/blob/bdab8ed45a2446eddffae28d27b353bb817189c5/tests/tests.js
309
310    struct TestCase {
311        decoded: &'static [u16],
312        encoded: &'static [u8],
313        description: &'static str,
314    }
315
316    #[crate::ctb_test]
317    fn test_wtf8_encode_decode() -> Result<()> {
318        let cases = [
319            // 1-byte
320            TestCase {
321                decoded: &[0x0000],
322                encoded: b"\0",
323                description: "U+0000",
324            },
325            TestCase {
326                decoded: &[0x005C],
327                encoded: b"\x5C",
328                description: "U+005C",
329            },
330            TestCase {
331                decoded: &[0x007F],
332                encoded: b"\x7F",
333                description: "U+007F",
334            },
335            // 2-byte
336            TestCase {
337                decoded: &[0x0080],
338                encoded: &[0xC2, 0x80],
339                description: "U+0080",
340            },
341            TestCase {
342                decoded: &[0x05CA],
343                encoded: &[0xD7, 0x8A],
344                description: "U+05CA",
345            },
346            TestCase {
347                decoded: &[0x07FF],
348                encoded: &[0xDF, 0xBF],
349                description: "U+07FF",
350            },
351            // 3-byte
352            TestCase {
353                decoded: &[0x0800],
354                encoded: &[0xE0, 0xA0, 0x80],
355                description: "U+0800",
356            },
357            TestCase {
358                decoded: &[0x2C3C],
359                encoded: &[0xE2, 0xB0, 0xBC],
360                description: "U+2C3C",
361            },
362            TestCase {
363                decoded: &[0xFFFF],
364                encoded: &[0xEF, 0xBF, 0xBF],
365                description: "U+FFFF",
366            },
367            // Unmatched surrogate halves
368
369            // high surrogates: 0xD800 to 0xDBFF
370            TestCase {
371                decoded: &[0xD800],
372                encoded: &[0xED, 0xA0, 0x80],
373                description: "U+D800",
374            },
375            TestCase {
376                decoded: &[0xD800, 0xD800],
377                encoded: &[0xED, 0xA0, 0x80, 0xED, 0xA0, 0x80],
378                description: "High surrogate followed by another high surrogate",
379            },
380            TestCase {
381                decoded: &[0xD800, 0x41_u16],
382                encoded: &[0xED, 0xA0, 0x80, b'A'],
383                description: "High surrogate followed by a symbol that is not a surrogate",
384            },
385            TestCase {
386                decoded: &[0xD800, 0xD834, 0xDF06, 0xD800],
387                encoded: &[
388                    0xED, 0xA0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xA0, 0x80,
389                ],
390                description: "Unmatched high surrogate, followed by a surrogate pair, followed by an unmatched high surrogate",
391            },
392            TestCase {
393                decoded: &[0xD9AF],
394                encoded: &[0xED, 0xA6, 0xAF],
395                description: "U+D9AF",
396            },
397            TestCase {
398                decoded: &[0xDBFF],
399                encoded: &[0xED, 0xAF, 0xBF],
400                description: "U+DBFF",
401            },
402            // low surrogates: 0xDC00 to 0xDFFF
403            TestCase {
404                decoded: &[0xDC00],
405                encoded: &[0xED, 0xB0, 0x80],
406                description: "U+DC00",
407            },
408            TestCase {
409                decoded: &[0xDC00, 0xDC00],
410                encoded: &[0xED, 0xB0, 0x80, 0xED, 0xB0, 0x80],
411                description: "Low surrogate followed by another low surrogate",
412            },
413            TestCase {
414                decoded: &[0xDC00, 0x41_u16],
415                encoded: &[0xED, 0xB0, 0x80, b'A'],
416                description: "Low surrogate followed by a symbol that is not a surrogate",
417            },
418            TestCase {
419                decoded: &[0xDC00, 0xD834, 0xDF06, 0xDC00],
420                encoded: &[
421                    0xED, 0xB0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xB0, 0x80,
422                ],
423                description: "Unmatched low surrogate, followed by a surrogate pair, followed by an unmatched low surrogate",
424            },
425            TestCase {
426                decoded: &[0xDEEE],
427                encoded: &[0xED, 0xBB, 0xAE],
428                description: "U+DEEE",
429            },
430            TestCase {
431                decoded: &[0xDFFF],
432                encoded: &[0xED, 0xBF, 0xBF],
433                description: "U+DFFF",
434            },
435            // 4-byte
436            TestCase {
437                // 0x010000 as surrogates
438                decoded: &[0xD800, 0xDC00],
439                encoded: &[0xF0, 0x90, 0x80, 0x80],
440                description: "U+10000",
441            },
442            TestCase {
443                // 0x01D306 as surrogates
444                decoded: &[0xD834, 0xDF06],
445                encoded: &[0xF0, 0x9D, 0x8C, 0x86],
446                description: "U+1D306",
447            },
448            TestCase {
449                // 0x10FFFF as surrogates
450                decoded: &[0xDBFF, 0xDFFF],
451                encoded: &[0xF4, 0x8F, 0xBF, 0xBF],
452                description: "U+10FFFF",
453            },
454        ];
455        for case in &cases {
456            // Encode
457            let encoded = encode_wtf8_from_ucs2(case.decoded)?;
458            assert_eq!(encoded, case.encoded, "Encoding: {}", case.description);
459            // Decode
460            let decoded = decode_wtf8_to_ucs2(case.encoded);
461            if let Ok(decoded) = &decoded {
462                assert_eq!(
463                    decoded.as_slice(),
464                    case.decoded,
465                    "Decoding: {}, encoded: {:?}, decoded: {:?}, expected: {:?}",
466                    case.description,
467                    case.encoded,
468                    decoded,
469                    case.decoded
470                );
471            } else {
472                panic!(
473                    "Decoding error for case '{}':\n  error: {:?}\n  encoded: {:?}\n  expected decoded: {:?}",
474                    case.description,
475                    decoded.err(),
476                    case.encoded,
477                    case.decoded,
478                );
479            }
480        }
481        Ok(())
482    }
483
484    #[crate::ctb_test]
485    fn test_wtf8_decode_errors() {
486        // Invalid WTF-8 detected
487        decode_wtf8_single(&[0xFF]).unwrap_err();
488        // Invalid continuation byte (4-byte sequence expected)
489        decode_wtf8_single(&[0xE9, 0x00, 0x00]).unwrap_err();
490        // Invalid continuation byte
491        decode_wtf8_single(&[0xC2, 0xFF, 0xFF]).unwrap_err();
492        decode_wtf8_single(&[0xC2, 0xEF, 0xBF, 0xBF]).unwrap_err();
493        // Invalid byte index
494        decode_wtf8_single(&[0xF0, 0x9D]).unwrap_err();
495        decode_wtf8_to_scalars(&[0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
496            .unwrap_err(); // UNICODE_HISTORIC_MAX
497    }
498
499    #[crate::ctb_test]
500    fn test_encode_wtf8_single_basic() {
501        // 1-byte
502        assert_eq!(encode_wtf8_single(0x00).unwrap(), vec![0x00]);
503        assert_eq!(encode_wtf8_single(0x7F).unwrap(), vec![0x7F]);
504        // 2-byte
505        assert_eq!(encode_wtf8_single(0x80).unwrap(), vec![0xC2, 0x80]);
506        assert_eq!(encode_wtf8_single(0x7FF).unwrap(), vec![0xDF, 0xBF]);
507        // 3-byte
508        assert_eq!(encode_wtf8_single(0x800).unwrap(), vec![0xE0, 0xA0, 0x80]);
509        assert_eq!(encode_wtf8_single(0xFFFF).unwrap(), vec![0xEF, 0xBF, 0xBF]);
510        // 4-byte
511        assert_eq!(
512            encode_wtf8_single(0x10000).unwrap(),
513            vec![0xF0, 0x90, 0x80, 0x80]
514        );
515        assert_eq!(
516            encode_wtf8_single(UNICODE_MAX).unwrap(),
517            vec![0xF4, 0x8F, 0xBF, 0xBF]
518        );
519        encode_wtf8_single(UNICODE_HISTORIC_MAX).unwrap_err();
520    }
521
522    #[crate::ctb_test]
523    fn test_encode_wtf8_from_scalars_surrogates() {
524        // Unpaired high surrogate
525        assert_eq!(
526            encode_wtf8_from_scalars(&[0xD800]).unwrap(),
527            vec![0xED, 0xA0, 0x80]
528        );
529        // Surrogate pair
530        assert_eq!(
531            encode_wtf8_from_scalars(&[0xD834, 0xDF06]).unwrap(),
532            vec![0xF0, 0x9D, 0x8C, 0x86]
533        );
534        // Mixed
535        assert_eq!(
536            encode_wtf8_from_scalars(&[0xD800, 0xD834, 0xDF06, 0xD800])
537                .unwrap(),
538            vec![0xED, 0xA0, 0x80, 0xF0, 0x9D, 0x8C, 0x86, 0xED, 0xA0, 0x80]
539        );
540    }
541
542    #[crate::ctb_test]
543    fn test_decode_wtf8_to_scalars_basic() {
544        // 1-byte
545        assert_eq!(decode_wtf8_to_scalars(&[0x00]).unwrap(), vec![0x00]);
546        // 2-byte
547        assert_eq!(decode_wtf8_to_scalars(&[0xC2, 0x80]).unwrap(), vec![0x80]);
548        // 3-byte
549        assert_eq!(
550            decode_wtf8_to_scalars(&[0xE0, 0xA0, 0x80]).unwrap(),
551            vec![0x800]
552        );
553        // 4-byte
554        assert_eq!(
555            decode_wtf8_to_scalars(&[0xF0, 0x90, 0x80, 0x80]).unwrap(),
556            vec![0x10000]
557        );
558        assert_eq!(
559            decode_wtf8_to_scalars(&[0xF4, 0x8F, 0xBF, 0xBF]).unwrap(),
560            vec![UNICODE_MAX]
561        );
562        decode_wtf8_to_scalars(&[0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF])
563            .unwrap_err();
564    }
565
566    #[crate::ctb_test]
567    fn test_is_unpackable_wtf8() {
568        assert!(is_unpackable_wtf8(&[0x00]));
569        assert!(is_unpackable_wtf8(b"AAAA"));
570        assert!(is_unpackable_wtf8(&[b'A', b'A', b'A', 0xE0, 0xA0, 0x80]));
571        assert!(is_unpackable_wtf8(&[0xE0, 0xA0, 0x80, b'A', b'A', b'A']));
572        assert!(is_unpackable_wtf8(&[0xC2, 0x80]));
573        assert!(is_unpackable_wtf8(&[0xE0, 0xA0, 0x80]));
574        assert!(is_unpackable_wtf8(&[0xF0, 0x90, 0x80, 0x80]));
575        assert!(!is_unpackable_wtf8(&[0xC2])); // incomplete
576        assert!(!is_unpackable_wtf8(&[0xF0, 0x90])); // incomplete
577        assert!(!is_unpackable_wtf8(&[0xFF])); // invalid
578    }
579}