Expand description
Permissive UTF-8 / UTF-16 / UTF-32 transcoding, comparison and BOM detection, with SIMD ASCII fast paths.
A Rust port of the xstd::codepoint_cvt / utf_* family. Design points
carried over:
- Permissive, non-validating codecs. Decoding never fails: truncated
UTF-8 sequences decode to
0(consuming the remainder), lone surrogates pass through, garbage-in produces garbage-out. Values are rawu32codepoints, notchar. - ASCII-only case folding for the
*_ignore_ascii_caseoperations andAsciiCasetranscoding. - Foreign endianness as a type parameter:
Utf16<true>is byte-swapped relative to the native byte order (seeUtf16Be/Utf16Lealiases). - Terminal text primitives, allocation-free and generic over the
encoding: grapheme segmentation (
graphemes, UAX #29 incl.GB9cand GB11) with double-ended, exact-length iterators, visible cell width (width), width truncation (truncate), greedy word wrap (wrap), and SIMD ANSI/VT stripping in place (MakeAnsiStripped,IntoAnsiStripped). TheTextextension trait exposes them as methods onstrand native code-unit slices. Unicode properties come from the generatedUNICODE_VERSIONtrie (scripts/gen_props.py). - Scalar property lookups: NFC/NFD normalization with a SIMD quick-check
(
ToUnicodeNormalized,is_nfc), plus permissiveGeneral_Category(general_category,general_category_group) and UAX #24 script (script) — the lookup surface of theunicode-normalization,unicode-propertiesandunicode-scriptcrates from one table family, also asUcdmethods onchar/u32. - Strict stream decoding from any
std::io::BufRead(BufReadCharsExt): batch-decodedchariteration in every supported encoding, with errors that carry the offending bytes (ReadCharError). Drop-in compatible with (and considerably faster than) theutf8-charscrate. - Method-level entry points for the codec itself:
Text::transcodeinfers the target encoding from the container it fills (TextBuf),Text::eq_textcompares across encodings, andEncoding::from_bytesdecodes a BOM-tagged byte stream into that encoding’sContainer.
Special-op mapping from the C++ original:
C++ (xstd) | Rust |
|---|---|
clang vector extensions (xvec) | core::simd (LLVM vector IR) |
bit_pdep / bit_pext (BMI2) | _pdep_u32 / _pext_u32 under cfg(bmi2) |
assume(..) | core::hint::assert_unchecked |
bswapw / bswapd | u16::swap_bytes / u32::swap_bytes |
lsb(mask()) | Mask::to_bitmask().trailing_zeros() |
| overlapped tail vector load/store | Simd::from_slice / copy_to_slice on an |
overlapping window at limit - N |
Deliberate fixes over the original:
- UTF-16 encode computes the low surrogate as
0xDC00 | (cp & 0x3FF); the C++0xDC00 | uint16_t(cp)corrupts pairs when bit 13 ofcp - 0x10000is set (e.g. U+12000). compareorders by decoded codepoint everywhere (the C++ mixed UTF-16 code-unit order with codepoint order) and a longer string with a trailingNULcodepoint no longer compares equal to its prefix.
Structs§
- Chars
- Iterator over the chars of a
BufRead, yieldingio::Result<char>. - Chars
Raw - Iterator over the chars of a
BufRead, yieldingResult<char, ReadCharError>. - Codepoints
- Iterator over the raw codepoints of an encoded slice.
- Grapheme
- A borrowed extended grapheme cluster and its terminal cell width.
- Grapheme
Indices - Allocation-free double-ended iterator over extended grapheme clusters and their code-unit offsets.
- Graphemes
- Allocation-free double-ended iterator over extended grapheme clusters.
- Normalization
Error - Reports the workspace capacity needed for allocation-free normalization.
- Read
Char Error - Bytes read from a stream that failed to decode, plus the
io::Errorclassifying the failure. - StrGrapheme
Indices - Double-ended, exact-length iterator over a UTF-8 string’s grapheme clusters and byte offsets.
- StrGraphemes
- Double-ended, exact-length iterator over the extended grapheme clusters of
a UTF-8 string, yielding borrowed sub-strings. Created by
graphemes_str. - StrWrapped
- Iterator of wrapped
&strlines, created bywrap_str. - Utf8
- UTF-8. Byte-oriented, so there is no foreign-endianness variant.
- Utf16
- UTF-16.
FOREIGNselects byte order opposite to native (seeUtf16Le/Utf16Be). - Utf32
- UTF-32.
FOREIGNselects byte order opposite to native (seeUtf32Le/Utf32Be). - Wrapped
- Iterator of wrapped lines, created by
wrap. - Wrapped
Line - A borrowed wrapped subline with its position and terminal cell width.
- Wrapped
Measured - Iterator of wrapped lines with source offsets and visible widths, created
by
wrap_measured.
Enums§
- Ascii
Case - ASCII case transform applied while transcoding.
- Bom
- Byte order mark at the head of a raw byte stream.
- General
Category General_Categoryproperty value (UAX #44), e.g.\p{Lu}.- General
Category Group - The seven
General_Categorygroups:\p{L},\p{M},\p{N},\p{P},\p{S},\p{Z},\p{C}. - Kind
- Encoding family, used to detect “same encoding” fast paths at monomorphization time.
- Script
- Script property values (UAX #24) of UCD 17.0.0.
Constants§
- UNICODE_
VERSION - Unicode version of the generated property tables.
Traits§
- BufRead
Chars Ext - Extends
BufReadwith strict char decoding, batch-accelerated over the reader’s internal buffer. - Encoding
- A UTF encoding: a stateless codec between raw
u32codepoints and code units. - Into
Ansi Stripped - Converts an owned string into ANSI/VT-free text without reallocating.
- Into
Unicode Normalized - Converts an owned string to NFC or NFD while reusing its allocation.
- Make
Ansi Stripped - Compacts ANSI/VT-free text into a mutable code-unit slice view.
- Make
Unicode Normalized - Normalizes a string in place without allocating.
- Stream
Decode - An encoding whose chars can be strictly decoded from a byte stream.
- Text
- Terminal text primitives as methods on
strand native code-unit slices. - TextBuf
- Owned destination of
Text::transcode; pins the target encoding through its code-unit type. - ToAnsi
Stripped - Creates an ANSI/VT-free owned string from a borrowed string.
- ToUnicode
Normalized - Creates owned NFC or NFD text from a borrowed string.
- Ucd
general_category,general_category_groupandscriptas methods on the scalar itself.- Unit
- A UTF code unit:
u8(UTF-8),u16(UTF-16) oru32(UTF-32).
Functions§
- canonical_
combining_ class - Canonical Combining Class (ccc) of a codepoint; 0 for starters, out-of-range input and unassigned codepoints.
- chars
- Iterates
inputaschars, substituting U+FFFD for unit sequences that decode to invalid scalar values. - codepoints
- Iterates the raw (unvalidated) codepoints of
input. - compare
- Compares two encoded strings in codepoint order.
- compare_
ignore_ ascii_ case comparewith ASCII-only case folding (utf_icompare).- detect_
bom - Detects a BOM, returning it plus the byte length to skip.
- equals
- Codepoint equality across encodings (
utf_cmpeq). - equals_
ignore_ ascii_ case equalswith ASCII-only case folding (utf_icmpeq).- from_
bytes - Identifies the encoding of a raw byte stream from its BOM (defaulting to
UTF-8) and transcodes it to
T. - general_
category General_Categoryof a codepoint.- general_
category_ group general_categoryreduced to its group: the\p{L}/\p{N}/\p{M}classes of the reference tokenizer regexes in one lookup.- grapheme_
indices - Iterates the extended grapheme clusters of an encoded slice with their code-unit offsets.
- grapheme_
indices_ str - Iterates a UTF-8 string’s extended grapheme clusters with their byte offsets.
- graphemes
- Iterates the extended grapheme clusters of an encoded slice without allocating.
- graphemes_
str - Iterates the extended grapheme clusters of a UTF-8 string as borrowed strings.
- is_nfc
- Reports whether
textis definitely in NFC form. - is_
nfc_ codepoints is_nfcover raw codepoints, for callers holding non-UTF-8 text (UTF-16/UTF-32 units) who want the quick-check without transcoding.- script
- Script property of a codepoint (UAX #24), e.g.
\p{Han}. - skip_
columns - Tail of
inputafter dropping enough whole clusters to covercolumnsterminal cells, together with the exact dropped width. - skip_
columns_ str skip_columnsover UTF-8str.- to_
string - Transcodes to an owned
String. - transcode
- Transcodes all of
srcinto a freshly allocated unit vector. - transcode_
into - Transcodes as much of
srcintodstas fits, returning(units_read, units_written). Never splits a codepoint: encoding stops at the last codepoint whose output fits. - transcode_
with_ case transcodewith ASCII case folding.- transcoded_
len - Unit count
srcwould occupy once transcoded toT(utf_length). - truncate
- Longest prefix of
inputno wider thanmax_widthterminal cells, cut on an extended grapheme cluster boundary. - truncate_
measured - Longest prefix of
inputno wider thanmax_widthterminal cells, cut on an extended grapheme cluster boundary, and its exact terminal-cell width. - truncate_
measured_ str truncate_measuredover UTF-8str.- truncate_
str truncateover UTF-8str.- width
- Visible width of
inputin terminal cells (extended grapheme clusters, UAX #11 plus emoji presentation rules, with an ASCII bulk path). - width_
ansi - Visible terminal width of
input, ignoring ANSI/VT escape sequences. - width_
ansi_ str - Visible terminal width of a UTF-8 string, ignoring ANSI/VT escape sequences.
- width_
char - Standalone terminal-cell width of
c. - width_
str widthover UTF-8str.- width_
within - Visible width of
inputwhen it is at mostmax_width, orNoneonce the running width exceeds the bound. - width_
within_ str width_withinover UTF-8str.- wrap
- Greedily wraps
inputinto at least one borrowed terminal-width subline. - wrap_
measured - Greedily wraps
input, reporting each subline’s offset and visible width. - wrap_
measured_ str - Applies
wrap_measuredto a UTF-8 string. - wrap_
str - Applies
wrapto a UTF-8 string.