Module Uutf
Non-blocking streaming Unicode codec.
Uutf is a non-blocking streaming codec to decode and encode the UTF-8, UTF-16, UTF-16LE and UTF-16BE encoding schemes. It can efficiently work character by character without blocking on IO. Decoders perform character position tracking and support newline normalization.
Functions are also provided to fold over the characters of UTF encoded OCaml string values and to directly encode characters in OCaml Buffer.t values.
See examples of use.
v1.0.2 — homepage
References
- The Unicode Consortium. The Unicode Standard. (latest version)
Special Unicode characters
val u_bom : Stdlib.Uchar.tu_bomis the byte order mark (BOM) character (U+FEFF).
val u_rep : Stdlib.Uchar.tu_repis the replacement character (U+FFFD).
Unicode encoding schemes
type encoding=[|`UTF_16|`UTF_16BE|`UTF_16LE|`UTF_8]The type for Unicode encoding schemes.
type decoder_encoding=[|encoding|`US_ASCII|`ISO_8859_1]The type for encoding schemes decoded by
Uutf. Unicode encoding schemes plus US-ASCII and ISO/IEC 8859-1 (latin-1).
val encoding_of_string : string -> decoder_encoding optionencoding_of_string sconverts a (case insensitive) IANA character set name to an encoding.
val encoding_to_string : [< decoder_encoding ] -> stringencoding_to_string eis a IANA character set name fore.
Decode
type src=[|`Channel of Stdlib.in_channel|`String of string|`Manual]The type for input sources. With a
`Manualsource the client must provide input withManual.src.
type nln=[|`ASCII of Stdlib.Uchar.t|`NLF of Stdlib.Uchar.t|`Readline of Stdlib.Uchar.t]The type for newline normalizations. The variant argument is the normalization character.
`ASCII, normalizes CR (U+000D), LF (U+000A) and CRLF (<U+000D,U+000A>).`NLF, normalizes the Unicode newline function (NLF). This is NEL (U+0085) and the normalizations of`ASCII.`Readline, normalizes for a Unicode readline function. This is FF (U+000C), LS (U+2028), PS (U+2029), and the normalizations of`NLF.
Used with an appropriate normalization character the
`NLFand`Readlinenormalizations allow to implement all the different recommendations of Unicode's newline guidelines (section 5.8 in Unicode 9.0.0).
val decoder : ?nln:[< nln ] -> ?encoding:[< decoder_encoding ] -> [< src ] -> decoderdecoder nln encoding srcis a decoder that inputs fromsrc.Byte order mark. Byte order mark (BOM) constraints are application dependent and prone to misunderstandings (see the FAQ). Hence,
Uutfdecoders have a simple rule: an initial BOM is always removed from the input and not counted in character position tracking. The functiondecoder_removed_bomdoes however returntrueif a BOM was removed so that all the information can be recovered if needed.For UTF-16BE and UTF-16LE the above rule is a violation of conformance D96 and D97 of the standard.
Uutffavors the idea that if there's a BOM, decoding with`UTF_16or the`UTF_16XXcorresponding to the BOM should decode the same character sequence (this is not the case if you stick to the standard). The client can however regain conformance by consulting the result ofdecoder_removed_bomand take appropriate action.Encoding.
encodingspecifies the decoded encoding scheme. If`UTF_16is used the endianness is determined according to the standard: from a BOM if there is one,`UTF_16BEotherwise.If
encodingis unspecified it is guessed. The result of a guess can only be`UTF_8,`UTF_16BEor`UTF_16LE. The heuristic looks at the first three bytes of input (or less if impossible) and takes the first matching byte pattern in the table below.xx = any byte .. = any byte or no byte (input too small) pp = positive byte uu = valid UTF-8 first byte Bytes | Guess | Rationale ---------+-----------+----------------------------------------------- EF BB BF | `UTF_8 | UTF-8 BOM FE FF .. | `UTF_16BE | UTF-16BE BOM FF FE .. | `UTF_16LE | UTF-16LE BOM 00 pp .. | `UTF_16BE | ASCII UTF-16BE and U+0000 is often forbidden pp 00 .. | `UTF_16LE | ASCII UTF-16LE and U+0000 is often forbidden uu .. .. | `UTF_8 | ASCII UTF-8 or valid UTF-8 first byte. xx xx .. | `UTF_16BE | Not UTF-8 => UTF-16, no BOM => UTF-16BE .. .. .. | `UTF_8 | Single malformed UTF-8 byte or no input.This heuristic is compatible both with BOM based recognitition and JSON-like encoding recognition that relies on ASCII being present at the beginning of the stream. Also,
decoder_removed_bomwill tell the client if the guess was BOM based.Newline normalization. If
nlnis specified, the given newline normalization is performed, seenln. Otherwise all newlines are returned as found in the input.Character position. The line number, column number, byte count and character count of the last decoded character (including
`Malformedones) are respectively returned bydecoder_line,decoder_col,decoder_byte_countanddecoder_count. Before the first call to Decode the line number is1and the column is0. Each Decode returning`Ucharor`Malformedincrements the column until a newline. On a newline, the line number is incremented and the column set to zero. For example the line is2and column0after the first newline was decoded. This can be understood as if Decode was moving an insertion point to the right in the data. A newline is anything normalized by`Readline, seenln.Uutfassumes that each Unicode scalar value has a column width of 1. The same assumption may not be made by the display program (e.g. foremacs' compilation mode you need to setcompilation-error-screen-columnstonil). The problem is in general difficult to solve without interaction or convention with the display program's rendering engine. Depending on the context better column increments can be implemented by usingUucp.Break.tty_width_hint or grapheme cluster boundaries (seeUuseg).
val decode : decoder -> [ `Await | `Uchar of Stdlib.Uchar.t | `End | `Malformed of string ]decode dis:`Awaitifdhas a`Manualinput source and awaits for more input. The client must useManual.srcto provide it.`Uchar uif a Unicode scalar valueuwas decoded.`Endif the end of input was reached.`Malformed bytesif thebytessequence is malformed according to the decoded encoding scheme. If you are interested in a best-effort decoding you can still continue to decode after an error until the decoder synchronizes again on valid bytes. It may however be a good idea to signal the malformed characters by adding anu_repcharacter to the parsed data, see the examples.
Note. Repeated invocation always eventually returns
`End, even in case of errors.
val decoder_encoding : decoder -> decoder_encodingdecoder_encoding disd's the decoded encoding scheme ofd.Warning. If the decoder guesses the encoding or uses
`UTF_16, rely on this value only after the first`Ucharwas decoded.
val decoder_line : decoder -> intdecoder_line dis the line number of the last decoded (or malformed) character. Seedecoderfor details.
val decoder_col : decoder -> intdecoder_col dis the column number of the last decoded (or malformed) character. Seedecoderfor details.
val decoder_byte_count : decoder -> intdecoder_byte_count dis the number of bytes already decoded ond(including malformed ones). This is the last Decode's end byte offset counting from the beginning of the stream.
val decoder_count : decoder -> intdecoder_count dis the number of characters already decoded ond(including malformed ones). Seedecoderfor details.
val decoder_removed_bom : decoder -> booldecoder_removed_bom distrueiff an initial BOM was removed from the input stream. Seedecoderfor details.
val pp_decode : Stdlib.Format.formatter -> [< `Await | `Uchar of Stdlib.Uchar.t | `End | `Malformed of string ] -> unitpp_decode ppf vprints an unspecified representation ofvonppf.
Encode
type dst=[|`Channel of Stdlib.out_channel|`Buffer of Stdlib.Buffer.t|`Manual]The type for output destinations. With a
`Manualdestination the client must provide output storage withManual.dst.
val encoder : [< encoding ] -> [< dst ] -> encoderencoder encoding dstis an encoder forencodingthat outputs todst.Note. No initial BOM is encoded. If needed, this duty is left to the client.
val encode : encoder -> [< `Await | `End | `Uchar of Stdlib.Uchar.t ] -> [ `Ok | `Partial ]encode e vis :`Partialiffehas a`Manualdestination and needs more output storage. The client must useManual.dstto provide a new buffer and then call Encode with`Awaituntil`Okis returned.`Okwhen the encoder is ready to encode a new`Ucharor`End
For
`Manualdestination, encoding`Endalways returns`Partial, the client should continue as usual with`Awaituntil`Okis returned at which pointManual.dst_remeis guaranteed to be the size of the last provided buffer (i.e. nothing was written).Raises.
Invalid_argumentif an`Ucharor`Endis encoded after a`Partialencode.
Manual sources and destinations.
module Manual : sig ... endManual sources and destinations.
String folders and Buffer encoders
module String : sig ... endFold over the characters of UTF encoded OCaml
stringvalues.
Examples
Read lines
The value of lines src is the list of lines in src as UTF-8 encoded OCaml strings. Line breaks are determined according to the recommendation R4 for a readline function in section 5.8 of Unicode 9.0.0. If a decoding error occurs we silently replace the malformed sequence by the replacement character u_rep and continue.
let lines ?encoding (src : [`Channel of in_channel | `String of string]) =
let rec loop d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop d buf acc
| `Await -> assert false
in
let nln = `Readline (Uchar.of_int 0x000A) in
loop (Uutf.decoder ~nln ?encoding src) (Buffer.create 512) []Using the `Manual interface, lines_fd does the same but on a Unix file descriptor.
let lines_fd ?encoding (fd : Unix.file_descr) =
let rec loop fd s d buf acc = match Uutf.decode d with
| `Uchar u ->
begin match Uchar.to_int u with
| 0x000A ->
let line = Buffer.contents buf in
Buffer.clear buf; loop fd s d buf (line :: acc)
| _ ->
Uutf.Buffer.add_utf_8 buf u; loop fd s d buf acc
end
| `End -> List.rev (Buffer.contents buf :: acc)
| `Malformed _ -> Uutf.Buffer.add_utf_8 buf Uutf.u_rep; loop fd s d buf acc
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fd s 0 (Bytes.length s) in
Uutf.Manual.src d s 0 rc; loop fd s d buf acc
in
let s = Bytes.create 65536 (* UNIX_BUFFER_SIZE in 4.0.0 *) in
let nln = `Readline (Uchar.of_int 0x000A) in
loop fd s (Uutf.decoder ~nln ?encoding `Manual) (Buffer.create 512) []Recode
The result of recode src out_encoding dst has the characters of src written on dst with encoding out_encoding. If a decoding error occurs we silently replace the malformed sequence by the replacement character u_rep and continue. Note that we don't add an initial BOM to dst, recoding will thus loose the initial BOM src may have. Whether this is a problem or not depends on the context.
let recode ?nln ?encoding out_encoding
(src : [`Channel of in_channel | `String of string])
(dst : [`Channel of out_channel | `Buffer of Buffer.t])
=
let rec loop d e = match Uutf.decode d with
| `Uchar _ as u -> ignore (Uutf.encode e u); loop d e
| `End -> ignore (Uutf.encode e `End)
| `Malformed _ -> ignore (Uutf.encode e (`Uchar Uutf.u_rep)); loop d e
| `Await -> assert false
in
let d = Uutf.decoder ?nln ?encoding src in
let e = Uutf.encoder out_encoding dst in
loop d eUsing the `Manual interface, recode_fd does the same but between Unix file descriptors.
let recode_fd ?nln ?encoding out_encoding
(fdi : Unix.file_descr)
(fdo : Unix.file_descr)
=
let rec encode fd s e v = match Uutf.encode e v with `Ok -> ()
| `Partial ->
let rec unix_write fd s j l =
let rec write fd s j l = try Unix.single_write fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> write fd s j l
in
let wc = write fd s j l in
if wc < l then unix_write fd s (j + wc) (l - wc) else ()
in
unix_write fd s 0 (Bytes.length s - Uutf.Manual.dst_rem e);
Uutf.Manual.dst e s 0 (Bytes.length s);
encode fd s e `Await
in
let rec loop fdi fdo ds es d e = match Uutf.decode d with
| `Uchar _ as u -> encode fdo es e u; loop fdi fdo ds es d e
| `End -> encode fdo es e `End
| `Malformed _ -> encode fdo es e (`Uchar Uutf.u_rep); loop fdi fdo ds es d e
| `Await ->
let rec unix_read fd s j l = try Unix.read fd s j l with
| Unix.Unix_error (Unix.EINTR, _, _) -> unix_read fd s j l
in
let rc = unix_read fdi ds 0 (Bytes.length ds) in
Uutf.Manual.src d ds 0 rc; loop fdi fdo ds es d e
in
let ds = Bytes.create 65536 (* UNIX_BUFFER_SIZE in 4.0.0 *) in
let es = Bytes.create 65536 (* UNIX_BUFFER_SIZE in 4.0.0 *) in
let d = Uutf.decoder ?nln ?encoding `Manual in
let e = Uutf.encoder out_encoding `Manual in
Uutf.Manual.dst e es 0 (Bytes.length es);
loop fdi fdo ds es d e