nox-utf8 #
A codec that refuses malformed UTF-8 should say where the input went wrong,
and the stdlib's String.is_valid_utf_8 answers only yes or no. nox-utf8
validates UTF-8 (RFC 3629) and reports the byte offset of the first malformed
sequence. Utf8.validate checks a whole string, and Utf8.Stream checks input
that arrives in pieces, where a multi-byte sequence may straddle two of them.
Installation #
Install with opam:
$ opam install nox-utf8
If opam cannot find the package, it may not yet be released in the public
opam-repository. Add the overlay repository, then install it:
$ opam repo add samoht https://tangled.org/gazagnaire.org/opam-overlay.git
$ opam update
$ opam install nox-utf8
Usage #
# Utf8.validate "héllo";;
- : (unit, int) result = Ok ()
# Utf8.validate "h\xc3\xa9llo\xffx";;
- : (unit, int) result = Error 6
Utf8.validate runs the stdlib's allocation-free String.is_valid_utf_8
first, so only invalid input pays for locating the first malformed byte.
Utf8.Stream uses Bjoern Hoehrmann's DFA. A 256-entry table maps each byte to
one of twelve character classes, and a 108-entry table maps a state and a
class to the next state, over nine states: state 0 accepts at a character
boundary and state 12 rejects. The whole decoder state is that one small
integer, so a sequence split between two pieces resumes from the state the
first piece ended in. bench/README.md compares its cost with the stdlib and
with uutf.
Code points and text #
Utf8.uchars decodes a string to its code points, each maximal ill-formed
subpart as one U+FFFD, and Utf8.length counts them without decoding.
Utf8.of_latin1_if_invalid reads a string that is not UTF-8 as ISO-8859-1.
# Utf8.uchars "a\xE1\x80b" |> Array.map Uchar.to_int;;
- : int array = [|97; 65533; 98|]
# Utf8.length "h\xc3\xa9llo";;
- : int = 5
The nox-utf8.text sub-library, module Utf8_text, works by Unicode
character properties through uucp and uunf, which nox-utf8 itself does not
link: trim, words and collapse_spaces cut at the White_Space
property, lines at the mandatory breaks of UAX #14, and strip_marks folds
accents and compatibility characters away.
# Utf8_text.words "\u{3000}deux\u{00A0}mots\n";;
- : string list = ["deux"; "mots"]
# Utf8_text.strip_marks "\u{FB01}n de l'\u{00E9}t\u{00E9}";;
- : string = "fin de l'ete"
Licence #
ISC.