Skip to content

Core\Encoding

Converts between string and bytes. It changes text to and from a character set, and writes bytes as base64, base32 or hex text.

Core\Encoding is where a string becomes bytes and back: encodeText and decodeText convert text through a Core\Charset case, and the base64, base64url, base32 and hex pairs spell a buffer as text and read it back. Every decoder is strict — a character outside the alphabet, padding that is missing or non-canonical, a sequence the charset cannot read — and throws rather than answering false or substituting ? or U+FFFD; isValidText is decodeText's question with a bool answer. A bytes value cannot be written directly in the code. Use fromHex or encodeText to write a buffer in source.

<?nvs
bytes $raw = Core\Encoding::encodeText('héllo', Core\Charset::Utf8);
echo Core\Bytes::length($raw), ' ', Core\Encoding::toHex($raw), "\n";
echo Core\Encoding::toBase64($raw), ' ', Core\Encoding::toBase64Url($raw), ' ', Core\Encoding::toBase32($raw), "\n";
echo Core\Encoding::decodeText(Core\Encoding::fromBase64('aMOpbGxv'), Core\Charset::Utf8), "\n";
bytes $latin = Core\Encoding::encodeText('héllo', Core\Charset::Latin1);
echo Core\Bytes::length($latin), ' ', Core\Encoding::toHex($latin), "\n";
echo Core\Encoding::isValidText($latin, Core\Charset::Utf8) ? 'utf-8' : 'not utf-8', "\n";
bytes $png = Core\Encoding::fromHex('89504e47');
echo Core\Bytes::at($png, 1), "\n";
try {
bytes $never = Core\Encoding::fromBase64('not base64!');
echo "decoded\n";
} catch (Throwable $e) {
echo "refused\n";
}
Output
6 68c3a96c6c6f
aMOpbGxv aMOpbGxv NDB2S3DMN4
héllo
5 68e96c6c6f
not utf-8
80
refused

Members

11 members.

MemberSignature
encodeTextencodeText(string $s, Core\Charset $charset): bytes
decodeTextdecodeText(bytes $b, Core\Charset $charset): string
isValidTextisValidText(bytes $b, Core\Charset $charset): bool
toBase64toBase64(bytes $b): string
fromBase64fromBase64(string $s): bytes
toBase64UrltoBase64Url(bytes $b): string
fromBase64UrlfromBase64Url(string $s): bytes
toBase32toBase32(bytes $b): string
fromBase32fromBase32(string $s): bytes
toHextoHex(bytes $b): string
fromHexfromHex(string $s): bytes