Package 'zuutf'

Title: Fast Unicode Validation and Transcoding with 'simdutf'
Description: Validates text and converts it between the Unicode Transformation Formats UTF-8, UTF-16 and UTF-32, in either byte order, and Latin-1, counts characters, detects encodings, and encodes and decodes Base64, with a bundled copy of the 'simdutf' library (<https://github.com/simdutf/simdutf>). 'simdutf' chooses single instruction, multiple data (SIMD) code for the running processor at first use, so validation and conversion run at gigabytes per second; its methods are described by Keiser and Lemire (2021) <doi:10.48550/arXiv.2010.03090>, Lemire and Mula (2022) <doi:10.48550/arXiv.2109.10433> and Mula and Lemire (2020) <doi:10.48550/arXiv.1910.05109>. Every validation and conversion can report the position of the first ill-formed sequence, in the units of the input. Character, raw and list-of-raw input are accepted, and invalid input can raise an error, be replaced with U+FFFD, or give a missing value. The same functions are published to other packages as a registered C interface.
Authors: Pedro Baltazar [aut, cre, cph], Daniel Lemire [ctb, cph] (simdutf, bundled in src/vendor/simdutf), The simdutf authors [cph] (simdutf, bundled in src/vendor/simdutf), Facebook, Inc [cph] (CPU detection in src/vendor/simdutf/simdutf.h, from PyTorch), Idiap Research Institute [cph] (CPU detection in src/vendor/simdutf/simdutf.h, from PyTorch), Deepmind Technologies [cph] (CPU detection in src/vendor/simdutf/simdutf.h, from PyTorch), NEC Laboratories America [cph] (CPU detection in src/vendor/simdutf/simdutf.h, from PyTorch), NYU [cph] (CPU detection in src/vendor/simdutf/simdutf.h, from PyTorch), Adam Paszke [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Soumith Chintala [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Ronan Collobert [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Koray Kavukcuoglu [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Clement Farabet [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Leon Bottou [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Iain Melvin [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Jason Weston [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Samy Bengio [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Johnny Mariethoz [ctb] (PyTorch CPU detection, in src/vendor/simdutf/simdutf.h), Markus Kuhn [cph] (UTF-8 stress test, tests/testthat/fixtures/UTF-8-test.txt), web-platform-tests contributors [cph] (Base64 vectors, tests/testthat/fixtures/whatwg-base64.tsv)
Maintainer: Pedro Baltazar <[email protected]>
License: MIT + file LICENSE
Version: 0.1.0.9000
Built: 2026-12-01 09:56:40 UTC
Source: https://github.com/pedrobtz/zuutf

Help Index


Encode and decode Base64

Description

base64_encode() writes bytes as Base64 text; base64_decode() reads it back.

Usage

base64_encode(x, url = FALSE, pad = TRUE, line_length = NULL)

base64_decode(x, url = FALSE, forgiving = TRUE, pad = TRUE)

Arguments

x

For base64_encode(), a raw vector, or a single string, which is encoded as its UTF-8 bytes. For base64_decode(), a single string or a raw vector holding the Base64 text.

url

Which alphabet: FALSE (the default) for the standard one with + and /, TRUE for the URL- and filename-safe one with - and ⁠_⁠. base64_decode() also takes NA, which accepts either.

pad

Whether base64_encode() writes = padding. For base64_decode() with forgiving = FALSE, whether padding is required (TRUE, the default) or refused (FALSE); forgiving decoding accepts either, so pad = FALSE needs forgiving = FALSE.

line_length

NULL (the default) for one line, or a whole number of at least 4, one Base64 quantum: a line feed ("\n") is written after every line_length characters, as MIME and PEM do with 76 and 64. A value at least as long as the text gives one line. For the CRLF of MIME, use gsub() on the result.

forgiving

TRUE (the default) for WHATWG forgiving decoding, FALSE for strict RFC 4648; see Details.

Details

Decoding is forgiving by default, as the WHATWG "forgiving-base64 decode" is: ASCII whitespace (space, tab, line feed, form feed, carriage return) is skipped, padding is optional, and a final quantum of a single character is an error. forgiving = FALSE reads RFC 4648 section 3.3 strictly: padding is required, the unused bits of the last character must be zero, and whitespace is an error too. Padding is required with the URL alphabet as well, unless pad = FALSE: then padding is an error instead, and an unpadded text is read just as strictly. That is the Base64url of JOSE (RFC 7515 section 2) and of JWTs, where each value has exactly one accepted encoding, the one base64_encode(pad = FALSE) writes.

Value

base64_encode(): a single string. base64_decode(): a raw vector. Input the chosen mode rejects raises a zuutf_base64_error whose offset is the 1-based position of the offending character.

See Also

zuutf_error for the condition classes.

Examples

base64_encode(charToRaw("hello"))
base64_encode("hello", pad = FALSE)
base64_encode(as.raw(c(0xfb, 0xff)), url = TRUE)
base64_encode(as.raw(0:59), line_length = 64)

rawToChar(base64_decode("aGVsbG8="))
base64_decode(" aGVs bG8 ")              # whitespace is skipped
base64_decode("-_8", url = TRUE)
base64_decode("+/8", url = NA)           # either alphabet
tryCatch(
  base64_decode("aGVsbG8", forgiving = FALSE),   # padding is required
  zuutf_base64_error = function(e) e$offset
)
# Unpadded Base64url, read strictly, as JOSE and JWTs use it
base64_decode("aGVsbG8", url = TRUE, forgiving = FALSE, pad = FALSE)

Convert between Unicode encodings

Description

utf_convert() converts bytes from one encoding to another. utf_decode() converts bytes to a character vector marked UTF-8. utf_encode() converts a character vector to bytes.

Usage

utf_convert(x, from, to, invalid = c("error", "replace", "na"))

utf_decode(x, from = "auto", invalid = c("error", "replace", "na"))

utf_encode(x, to = "UTF-16LE", invalid = c("error", "replace", "na"))

Arguments

x

For utf_convert() and utf_decode(), a raw vector (one element) or a list of raw vectors (one element each, NULL for a missing one). For utf_encode(), a character vector, taken in its marked encoding; strings marked "bytes" are refused.

from

The encoding of x: "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-16", "UTF-32LE", "UTF-32BE", "UTF-32", "Latin-1", or "auto" for utf_detect()'s first candidate (UTF-8 when there is none). Matched without regard to case or hyphens.

to

The target encoding: "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" or "Latin-1".

invalid

"error", "replace" or "na"; see Details.

Details

Every pair of UTF-8, UTF-16 and UTF-32 (either byte order) and Latin-1 converts in both directions. A leading byte-order mark that matches from is dropped, and with "UTF-16", "UTF-32" or "auto" it chooses the encoding; the output never carries one.

invalid says what happens to input that is ill-formed in from, and, with a "Latin-1" target, to code points above U+00FF:

  • "error" raises a zuutf_encoding_error with the element's index, the offset of the problem in the input's code units and the encoding it lies in.

  • "replace" writes U+FFFD (or ⁠?⁠ in Latin-1, which has no U+FFFD) in place of each maximal ill-formed subpart, as the WHATWG decoder does: one per unpaired surrogate in UTF-16, one per out-of-range unit in UTF-32, one per partial unit at the end, and one per unrepresentable code point.

  • "na" gives NA (NULL in a list of raw vectors) for that element.

R strings cannot hold U+0000, so utf_decode() raises zuutf_nul_error with its index and offset whatever invalid says; utf_convert() keeps it.

Value

utf_convert() and utf_encode(): a raw vector for a raw vector or a single string, otherwise a list of raw vectors (NULL for a missing or, under "na", invalid element). A single string that is NA, or invalid under "na", gives NULL, and its name is dropped, since a raw vector has no element names. utf_decode(): a character vector marked UTF-8, one string per element. A list, or a character vector of any other length, keeps its names.

See Also

utf_detect(), utf_valid(), utf_length_as(); iconv().

Examples

# UTF-16 from a Windows tool, with its byte-order mark
b <- as.raw(c(0xff, 0xfe, 0x63, 0x00, 0x61, 0x00, 0x66, 0x00, 0xe9, 0x00))
utf_decode(b)                          # "auto" reads the BOM
utf_decode(b, "UTF-16LE")

utf_encode("caf\u00e9", "UTF-16BE")
utf_convert(charToRaw("caf\u00e9"), "UTF-8", "Latin-1")

# ill-formed input
bad <- as.raw(c(0x61, 0xff, 0x62))
utf_decode(bad, "UTF-8", invalid = "replace")
utf_decode(bad, "UTF-8", invalid = "na")
tryCatch(
  utf_decode(bad, "UTF-8"),
  zuutf_encoding_error = function(e) e$offset
)
utf_encode("\u4e2d", "Latin-1", invalid = "replace")

Count code points and conversion lengths

Description

utf_count() counts the code points (characters, in the sense of nchar(type = "chars")) of each element. utf_length_as() gives the number of bytes converting each element from from to to will produce, without converting it.

Usage

utf_count(x, encoding = "UTF-8", useBytes = FALSE)

utf_length_as(x, from = "UTF-8", to)

Arguments

x

A character vector, a raw vector (one element), or a list of raw vectors (one element each). NA strings and NULL list elements give NA.

encoding, from

The encoding of the input: "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-16", "UTF-32LE", "UTF-32BE", "UTF-32" or "Latin-1", matched without regard to case or hyphens; utf_count() also takes "ASCII". A character vector is UTF-8 text, so for one only "UTF-8" applies, and "ASCII" in utf_count(), unless useBytes = TRUE in utf_count().

useBytes

For a character vector: FALSE (the default) takes each string in its marked encoding and checks its UTF-8 form, refusing strings marked "bytes"; TRUE checks the bytes of every string as they are, which is how to check a string R believes is UTF-8.

to

The target encoding: "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-32LE", "UTF-32BE" or "Latin-1".

Details

A leading byte-order mark that matches the input encoding is skipped and not counted, and a conversion writes none, so neither counts it. An element that is ill-formed in its encoding gives NA; utf_error_at() says where. With a "Latin-1" target every code point is one byte, those above U+00FF included, since a conversion writes one byte for each of them too (an error, ⁠?⁠ or NA, as its invalid argument says).

Value

An integer vector, one value per element, NA where the element is NA, NULL or ill-formed. Counts beyond the integer range come back as doubles. A character vector or a list keeps its names.

See Also

utf_valid(); nchar().

Examples

utf_count(c("abc", "caf\u00e9", "\U0001f600", NA))
utf_count(as.raw(c(0x3d, 0xd8, 0x00, 0xde)), "UTF-16LE")   # one emoji

utf_length_as("caf\u00e9", to = "UTF-16LE")   # 8 bytes
utf_length_as("\U0001f600", to = "UTF-16LE")  # a surrogate pair: 4 bytes
utf_length_as(as.raw(c(0x63, 0xe9)), from = "Latin-1", to = "UTF-8")

Detect the encoding of bytes

Description

Lists the encodings each element could be in. A byte-order mark decides alone; otherwise the candidates are every encoding the bytes are valid in, by the validators of simdutf, in the order UTF-8, UTF-16LE, UTF-16BE, UTF-32LE, UTF-32BE. Latin-1 is never listed, since every byte string is valid Latin-1, and pure ASCII text is valid UTF-16 too when its length is even, which is why UTF-8 comes first. ⁠FF FE 00 00⁠ is the UTF-32LE byte-order mark, so it is detected as an empty UTF-32LE string, although it is also a UTF-16LE mark followed by U+0000; the longer mark wins.

Usage

utf_detect(x)

Arguments

x

A raw vector (one element) or a list of raw vectors.

Value

For a raw vector, a character vector of candidate encodings, best first, and character(0) when none fits. For a list, a list of such vectors (NULL for a NULL element), keeping its names.

See Also

utf_decode(), whose from = "auto" takes the first candidate.

Examples

utf_detect(charToRaw("hello"))
utf_detect(as.raw(c(0xff, 0xfe, 0x68, 0x00)))   # a UTF-16LE BOM
utf_detect(as.raw(c(0xff, 0xff, 0xff)))

Validate text in a Unicode encoding

Description

utf_valid() tells whether each element is well-formed in encoding. utf_error_at() gives the position of its first error. utf_is_ascii() tells whether each element is pure ASCII, bytes 0x00 to 0x7F.

Usage

utf_valid(x, encoding = "UTF-8", useBytes = FALSE)

utf_error_at(x, encoding = "UTF-8", useBytes = FALSE)

utf_is_ascii(x)

Arguments

x

A character vector, a raw vector (one element), or a list of raw vectors (one element each). NA strings and NULL list elements give NA.

encoding

The encoding to check against: "UTF-8", "UTF-16LE", "UTF-16BE", "UTF-16", "UTF-32LE", "UTF-32BE", "UTF-32", "Latin-1" or "ASCII", matched without regard to case or hyphens ("utf8" is "UTF-8"). A character vector is UTF-8 text, so for one only "UTF-8" and "ASCII" apply unless useBytes = TRUE.

useBytes

For a character vector: FALSE (the default) takes each string in its marked encoding and checks its UTF-8 form, refusing strings marked "bytes"; TRUE checks the bytes of every string as they are, which is how to check a string R believes is UTF-8.

Details

Well-formed means what Unicode says: in UTF-8, no overlong forms, no encoded surrogates (U+D800 to U+DFFF), nothing above U+10FFFF and no truncated sequence; in UTF-16, no unpaired surrogate; in UTF-32, no surrogate and nothing above U+10FFFF. A UTF-16 or UTF-32 input whose length is not a whole number of code units is ill-formed at its last, partial unit. Every byte string is valid Latin-1.

A leading byte-order mark that matches encoding is skipped. With "UTF-16" or "UTF-32", a byte-order mark chooses the byte order, and without one the input is big-endian.

Value

utf_valid() and utf_is_ascii(): a logical vector, one value per element. utf_error_at(): an integer vector of 1-based offsets of the first error, in the input's code units (bytes for UTF-8, Latin-1 and ASCII; 16-bit units for UTF-16; 32-bit units for UTF-32), counted after any byte-order mark, and NA where the element is valid. A character vector or a list keeps its names.

See Also

utf_count(); validUTF8(), which answers yes or no for UTF-8 only.

Examples

utf_valid(c("abc", "caf\u00e9", NA))
utf_valid(as.raw(c(0xc3, 0x28)))            # a truncated sequence
utf_error_at(as.raw(c(0x61, 0x62, 0xff)))   # third byte

# UTF-16 with and without a byte-order mark
le <- as.raw(c(0xff, 0xfe, 0x61, 0x00, 0x00, 0xd8))
utf_valid(le, "UTF-16")                     # the BOM says little-endian
utf_error_at(le, "UTF-16LE")                # unpaired surrogate, unit 2

# several byte strings at once
utf_valid(list(charToRaw("ok"), as.raw(0xc0), NULL))

utf_is_ascii(c("abc", "caf\u00e9"))

Conditions raised by zuutf

Description

Every error zuutf raises inherits from zuutf_error, then error and condition, so a caller can catch all of them, or one kind, with tryCatch(). Test code should match on the class, never on the message.

Details

Class Fields Raised when
zuutf_invalid_argument wrong type, unknown encoding name, a "bytes" string without useBytes
zuutf_encoding_error index, offset, encoding input that is ill-formed in its encoding under invalid = "error", or a code point a Latin-1 target cannot represent
zuutf_nul_error index, offset utf_decode() meets U+0000, which an R string cannot hold
zuutf_base64_error offset Base64 input that base64_decode()'s mode rejects
zuutf_size_error an output longer than a string (2^31 - 1 bytes) or a raw vector can hold
zuutf_internal_error a simdutf result zuutf did not expect, or a kernel forced through SIMDUTF_FORCE_IMPLEMENTATION that this processor cannot run

index is the 1-based element of the input, offset the 1-based position of the first error in the input's code units (bytes for UTF-8, Latin-1 and ASCII; 16-bit units for UTF-16; 32-bit units for UTF-32), counted after any byte-order mark, and encoding the name of the encoding.

Examples

tryCatch(
  utf_valid("abc", encoding = "EBCDIC"),
  zuutf_invalid_argument = function(e) class(e)
)

Information about the bundled simdutf library

Description

Reports the version of simdutf compiled into zuutf, the kernel in use, and every kernel compiled in with whether this processor can run it.

Usage

zuutf_info()

Details

simdutf picks the most advanced kernel the processor supports the first time any function needs one: on x86-64 "icelake" (AVX-512), "haswell" (AVX2) or "westmere" (SSE4.2), on ARM64 "arm64" (NEON), and "fallback", plain C++, everywhere. Setting the environment variable SIMDUTF_FORCE_IMPLEMENTATION to a kernel name before R starts makes simdutf use that kernel instead; an unknown name, or one this processor cannot run, gives "unsupported", and every function then fails.

Value

A list with elements:

  • simdutf: the simdutf version, as a string.

  • kernel: the name of the kernel in use.

  • kernels: a data frame with one row per kernel compiled in and columns name, description and supported (whether this processor can run it).

Examples

info <- zuutf_info()
info$simdutf
info$kernel
info$kernels