Overview
Encoders and decoders for converting between different data representations, including JSON and UTF-8.
In addition to converters for common data representations, this library provides support for implementing converters in a way which makes them easy to chain and to use with streams.
To use this library in your code:
import 'raya:convert';
Two commonly used converters are the top-level instances of JsonCodec and Utf8Codec, named json and utf8, respectively.
JSON
JSON is a simple text format for representing structured objects and collections.
A JsonCodec encodes JSON objects to strings and decodes strings to JSON objects. The json encoder/decoder transforms between strings and object structures, such as lists and maps, using the JSON format.
The json is the default implementation of JsonCodec.
Examples
var encoded = json.encode([1, 2, { "a": null }]);
var decoded = json.decode('["foo", { "bar": 499 }]');
For more information, see also JsonEncoder and JsonDecoder.
UTF-8
A Utf8Codec encodes strings to UTF-8 code units (bytes) and decodes UTF-8 code units to strings.
The utf8 is the default implementation of Utf8Codec.
Example:
var encoded = utf8.encode('Îñţérñåţîöñåļîžåţîờñ');
var decoded = utf8.decode([
195, 142, 195, 177, 197, 163, 195, 169, 114, 195, 177, 195, 165, 197,
163, 195, 174, 195, 182, 195, 177, 195, 165, 196, 188, 195, 174, 197,
190, 195, 165, 197, 163, 195, 174, 225, 187, 157, 195, 177]);
For more information, see also Utf8Encoder and Utf8Decoder.
ASCII
An AsciiCodec encodes strings as ASCII codes stored as bytes and decodes ASCII bytes to strings. Not all characters can be represented as ASCII, so not all strings can be successfully converted.
The ascii is the default implementation of AsciiCodec.
Example:
var encoded = ascii.encode('This is ASCII!');
var decoded = ascii.decode([0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
0x20, 0x41, 0x53, 0x43, 0x49, 0x49, 0x21]);
For more information, see also AsciiEncoder and AsciiDecoder.
Latin-1
A Latin1Codec encodes strings to ISO Latin-1 (aka ISO-8859-1) bytes and decodes Latin-1 bytes to strings. Not all characters can be represented as Latin-1, so not all strings can be successfully converted.
The latin1 is the default implementation of Latin1Codec.
Example:
var encoded = latin1.encode('blåbærgrød');
var decoded = latin1.decode([0x62, 0x6c, 0xe5, 0x62, 0xe6,
0x72, 0x67, 0x72, 0xf8, 0x64]);
For more information, see also Latin1Encoder and Latin1Decoder.
Base64
A Base64Codec encodes bytes using the default base64 alphabet, decodes using both the base64 and base64url alphabets, does not allow invalid characters and requires padding.
The base64 is the default implementation of Base64Codec.
Example:
var encoded = base64.encode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);
var decoded = base64.decode('YmzDpWLDpnJncsO4ZAo=');
For more information, see also Base64Encoder and Base64Decoder.
Converters
Converters are often used with streams to transform the data that comes through the stream as it becomes available. The following code uses two converters. The first is a UTF-8 decoder, which converts the data from bytes to UTF-8 as it is read from a file, The second is an instance of LineSplitter, which splits the data on newline boundaries.
const showLineNumbers = true;
var lineNumber = 1;
var stream = File('quotes.txt').openRead();
stream.transform(utf8.decoder)
.transform(const LineSplitter())
.forEach((line) {
if (showLineNumbers) {
stdout.write('${lineNumber++} ');
}
stdout.writeln(line);
});
See the documentation for the Codec and Converter classes for information about creating your own converters.
HTML Escape
HtmlEscape converter escapes characters with special meaning in HTML. The converter finds characters that are significant in HTML source and replaces them with corresponding HTML entities.
Custom escape modes can be created using the HtmlEscapeMode.new constructor.
Example:
const htmlEscapeMode = HtmlEscapeMode(
name: 'custom',
escapeLtGt: true,
escapeQuot: false,
escapeApos: false,
escapeSlash: false,
);
const HtmlEscape htmlEscape = HtmlEscape(htmlEscapeMode);
String unescaped = 'Text & subject';
String escaped = htmlEscape.convert(unescaped);
print(escaped); // Text & subject
unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 > 1 and 1 < 10
unescaped = "Single-quoted: 'text'";
escaped = htmlEscape.convert(unescaped);
print(escaped); // Single-quoted: 'text'
unescaped = 'Double-quoted: "text"';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Double-quoted: "text"
unescaped = 'Path: /system/';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Path: /system/Functions and constants
Functions
String base64Encode(List<int> bytes)Encodes bytes using base64 encoding.
Shorthand for base64.encode(bytes). Useful if a local variable shadows the global base64 constant.
import 'raya:convert';
void main() {
final bytes = utf8.encode('Hello, Raya!');
final b64 = base64Encode(bytes);
print('base64: $b64');
print('decoded: ${utf8.decode(base64Decode(b64))}');
print('url-safe: ${base64UrlEncode([251, 255, 254])}');
print('standard: ${base64Encode([251, 255, 254])}');
}base64: SGVsbG8sIFJheWEh decoded: Hello, Raya! url-safe: -__- standard: +//+
String base64UrlEncode(List<int> bytes)Encodes bytes using base64url encoding.
Shorthand for base64url.encode(bytes).
import 'raya:convert';
void main() {
final bytes = [251, 255, 191, 0, 1];
print('url-safe: ${base64UrlEncode(bytes)}');
print('standard: ${base64Encode(bytes)}');
print('decodes back: ${base64Url.decode(base64UrlEncode(bytes))}');
}url-safe: -_-_AAE= standard: +/+/AAE= decodes back: [251, 255, 191, 0, 1]
Uint8List base64Decode(String source)Decodes base64 or base64url encoded bytes.
Shorthand for base64.decode(bytes). Useful if a local variable shadows the global base64 constant.
import 'raya:convert';
void main() {
final bytes = base64Decode('SGVsbG8sIFJheWEh');
print('bytes: $bytes');
print('as text: ${utf8.decode(bytes)}');
try {
base64Decode('abc');
} on FormatException catch (e) {
print('bad length: ${e.message}');
}
}bytes: [72, 101, 108, 108, 111, 44, 32, 82, 97, 121, 97, 33] as text: Hello, Raya! bad length: Invalid length, must be multiple of four
String jsonEncode(Object? object, {Object? Function(Object? nonEncodable)? toEncodable})Converts object to a JSON string.
If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.
If toEncodable is omitted, it defaults to a function that returns the result of calling .toJson on the unencodable object.
Shorthand for json.encode. Useful if a local variable shadows the global json constant.
Example:
const data = {'text': 'foo', 'value': 2, 'status': false, 'extra': null};
final String jsonString = jsonEncode(data);
print(jsonString); // {"text":"foo","value":2,"status":false,"extra":null}
Example of converting an otherwise unsupported object to a custom JSON format:
class CustomClass {
final String text;
final int value;
CustomClass({required this.text, required this.value});
CustomClass.fromJson(Map<String, dynamic> json)
: text = json['text'],
value = json['value'];
static Map<String, dynamic> toJson(CustomClass value) =>
{'text': value.text, 'value': value.value};
}
void main() {
final CustomClass cc = CustomClass(text: 'Raya', value: 123);
final jsonText = jsonEncode({'cc': cc},
toEncodable: (Object? value) => value is CustomClass
? CustomClass.toJson(value)
: throw UnsupportedError('Cannot convert to JSON: $value'));
print(jsonText); // {"cc":{"text":"Raya","value":123}}
}import 'raya:convert';
void main() {
final data = {
'name': 'Raya',
'year': 2026,
'tags': ['exact', 'fast'],
'stable': true,
'parent': null,
};
print(jsonEncode(data));
print(jsonEncode([1, 2.5, 'three']));
}{"name":"Raya","year":2026,"tags":["exact","fast"],"stable":true,"parent":null}
[1,2.5,"three"]dynamic jsonDecode(String source, {Object? Function(Object? key, Object? value)? reviver})Parses the string and returns the resulting Json object.
The optional reviver function is called once for each object or list property that has been parsed during decoding. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.
The default reviver (when not provided) is the identity function.
Shorthand for json.decode. Useful if a local variable shadows the global json constant.
Example:
const jsonString =
'{"text": "foo", "value": 1, "status": false, "extra": null}';
final data = jsonDecode(jsonString);
print(data['text']); // foo
print(data['value']); // 1
print(data['status']); // false
print(data['extra']); // null
const jsonArray = '''
[{"text": "foo", "value": 1, "status": true},
{"text": "bar", "value": 2, "status": false}]
''';
final List<dynamic> dataList = jsonDecode(jsonArray);
print(dataList[0]); // {text: foo, value: 1, status: true}
print(dataList[1]); // {text: bar, value: 2, status: false}
final item = dataList[0];
print(item['text']); // foo
print(item['value']); // 1
print(item['status']); // falseimport 'raya:convert';
void main() {
const text = '{"id": 7, "scores": [9.5, 8], "user": {"name": "Ada"}}';
final m = jsonDecode(text) as Map<String, dynamic>;
print('id: ${m['id']}');
print('scores: ${m['scores']}');
print('name: ${m['user']['name']}');
print('types: ${m['id'].runtimeType}, ${m['scores'].runtimeType}');
}id: 7 scores: [9.5, 8] name: Ada types: int, List<dynamic>
Constants and variables
const AsciiCodec ascii = AsciiCodec()An instance of the default implementation of the AsciiCodec.
This instance provides a convenient access to the most common ASCII use cases.
Examples:
var encoded = ascii.encode("This is ASCII!");
var decoded = ascii.decode([0x54, 0x68, 0x69, 0x73, 0x20, 0x69, 0x73,
0x20, 0x41, 0x53, 0x43, 0x49, 0x49, 0x21]);const Base64Codec base64 = Base64Codec()A base64 encoder and decoder.
It encodes using the default base64 alphabet, decodes using both the base64 and base64url alphabets, does not allow invalid characters and requires padding.
Examples:
var encoded = base64.encode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);
var decoded = base64.decode("YmzDpWLDpnJncsO4ZAo=");
The top-level base64Encode and base64Decode functions may be used instead if a local variable shadows the base64 constant.
import 'raya:convert';
void main() {
final enc = base64.encode([0, 1, 2, 3, 4, 5]);
print(enc);
print(base64.decode(enc));
print(base64.normalize('AAECAwQF'));
}AAECAwQF [0, 1, 2, 3, 4, 5] AAECAwQF
const Base64Codec base64Url = Base64Codec.urlSafe()A base64url encoder and decoder.
It encodes and decodes using the base64url alphabet, decodes using both the base64 and base64url alphabets, does not allow invalid characters and requires padding.
Examples:
var encoded = base64Url.encode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);
var decoded = base64Url.decode("YmzDpWLDpnJncsO4ZAo=");const HtmlEscape htmlEscape = HtmlEscape()A String converter that converts characters to HTML entities.
This is intended to sanitize text before inserting the text into an HTML document. Characters that are meaningful in HTML are converted to HTML entities (like & for &).
The general converter escapes all characters that are meaningful in HTML attributes or normal element context. Elements with special content types (like CSS or JavaScript) may need a more specialized escaping that understands that content type.
If the context where the text will be inserted is known in more detail, it's possible to omit escaping some characters (like quotes when not inside an attribute value).
The escaped text should only be used inside quoted HTML attributes values or as text content of a normal element. Using the escaped text inside a tag, but not inside a quoted attribute value, is still dangerous.
import 'raya:convert';
void main() {
print(htmlEscape.convert('<a href="x">Tom & Jerry</a>'));
}<a href="x">Tom & Jerry</a>
const JsonCodec json = JsonCodec()An instance of the default implementation of the JsonCodec.
This instance provides a convenient access to the most common JSON use cases.
Examples:
var encoded = json.encode([1, 2, { "a": null }]);
var decoded = json.decode('["foo", { "bar": 499 }]');
The top-level jsonEncode and jsonDecode functions may be used instead if a local variable shadows the json constant.
const Latin1Codec latin1 = Latin1Codec()An instance of the default implementation of the Latin1Codec.
This instance provides a convenient access to the most common ISO Latin 1 use cases.
Examples:
var encoded = latin1.encode("blåbærgrød");
var decoded = latin1.decode([0x62, 0x6c, 0xe5, 0x62, 0xe6,
0x72, 0x67, 0x72, 0xf8, 0x64]);import 'raya:convert';
void main() {
print(latin1.encode('café'));
print(latin1.decode([99, 97, 102, 233]));
print(ascii.encode('ABC'));
}[99, 97, 102, 233] café [65, 66, 67]
const int unicodeReplacementCharacterRune = 0xFFFDThe Unicode Replacement character U+FFFD (�).
const int unicodeBomCharacterRune = 0xFEFFThe Unicode Byte Order Marker (BOM) character U+FEFF.
const Utf8Codec utf8 = Utf8Codec()An instance of the default implementation of the Utf8Codec.
This instance provides a convenient access to the most common UTF-8 use cases.
Examples:
var encoded = utf8.encode("Îñţérñåţîöñåļîžåţîờñ");
var decoded = utf8.decode([0x62, 0x6c, 0xc3, 0xa5, 0x62, 0xc3, 0xa6,
0x72, 0x67, 0x72, 0xc3, 0xb8, 0x64]);import 'raya:convert';
void main() {
const s = 'Raya · π ≈ 3.14';
final bytes = utf8.encode(s);
print('characters: ${s.length}, bytes: ${bytes.length}');
print('bytes: $bytes');
print('decoded: ${utf8.decode(bytes)}');
}characters: 15, bytes: 19 bytes: [82, 97, 121, 97, 32, 194, 183, 32, 207, 128, 32, 226, 137, 136, 32, 51, 46, 49, 52] decoded: Raya · π ≈ 3.14
Typedefs
typedef ByteConversionSinkBase = ByteConversionSinkThis class provides a base-class for converters that need to accept byte inputs.
typedef StringConversionSinkBase = StringConversionSinkThis class provides a base-class for converters that need to accept String inputs.
typedef StringConversionSinkMixin = StringConversionSinkThis class provides a mixin for converters that need to accept String inputs.
Classes
AsciiCodec
final class AsciiCodec extends Encoding
Encoding and decoding of ASCII characters.
An Encoding (conversion between strings and bytes) that converts ASCII characters (U+0000..U+007F) to and from their corresponding byte values.
Treats any non-ASCII character (U+0080..U+10FFFF) as an invalid input to endcoding, and any byte ≥ 128 as an invalid input to decoding.
Constructors
const AsciiCodec({this._allowInvalid = false})Instantiates a new AsciiCodec.
If _allowInvalid is true, the decode method and the converter returned by decoder will default to allowing invalid values, which are byte values greater than 127. If allowing invalid values, invalid values will be decoded to the Unicode Replacement character (U+FFFD). If not, a FormatException is be thrown. Calls to the decode method can choose to override this default.
Encoders will not accept invalid (non-ASCII) characters.
import 'raya:convert';
void main() {
const strict = AsciiCodec();
const lenient = AsciiCodec(allowInvalid: true);
print('encode: ${strict.encode('Hi!')}');
print('lenient decode of 200: ${lenient.decode([72, 200, 105]).codeUnits}');
try {
strict.decode([72, 200]);
} on FormatException {
print('strict decode of 200: FormatException');
}
}encode: [72, 105, 33] lenient decode of 200: [72, 65533, 105] strict decode of 200: FormatException
Properties
AsciiEncoder get encoderAsciiDecoder get decoderMethods
Uint8List encode(String source)import 'raya:convert';
void main() {
print("encode('ABC'): ${ascii.encode('ABC')}");
try {
ascii.encode('café');
} on ArgumentError {
print("encode('café'): ArgumentError (é is not ASCII)");
}
}encode('ABC'): [65, 66, 67]
encode('café'): ArgumentError (é is not ASCII)String decode(List<int> bytes, {bool? allowInvalid})Decodes the ASCII bytes (a list of unsigned 7-bit integers) to the corresponding string.
If bytes contains values that are not in the range 0.. 127, the decoder will eventually throw a FormatException.
If allowInvalid is not provided, it defaults to the value used to create this AsciiCodec.
import 'raya:convert';
void main() {
print('decode: ${ascii.decode([82, 97, 121, 97])}');
final s = ascii.decode([79, 75, 255], allowInvalid: true);
print('allowInvalid: ${s.codeUnits} (255 -> U+FFFD = 65533)');
}decode: Raya allowInvalid: [79, 75, 65533] (255 -> U+FFFD = 65533)
AsciiEncoder
final class AsciiEncoder extends _UnicodeSubsetEncoder
Converts strings of only ASCII characters to bytes.
Example:
const asciiEncoder = AsciiEncoder();
const sample = 'Raya';
final asciiValues = asciiEncoder.convert(sample);
print(asciiValues); // [68, 97, 114, 116]Constructors
const AsciiEncoder()import 'raya:convert';
void main() {
const enc = AsciiEncoder();
print('convert: ${enc.convert('Raya')}');
print('range 1..3: ${enc.convert('Raya', 1, 3)}');
}convert: [82, 97, 121, 97] range 1..3: [97, 121]
AsciiDecoder
final class AsciiDecoder extends _UnicodeSubsetDecoder
Converts ASCII bytes to string.
Example:
const asciiDecoder = AsciiDecoder();
final asciiValues = [68, 97, 114, 116];
final result = asciiDecoder.convert(asciiValues);
print(result); // Raya
Throws a FormatException if bytes contains values that are not in the range 0.. 127, and allowInvalid is false (the default).
If allowInvalid is true, any byte outside the range 0..127 is replaced by the Unicode replacement character, U+FFFD ('�').
Example with allowInvalid set to true:
const asciiDecoder = AsciiDecoder(allowInvalid: true);
final asciiValues = [68, 97, 114, 116, 20, 0xFF];
final result = asciiDecoder.convert(asciiValues);
print(result); // Raya �
print(result.codeUnits.last.toRadixString(16)); // fffdConstructors
const AsciiDecoder({bool allowInvalid = false})import 'raya:convert';
void main() {
const dec = AsciiDecoder();
print('convert: ${dec.convert([104, 105])}');
const lenient = AsciiDecoder(allowInvalid: true);
print('lenient: ${lenient.convert([104, 128, 105]).codeUnits}');
}convert: hi lenient: [104, 65533, 105]
Methods
ByteConversionSink startChunkedConversion(Sink<String> sink)Starts a chunked conversion.
The converter works more efficiently if the given sink is a StringConversionSink.
import 'raya:convert';
void main() {
final out = StringConversionSink.withCallback((s) => print('decoded: $s'));
final sink = const AsciiDecoder().startChunkedConversion(out);
sink.add([72, 101]);
sink.add([108, 108, 111]);
sink.close();
}decoded: Hello
Base64Codec
final class Base64Codec extends Codec<List<int>, String>
A base64 encoder and decoder.
A Base64Codec allows base64 encoding bytes into ASCII strings and decoding valid encodings back to bytes.
This implementation only handles the simplest RFC 4648 base64 and base64url encodings. It does not allow invalid characters when decoding and it requires, and generates, padding so that the input is always a multiple of four characters.
Constructors
const Base64Codec()import 'raya:convert';
void main() {
const codec = Base64Codec();
final text = codec.encode(utf8.encode('Raya'));
print('encode: $text');
print('decode: ${utf8.decode(codec.decode(text))}');
}encode: UmF5YQ== decode: Raya
const Base64Codec.urlSafe()import 'raya:convert';
void main() {
const url = Base64Codec.urlSafe();
final bytes = [0xfb, 0xff, 0xfe];
print('url-safe: ${url.encode(bytes)} (uses - and _)');
print('standard: ${base64.encode(bytes)} (uses + and /)');
}url-safe: -__- (uses - and _) standard: +//+ (uses + and /)
Properties
Base64Encoder get encoderBase64Decoder get decoderMethods
Uint8List decode(String encoded)Decodes encoded.
The input is decoded as if by decoder.convert.
The returned Uint8List contains exactly the decoded bytes, so the Uint8List.length is precisely the number of decoded bytes. The Uint8List.buffer may be larger than the decoded bytes.
import 'raya:convert';
void main() {
print('decode: ${base64.decode('AQID')}');
// Decoding accepts both alphabets.
print('url-safe input: ${base64.decode('-_8=')}');
}decode: [1, 2, 3] url-safe input: [251, 255]
String normalize(String source, [int start = 0, int? end])Validates and normalizes the base64 encoded data in source.
Only acts on the substring from start to end, with end defaulting to the end of the string.
Normalization will:
- Unescape any
%-escapes. - Only allow valid characters (
A-Z,a-z,0-9,/and+). - Normalize a
_or-character to/or+. - Validate that existing padding (trailing
=characters) is correct. - If no padding exists, add correct padding if necessary and possible.
- Validate that the length is correct (a multiple of four).
import 'raya:convert';
void main() {
print("normalize('SGk'): ${base64.normalize('SGk')} (padding added)");
print("normalize('-_8'): ${base64.normalize('-_8')} (url-safe chars mapped)");
print("base64Url.normalize('-_8'): ${base64Url.normalize('-_8')}");
print("decodes the same: ${base64.decode(base64.normalize('-_8'))}");
}normalize('SGk'): SGk= (padding added)
normalize('-_8'): +/8= (url-safe chars mapped)
base64Url.normalize('-_8'): +/8=
decodes the same: [251, 255]Base64Encoder
final class Base64Encoder extends Converter<List<int>, String>
Base64 and base64url encoding converter.
Encodes lists of bytes using base64 or base64url encoding.
The results are ASCII strings using a restricted alphabet.
Example:
final base64Encoder = base64.encoder;
const sample = 'Raya is open source';
final encodedSample = base64Encoder.convert(sample.codeUnits);
print(encodedSample); // RGFydCBpcyBvcGVuIHNvdXJjZQ==Constructors
const Base64Encoder()import 'raya:convert';
void main() {
const enc = Base64Encoder();
print('convert: ${enc.convert([1, 2, 3, 4])}');
}convert: AQIDBA==
const Base64Encoder.urlSafe()import 'raya:convert';
void main() {
const enc = Base64Encoder.urlSafe();
print('urlSafe: ${enc.convert([0xff, 0xef])}');
print('default: ${const Base64Encoder().convert([0xff, 0xef])}');
}urlSafe: _-8= default: /+8=
Methods
String convert(List<int> input)import 'raya:convert';
void main() {
final enc = base64.encoder;
for (final n in [1, 2, 3]) {
print('$n byte(s): ${enc.convert(List.filled(n, 77))}');
}
}1 byte(s): TQ== 2 byte(s): TU0= 3 byte(s): TU1N
ByteConversionSink startChunkedConversion(Sink<String> sink)import 'raya:convert';
void main() {
final parts = <String>[];
final sink = base64.encoder.startChunkedConversion(ChunkedConversionSink<String>.withCallback(parts.addAll));
sink.add([72, 101]);
sink.add([108, 108, 111]);
sink.close();
print('chunks: $parts');
print('joined: ${parts.join()} == ${base64Encode(utf8.encode('Hello'))}');
}chunks: [SGVs, bG8=] joined: SGVsbG8= == SGVsbG8=
Base64Decoder
final class Base64Decoder extends Converter<String, List<int>>
Decoder for base64 encoded data.
This decoder accepts both base64 and base64url ("url-safe") encodings.
The encoding is required to be properly padded.
Throws a FormatException if the input is not valid base64 data.
Example:
final base64Decoder = base64.decoder;
const base64Bytes = 'RGFydCBpcyBvcGVuIHNvdXJjZQ==';
final decodedBytes = base64Decoder.convert(base64Bytes);
// decodedBytes: [68, 97, 114, 116, 32, 105, 115, 32, 111, 112, 101, 110,
// 32, 115, 111, 117, 114, 99, 101]
// Print as string using UTF-8 decoder
print(utf8.decode(decodedBytes)); // Raya is open sourceConstructors
const Base64Decoder()import 'raya:convert';
void main() {
const dec = Base64Decoder();
print('convert: ${dec.convert('AAEC')}');
}convert: [0, 1, 2]
Methods
Uint8List convert(String input, [int start = 0, int? end])Decodes the characters of input from start to end as base64.
If start is omitted, it defaults to the start of input. If end is omitted, it defaults to the end of input.
The returned Uint8List contains exactly the decoded bytes, so the Uint8List.length is precisely the number of decoded bytes. The Uint8List.buffer may be larger than the decoded bytes.
import 'raya:convert';
void main() {
const text = 'data=SGVsbG8=;';
print('slice 5..13: ${utf8.decode(base64.decoder.convert(text, 5, 13))}');
}slice 5..13: Hello
StringConversionSink startChunkedConversion(Sink<List<int>> sink)import 'raya:convert';
void main() {
final out = ByteConversionSink.withCallback((bytes) => print('bytes: $bytes -> ${utf8.decode(bytes)}'));
final sink = base64.decoder.startChunkedConversion(out);
sink.add('SGVs');
sink.add('bG8=');
sink.close();
}bytes: [72, 101, 108, 108, 111] -> Hello
ByteConversionSink
abstract mixin class ByteConversionSink implements ChunkedConversionSink<List<int>>
The ByteConversionSink provides an interface for converters to efficiently transmit byte data.
Instead of limiting the interface to one non-chunked list of bytes it accepts its input in chunks (themselves being lists of bytes).
Constructors
const ByteConversionSink()import 'raya:convert';
// A sink that counts bytes; ByteConversionSink supplies addSlice.
class ByteCounter extends ByteConversionSink {
int count = 0;
@override
void add(List<int> chunk) => count += chunk.length;
@override
void close() => print('closed after $count bytes');
}
void main() {
final c = ByteCounter();
c.add([1, 2, 3]);
c.addSlice([9, 9, 9, 9, 9], 1, 3, true);
}closed after 5 bytes
factory ByteConversionSink.withCallback(void Function(List<int> accumulated) callback) = _ByteCallbackSinkimport 'raya:convert';
void main() {
final sink = ByteConversionSink.withCallback((all) => print('all bytes at close: $all'));
sink.add([1, 2]);
sink.add([3]);
print('nothing delivered yet');
sink.close();
}nothing delivered yet all bytes at close: [1, 2, 3]
factory ByteConversionSink.from(Sink<List<int>> sink) = _ByteAdapterSinkimport 'raya:convert';
class Collect implements Sink<List<int>> {
final chunks = <List<int>>[];
@override
void add(List<int> c) => chunks.add(c);
@override
void close() => print('chunks: $chunks');
}
void main() {
final sink = ByteConversionSink.from(Collect());
sink.add([1, 2]);
sink.addSlice([7, 8, 9], 0, 2, false);
sink.close();
}chunks: [[1, 2], [7, 8]]
Methods
void addSlice(List<int> chunk, int start, int end, bool isLast)Adds the next chunk to this.
Adds the bytes defined by start and end-exclusive to this.
If isLast is true closes this.
Contrary to add the given chunk must not be held onto. Once the method returns, it is safe to overwrite the data in it.
import 'raya:convert';
void main() {
final sink = ByteConversionSink.withCallback((all) => print('collected: $all'));
final buffer = [10, 20, 30, 40, 50];
sink.addSlice(buffer, 1, 3, false);
sink.addSlice(buffer, 4, 5, true); // isLast closes the sink
}collected: [20, 30, 50]
abstract interface class ChunkedConversionSink<T> implements Sink<T>
A ChunkedConversionSink is used to transmit data more efficiently between two converters during chunked conversions.
The basic ChunkedConversionSink is just a Sink, and converters should work with a plain Sink, but may work more efficiently with certain specialized types of ChunkedConversionSink.
Constructors
ChunkedConversionSink()import 'raya:convert';
class Summer implements ChunkedConversionSink<int> {
int total = 0;
@override
void add(int chunk) => total += chunk;
@override
void close() => print('total: $total');
}
void main() {
final ChunkedConversionSink<int> s = Summer();
[4, 5, 6].forEach(s.add);
s.close();
}total: 15
factory ChunkedConversionSink.withCallback(void Function(List<T> accumulated) callback) = _SimpleCallbackSink<T>import 'raya:convert';
void main() {
final sink = ChunkedConversionSink<String>.withCallback((all) => print('got ${all.length} chunks: $all'));
sink.add('a');
sink.add('b');
sink.close();
}got 2 chunks: [a, b]
Methods
void add(T chunk)Adds chunked data to this sink.
This method is also used when converters are used as StreamTransformers.
import 'raya:convert';
void main() {
// Feed a line splitter piece by piece; lines may span chunks.
final out = ChunkedConversionSink<String>.withCallback((lines) => print('lines: $lines'));
final sink = const LineSplitter().startChunkedConversion(out);
sink.add('first li');
sink.add('ne\nsecond\nthi');
sink.add('rd');
sink.close();
}lines: [first line, second, third]
void close()Closes the sink.
This signals the end of the chunked conversion. This method is called when converters are used as StreamTransformer's.
import 'raya:convert';
void main() {
final sink = ChunkedConversionSink<int>.withCallback((all) => print('callback runs on close: $all'));
sink.add(1);
print('before close');
sink.close();
print('after close');
}before close callback runs on close: [1] after close
Codec
abstract mixin class Codec<S, T>
A Codec encodes and (if supported) decodes data.
Codecs can be fused. For example fusing json and utf8 produces an encoder that can convert Json objects directly to bytes, or can decode bytes directly to json objects.
Fused codecs generally attempt to optimize the operations and can be faster than executing each step of an encoding separately.
The Codec class provides a default implementation of encode, decode, fuse and inverted. Subclasses can choose to provide more efficient implementations of these.
import 'raya:convert';
void main() {
// Codecs compose: JSON text -> UTF-8 bytes, and back.
final codec = json.fuse(utf8);
final bytes = codec.encode({'n': 1, 's': 'é'});
print('bytes: $bytes');
print('back: ${codec.decode(bytes)}');
}bytes: [123, 34, 110, 34, 58, 49, 44, 34, 115, 34, 58, 34, 195, 169, 34, 125]
back: {n: 1, s: é}Constructors
const Codec()import 'raya:convert';
class Rot13 extends Converter<String, String> {
const Rot13();
@override
String convert(String s) => String.fromCharCodes(s.codeUnits.map((c) {
if (c >= 97 && c <= 122) return (c - 97 + 13) % 26 + 97;
if (c >= 65 && c <= 90) return (c - 65 + 13) % 26 + 65;
return c;
}));
}
class Rot13Codec extends Codec<String, String> {
const Rot13Codec();
@override
Converter<String, String> get encoder => const Rot13();
@override
Converter<String, String> get decoder => const Rot13();
}
void main() {
const c = Rot13Codec();
print('encode: ${c.encode('Hello, Raya')}');
print('decode: ${c.decode(c.encode('Hello, Raya'))}');
}encode: Uryyb, Enln decode: Hello, Raya
Properties
Converter<S, T> get encoderReturns the encoder from S to T.
It may be stateful and should not be reused.
Converter<T, S> get decoderReturns the decoder of this, converting from T to S.
It may be stateful and should not be reused.
Codec<T, S> get invertedMethods
T encode(S input)Encodes input.
The input is encoded as if by encoder.convert.
import 'raya:convert';
void main() {
final Codec<String, List<int>> codec = utf8;
print("utf8.encode('€1'): ${codec.encode('€1')}");
print("json.encode: ${json.encode({'n': 1})}");
}utf8.encode('€1'): [226, 130, 172, 49]
json.encode: {"n":1}S decode(T encoded)Decodes encoded data.
The input is decoded as if by decoder.convert.
import 'raya:convert';
void main() {
print('utf8.decode: ${utf8.decode([0xe2, 0x82, 0xac, 0x31])}');
print("json.decode: ${json.decode('[1, 2, 3]')}");
}utf8.decode: €1 json.decode: [1, 2, 3]
Codec<S, R> fuse<R>(Codec<T, R> other)Fuses this with other.
When encoding, the resulting codec encodes with this before encoding with other.
When decoding, the resulting codec decodes with other before decoding with this.
In some cases one needs to use the inverted codecs to be able to fuse them correctly. That is, the output type of this (T) must match the input type of the second codec other.
Examples:
final jsonToBytes = json.fuse(utf8);
List<int> bytes = jsonToBytes.encode(["json-object"]);
var decoded = jsonToBytes.decode(bytes);
assert(decoded is List && decoded[0] == "json-object");
var inverted = json.inverted;
var jsonIdentity = json.fuse(inverted);
var jsonObject = jsonIdentity.encode(["1", 2]);
assert(jsonObject is List && jsonObject[0] == "1" && jsonObject[1] == 2);import 'raya:convert';
void main() {
// JSON text -> UTF-8 bytes -> base64, as one codec.
final codec = json.fuse(utf8).fuse(base64);
final packed = codec.encode({'id': 7, 'ok': true});
print('encoded: $packed');
print('decoded: ${codec.decode(packed)}');
}encoded: eyJpZCI6Nywib2siOnRydWV9
decoded: {id: 7, ok: true}Converter
abstract mixin class Converter<S, T> implements StreamTransformerBase<S, T>
A Converter converts data from one representation into another.
The Converter class provides a default implementation for every method other than convert.
Constructors
const Converter()import 'raya:convert';
class Celsius extends Converter<double, double> {
const Celsius();
@override
double convert(double fahrenheit) => (fahrenheit - 32) * 5 / 9;
}
void main() {
const c = Celsius();
for (final f in [32.0, 98.6, 212.0]) {
print('$f F = ${c.convert(f).toStringAsFixed(1)} C');
}
}32.0 F = 0.0 C 98.6 F = 37.0 C 212.0 F = 100.0 C
Static
static Converter<TS, TT> castFrom<SS, ST, TS, TT>(Converter<SS, ST> source)Adapts source to be a Converter<TS, TT>.
This allows source to be used at the new type, but at run-time it must satisfy the requirements of both the new type and its original type.
Conversion input must be both SS and TS and the output created by source for those input must be both ST and TT.
import 'raya:convert';
void main() {
final Converter<Object?, Object?> loose = Converter.castFrom<String, List<int>, Object?, Object?>(utf8.encoder);
print('through Object?: ${loose.convert('hi')}');
}through Object?: [104, 105]
Methods
T convert(S input)Converts input and returns the result of the conversion.
import 'raya:convert';
void main() {
final Converter<String, List<int>> enc = ascii.encoder;
print('ascii: ${enc.convert('ok')}');
final Converter<List<int>, String> dec = utf8.decoder;
print('utf8: ${dec.convert([0xc3, 0xa9, 0x21])}');
print('lines: ${const LineSplitter().convert('a\nb\r\nc')}');
}ascii: [111, 107] utf8: é! lines: [a, b, c]
Converter<S, TT> fuse<TT>(Converter<T, TT> other)Fuses this with other.
Encoding with the resulting converter is equivalent to converting with this before converting with other.
import 'raya:convert';
void main() {
final toBase64 = utf8.encoder.fuse(base64.encoder);
print("fused: ${toBase64.convert('Raya')}");
final roundTrip = utf8.encoder.fuse(utf8.decoder);
print("round trip: ${roundTrip.convert('naïve')}");
}fused: UmF5YQ== round trip: naïve
Sink<S> startChunkedConversion(Sink<T> sink)Starts a chunked conversion.
The returned sink serves as input for the long-running conversion. The given sink serves as output.
import 'raya:convert';
void main() {
final out = ChunkedConversionSink<String>.withCallback((parts) => print('base64: ${parts.join()}'));
final sink = utf8.encoder.fuse(base64.encoder).startChunkedConversion(out);
sink.add('Hel');
sink.add('lo');
sink.close();
}base64: SGVsbG8=
Stream<T> bind(Stream<S> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final bytes = Stream.fromIterable(['Ray', 'a!']);
final encoded = utf8.encoder.fuse(base64.encoder).bind(bytes);
print('chunks: ${await encoded.toList()}');
}chunks: [UmF5, YSE=]
Converter<RS, RT> cast<RS, RT>()Provides a Converter<RS, RT> view of this stream transformer.
The resulting transformer will check at run-time that all conversion inputs are actually instances of S, and it will check that all conversion output produced by this converter are actually instances of RT.
import 'raya:convert';
void main() {
final Converter<String, Object?> c = const JsonDecoder().cast<String, Object?>();
print('cast converter: ${c.convert('{"a": [1, 2]}')}');
}cast converter: {a: [1, 2]}Encoding
abstract class Encoding extends Codec<String, List<int>>
Open-ended set of encodings.
An encoding is a Codec encoding strings to lists of byte.
This class provides a default implementation of decodeStream, which is not incremental. It collects the entire input before decoding. Subclasses can choose to use that implementation, or implement a more efficient stream decoding.
Constructors
const Encoding()import 'raya:convert';
// A named Encoding that reuses Latin-1's converters.
class Western extends Encoding {
const Western();
@override
String get name => 'western';
@override
Converter<String, List<int>> get encoder => latin1.encoder;
@override
Converter<List<int>, String> get decoder => latin1.decoder;
}
void main() {
const Encoding e = Western();
print('${e.name}: encode café -> ${e.encode('café')}');
print('decode: ${e.decode([99, 97, 102, 233])}');
}western: encode café -> [99, 97, 102, 233] decode: café
Static
static Encoding? getByName(String? name)Returns an Encoding for a named character set.
The names used are the IANA official names for the character set (see IANA character sets). The names are case insensitive.
If character set is not supported null is returned.
import 'raya:convert';
void main() {
for (final n in ['utf-8', 'UTF8', 'iso-8859-1', 'us-ascii', 'klingon']) {
print('$n -> ${Encoding.getByName(n)?.name}');
}
}utf-8 -> utf-8 UTF8 -> null iso-8859-1 -> iso-8859-1 us-ascii -> us-ascii klingon -> null
Properties
Converter<String, List<int>> get encoderReturns the encoder from String to List<int>.
It may be stateful and should not be reused.
Converter<List<int>, String> get decoderReturns the decoder of this, converting from List<int> to String.
It may be stateful and should not be reused.
String get nameName of the encoding.
If the encoding is standardized, this is the lower-case version of one of the IANA official names for the character set (see http://www.iana.org/assignments/character-sets/character-sets.xml)
Methods
Future<String> decodeStream(Stream<List<int>> byteStream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
// The € sign's three bytes arrive split across chunks.
final chunks = Stream.fromIterable([
[0x31, 0xe2],
[0x82],
[0xac, 0x21]
]);
print('decoded: ${await utf8.decodeStream(chunks)}');
}decoded: 1€!
HtmlEscapeMode
final class HtmlEscapeMode
HTML escape modes.
Allows specifying a mode for HTML escaping that depends on the context where the escaped result is going to be used. The relevant contexts are:
- As text content of an HTML element.
- As value of a (single- or double-) quoted attribute value.
All modes require escaping of & (ampersand) characters, and may enable escaping of more characters.
Custom escape modes can be created using the HtmlEscapeMode.new constructor.
Example:
const htmlEscapeMode = HtmlEscapeMode(
name: 'custom',
escapeLtGt: true,
escapeQuot: false,
escapeApos: false,
escapeSlash: false,
);
const HtmlEscape htmlEscape = HtmlEscape(htmlEscapeMode);
String unescaped = 'Text & subject';
String escaped = htmlEscape.convert(unescaped);
print(escaped); // Text & subject
unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 > 1 and 1 < 10
unescaped = "Single-quoted: 'text'";
escaped = htmlEscape.convert(unescaped);
print(escaped); // Single-quoted: 'text'
unescaped = 'Double-quoted: "text"';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Double-quoted: "text"
unescaped = 'Path: /system/';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Path: /system/Constructors
const HtmlEscapeMode({this._name = "custom", this.escapeLtGt = false, this.escapeQuot = false, this.escapeApos = false, this.escapeSlash = false})Create a custom escaping mode.
The _name is only used as the result of toString, and defaults to 'custom' if not provided.
All modes escape &. The mode can further be set to escape < and > (escapeLtGt), " (escapeQuot), ' (escapeApos), and/or / (escapeSlash).
import 'raya:convert';
void main() {
const mode = HtmlEscapeMode(name: 'angles', escapeLtGt: true);
final esc = HtmlEscape(mode);
print(esc.convert('<b>"Tom" & Jerry</b>'));
print('mode: $mode');
}<b>"Tom" & Jerry</b> mode: angles
Static
static const HtmlEscapeMode unknown = HtmlEscapeMode._('unknown', true, true, true, true)Default escaping mode, which escapes all characters.
The result of such an escaping is usable both in element content and in any attribute value.
The escaping only works for elements with normal HTML content, and not, for example, for script or style element content, which require escapes matching their particular content syntax.
static const HtmlEscapeMode attribute = HtmlEscapeMode._('attribute', true, true, false, false)Escaping mode for text going into double-quoted HTML attribute values.
The result should not be used as the content of an unquoted or single-quoted attribute value.
Escapes double quotes (") but not single quotes ('), and escapes < and > characters because they are not allowed in strict XHTML attributes
static const HtmlEscapeMode sqAttribute = HtmlEscapeMode._('attribute', true, false, true, false)Escaping mode for text going into single-quoted HTML attribute values.
The result should not be used as the content of an unquoted or double-quoted attribute value.
Escapes single quotes (') but not double quotes ("), and escapes < and > characters because they are not allowed in strict XHTML attributes.
static const HtmlEscapeMode element = HtmlEscapeMode._('element', true, false, false, false)Escaping mode for text going into HTML element content.
The escaping only works for elements with normal HTML content, and not, for example, for script or style element content, which require escapes matching their particular content syntax.
Escapes < and > characters.
Properties
final bool escapeSlashWhether to escape "/" (forward slash, solidus).
Escaping a slash is recommended to avoid cross-site scripting attacks by the Open Web Application Security Project_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content)
Methods
String toString()import 'raya:convert';
void main() {
print(HtmlEscapeMode.unknown);
print(HtmlEscapeMode.attribute);
print(HtmlEscapeMode.element);
print(const HtmlEscapeMode(name: 'mine'));
}unknown attribute element mine
HtmlEscape
final class HtmlEscape extends Converter<String, String>
Converter which escapes characters with special meaning in HTML.
The converter finds characters that are significant in the HTML source and replaces them with corresponding HTML entities.
The characters that need escaping in HTML are:
&(ampersand) always needs to be escaped.<(less than) and>(greater than) when inside an element."(quote) when inside a double-quoted attribute value.'(apostrophe) when inside a single-quoted attribute value. Apostrophe is escaped as'instead of'since not all browsers understand'./(slash) is recommended to be escaped because it may be used to terminate an element in some HTML dialects.
Escaping > (greater than) isn't necessary, but the result is often found to be easier to read if greater-than is also escaped whenever less-than is.
Example:
const HtmlEscape htmlEscape = HtmlEscape();
String unescaped = 'Text & subject';
String escaped = htmlEscape.convert(unescaped);
print(escaped); // Text & subject
unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 > 1 and 1 < 10
unescaped = "Single-quoted: 'text'";
escaped = htmlEscape.convert(unescaped);
print(escaped); // Single-quoted: 'text'
unescaped = 'Double-quoted: "text"';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Double-quoted: "text"
unescaped = 'Path: /system/';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Path: /system/Constructors
const HtmlEscape([this.mode = HtmlEscapeMode.unknown])Create converter that escapes HTML characters.
If mode is provided as either HtmlEscapeMode.attribute or HtmlEscapeMode.element, only the corresponding subset of HTML characters is escaped. The default is to escape all HTML characters.
import 'raya:convert';
void main() {
const text = '<a href="x">Tom\'s & Jerry</a>';
print('unknown: ${const HtmlEscape().convert(text)}');
print('attribute: ${const HtmlEscape(HtmlEscapeMode.attribute).convert(text)}');
print('element: ${const HtmlEscape(HtmlEscapeMode.element).convert(text)}');
}unknown: <a href="x">Tom's & Jerry</a> attribute: <a href="x">Tom's & Jerry</a> element: <a href="x">Tom's & Jerry</a>
Properties
Methods
String convert(String text)import 'raya:convert';
void main() {
final user = '<script>alert(1)</script>';
print('<p>${htmlEscape.convert(user)}</p>');
}<p><script>alert(1)</script></p>
StringConversionSink startChunkedConversion(Sink<String> sink)import 'raya:convert';
void main() {
final out = StringConversionSink.withCallback((s) => print('escaped: $s'));
final sink = htmlEscape.startChunkedConversion(out);
sink.add('1 < 2');
sink.add(' & 3 > 2');
sink.close();
}escaped: 1 < 2 & 3 > 2
class JsonUnsupportedObjectError extends Error
Error thrown by JSON serialization if an object cannot be serialized.
The unsupportedObject field holds that object that failed to be serialized.
If an object isn't directly serializable, the serializer calls the toJson method on the object. If that call fails, the error will be stored in the cause field. If the call returns an object that isn't directly serializable, the cause is null.
Constructors
JsonUnsupportedObjectError(this.unsupportedObject, {this.cause, this.partialResult})import 'raya:convert';
class Point {
final int x, y;
Point(this.x, this.y);
}
void main() {
try {
jsonEncode({'p': Point(1, 2)});
} on JsonUnsupportedObjectError catch (e) {
print('unsupported: ${e.unsupportedObject is Point}');
}
final err = JsonUnsupportedObjectError(Point(0, 0), cause: 'no toJson');
print('cause: ${err.cause}');
}unsupported: true cause: no toJson
Properties
final String? partialResultThe partial result of the conversion, up until the error happened.
May be null.
Methods
String toString()import 'raya:convert';
void main() {
final e = JsonUnsupportedObjectError(#sym, cause: 'symbols have no JSON form');
print(e.toString().startsWith('Converting object to an encodable object failed'));
print('cause: ${e.cause}');
}true cause: symbols have no JSON form
JsonCyclicError
class JsonCyclicError extends JsonUnsupportedObjectError
Reports that an object could not be stringified due to cyclic references.
An object that references itself cannot be serialized by JsonCodec.encode/JsonEncoder.convert. When the cycle is detected, a JsonCyclicError is thrown.
Constructors
JsonCyclicError(super.object)The first object that was detected as part of a cycle.
import 'raya:convert';
void main() {
final list = <Object>[1];
list.add(list);
try {
jsonEncode(list);
} on JsonCyclicError catch (e) {
print('cyclic: ${identical(e.unsupportedObject, list)}');
}
}cyclic: true
Methods
String toString()import 'raya:convert';
void main() {
final m = <String, Object>{};
m['self'] = m;
try {
jsonEncode(m);
} on JsonCyclicError catch (e) {
print(e.toString());
}
}Cyclic error in JSON stringify
JsonCodec
final class JsonCodec extends Codec<Object?, String>
A JsonCodec encodes JSON objects to strings and decodes strings to JSON objects.
Examples:
var encoded = json.encode([1, 2, { "a": null }]);
var decoded = json.decode('["foo", { "bar": 499 }]');Constructors
const JsonCodec({this._reviver, this._toEncodable})Creates a JsonCodec with the given reviver and encoding function.
The _reviver function is called during decoding. It is invoked once for each object or list property that has been parsed. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.
If _reviver is omitted, it defaults to returning the value argument.
The _toEncodable function is used during encoding. It is invoked for values that are not directly encodable to a string (a value that is not a number, boolean, string, null, list or a map with string keys). The function must return an object that is directly encodable. The elements of a returned list and values of a returned map do not need to be directly encodable, and if they aren't, _toEncodable will be used on them as well. Please notice that it is possible to cause an infinite recursive regress in this way, by effectively creating an infinite data structure through repeated call to _toEncodable.
If _toEncodable is omitted, it defaults to a function that returns the result of calling .toJson on the unencodable object.
import 'raya:convert';
void main() {
final codec = JsonCodec(
toEncodable: (o) => o is DateTime ? o.toIso8601String() : o,
reviver: (k, v) => k == 'when' ? DateTime.parse(v as String) : v,
);
final text = codec.encode({'when': DateTime.utc(2026, 11, 29)});
print('encoded: $text');
print('revived year: ${(codec.decode(text)['when'] as DateTime).year}');
}encoded: {"when":"2026-11-29T00:00:00.000Z"}
revived year: 2026JsonCodec.withReviver(dynamic Function(Object? key, Object? value) reviver)Creates a JsonCodec with the given reviver.
The reviver function is called once for each object or list property that has been parsed during decoding. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.
import 'raya:convert';
void main() {
// A reviver turns "date" strings into DateTime values while decoding.
final codec = JsonCodec.withReviver((k, v) => k == 'date' ? DateTime.parse(v as String) : v);
final m = codec.decode('{"event": "launch", "date": "2026-11-29T12:00:00Z"}') as Map;
print(m['date'].runtimeType);
print((m['date'] as DateTime).year);
}DateTime 2026
Properties
JsonEncoder get encoderJsonDecoder get decoderMethods
dynamic decode(String source, {Object? Function(Object? key, Object? value)? reviver})Parses the string and returns the resulting Json object.
The optional reviver function is called once for each object or list property that has been parsed during decoding. The key argument is either the integer list index for a list property, the string map key for object properties, or null for the final result.
The default reviver (when not provided) is the identity function.
import 'raya:convert';
void main() {
final data = json.decode('{"name": "Ada", "langs": ["en", "fr"], "age": 36}');
print('name: ${data['name']}, langs: ${data['langs']}');
final doubled = json.decode('[1, 2, 3]', reviver: (k, v) => v is int ? v * 2 : v);
print('reviver doubled: $doubled');
}name: Ada, langs: [en, fr] reviver doubled: [2, 4, 6]
String encode(Object? value, {Object? Function(dynamic object)? toEncodable})Converts value to a JSON string.
If value contains objects that are not directly encodable to a JSON string (a value that is not a number, boolean, string, null, list or a map with string keys), the toEncodable function is used to convert it to an object that must be directly encodable.
If toEncodable is omitted, it defaults to a function that returns the result of calling .toJson on the unencodable object.
import 'raya:convert';
void main() {
print(json.encode({'a': 1, 'b': [true, null, 2.5], 'c': 'x"y'}));
print(json.encode(DateTime.utc(2026), toEncodable: (o) => (o as DateTime).year));
}{"a":1,"b":[true,null,2.5],"c":"x\"y"}
2026JsonEncoder
final class JsonEncoder extends Converter<Object?, String>
This class converts JSON objects to strings.
Example:
const JsonEncoder encoder = JsonEncoder();
const data = {'text': 'foo', 'value': '2'};
final String jsonString = encoder.convert(data);
print(jsonString); // {"text":"foo","value":"2"}
Example of pretty-printed output:
const JsonEncoder encoder = JsonEncoder.withIndent(' ');
const data = {'text': 'foo', 'value': '2'};
final String jsonString = encoder.convert(data);
print(jsonString);
// {
// "text": "foo",
// "value": "2"
// }Constructors
const JsonEncoder([Object? Function(dynamic object)? toEncodable])Creates a JSON encoder.
The JSON encoder handles numbers, strings, booleans, null, lists and maps with string keys directly.
Any other object is attempted converted by toEncodable to an object that is of one of the convertible types.
If toEncodable is omitted, it defaults to calling .toJson on the object.
import 'raya:convert';
void main() {
final enc = JsonEncoder((o) => o is Set ? o.toList() : o.toString());
print(enc.convert({'tags': {'a', 'b'}, 'when': Duration(minutes: 5)}));
}{"tags":["a","b"],"when":"0:05:00.000000"}const JsonEncoder.withIndent(this.indent, [Object? Function(dynamic object)? toEncodable])Creates a JSON encoder that creates multi-line JSON.
The encoding of elements of lists and maps are indented and put on separate lines. The indent string is prepended to these elements, once for each level of indentation.
If indent is null, the output is encoded as a single line.
The JSON encoder handles numbers, strings, booleans, null, lists and maps with string keys directly.
Any other object is attempted converted by toEncodable to an object that is of one of the convertible types.
If toEncodable is omitted, it defaults to calling .toJson on the object.
import 'raya:convert';
void main() {
const pretty = JsonEncoder.withIndent(' ');
print(pretty.convert({
'library': 'raya:convert',
'codecs': ['json', 'utf8', 'base64'],
}));
}{
"library": "raya:convert",
"codecs": [
"json",
"utf8",
"base64"
]
}Properties
final String? indentThe string used for indention.
When generating multi-line output, this string is inserted once at the beginning of each indented line for each level of indentation.
If null, the output is encoded as a single line.
Methods
String convert(Object? object)Converts object to a JSON String.
Directly serializable values are num, String, bool, and Null, as well as some List and Map values. For List, the elements must all be serializable. For Map, the keys must be String and the values must be serializable.
If a value of any other type is attempted to be serialized, the toEncodable function provided in the constructor is called with the value as argument. The result, which must be a directly serializable value, is serialized instead of the original value.
If the conversion throws, or returns a value that is not directly serializable, a JsonUnsupportedObjectError exception is thrown. If the call throws, the error is caught and stored in the JsonUnsupportedObjectError's cause field.
If a List or Map contains a reference to itself, directly or through other lists or maps, it cannot be serialized and a JsonCyclicError is thrown.
object should not change during serialization.
If an object is serialized more than once, convert may cache the text for it. In other words, if the content of an object changes after it is first serialized, the new values may not be reflected in the result.
import 'raya:convert';
void main() {
print(const JsonEncoder().convert([1, 'two', {'three': 3}]));
print(const JsonEncoder.withIndent(' ').convert({'k': [1, 2]}));
}[1,"two",{"three":3}]
{
"k": [
1,
2
]
}ChunkedConversionSink<Object?> startChunkedConversion(Sink<String> sink)Starts a chunked conversion.
The converter works more efficiently if the given sink is a StringConversionSink.
Returns a chunked-conversion sink that accepts at most one object. It is an error to invoke add more than once on the returned sink.
import 'raya:convert';
void main() {
final out = StringConversionSink.withCallback((s) => print('json: $s'));
final sink = const JsonEncoder().startChunkedConversion(out);
sink.add({'chunked': true, 'n': [1, 2]});
sink.close();
}json: {"chunked":true,"n":[1,2]}Stream<String> bind(Stream<Object?> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final objects = Stream<Object?>.fromIterable([{'id': 1}, [2, 3], 'four']);
await for (final text in const JsonEncoder().bind(objects)) {
print(text);
}
}{
"
id
":
1
}Converter<Object?, T> fuse<T>(Converter<String, T> other)import 'raya:convert';
void main() {
final toBytes = const JsonEncoder().fuse(utf8.encoder);
final bytes = toBytes.convert({'é': 1});
print('UTF-8 JSON bytes: $bytes');
}UTF-8 JSON bytes: [123, 34, 195, 169, 34, 58, 49, 125]
JsonUtf8Encoder
final class JsonUtf8Encoder extends Converter<Object?, List<int>>
Encoder that encodes a single object as a UTF-8 encoded JSON string.
This encoder works equivalently to first converting the object to a JSON string, and then UTF-8 encoding the string, but without creating an intermediate string.
Constructors
JsonUtf8Encoder([String? indent, dynamic Function(dynamic object)? toEncodable, int? bufferSize])Create converter.
If indent is non-null, the converter attempts to "pretty-print" the JSON, and uses indent as the indentation. Otherwise the result has no whitespace outside of string literals. If indent contains characters that are not valid JSON whitespace characters, the result will not be valid JSON. JSON whitespace characters are space (U+0020), tab (U+0009), line feed (U+000a) and carriage return (U+000d) (ECMA 404).
The bufferSize is the size of the internal buffers used to collect UTF-8 code units. If using startChunkedConversion, it will be the size of the chunks.
The JSON encoder handles numbers, strings, booleans, null, lists and maps directly.
Any other object is attempted converted by toEncodable to an object that is of one of the convertible types.
If toEncodable is omitted, it defaults to calling .toJson on the object.
import 'raya:convert';
void main() {
final enc = JsonUtf8Encoder(' ');
final bytes = enc.convert({'a': [1, 2]});
print(utf8.decode(bytes));
print('${bytes.length} bytes');
}{
"a": [
1,
2
]
}
23 bytesMethods
List<int> convert(Object? object)Convert object into UTF-8 encoded JSON.
import 'raya:convert';
void main() {
final bytes = JsonUtf8Encoder().convert(['€']);
print('bytes: $bytes');
print('same as utf8(jsonEncode): ${utf8.decode(bytes) == jsonEncode(['€'])}');
}bytes: [91, 34, 226, 130, 172, 34, 93] same as utf8(jsonEncode): true
ChunkedConversionSink<Object?> startChunkedConversion(Sink<List<int>> sink)Start a chunked conversion.
Only one object can be passed into the returned sink.
The argument sink will receive byte lists in sizes depending on the bufferSize passed to the constructor when creating this encoder.
import 'raya:convert';
void main() {
final out = ByteConversionSink.withCallback((b) => print('${b.length} bytes: ${utf8.decode(b)}'));
final sink = JsonUtf8Encoder().startChunkedConversion(out);
sink.add({'x': 1});
sink.close();
}7 bytes: {"x":1}Stream<List<int>> bind(Stream<Object?> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final chunks = await JsonUtf8Encoder().bind(Stream.value(<String, Object>{'ok': true})).toList();
print('decoded: ${utf8.decode(chunks.expand((c) => c).toList())}');
}decoded: {"ok":true}JsonDecoder
final class JsonDecoder extends Converter<String, Object?>
This class parses JSON strings and builds the corresponding objects.
A JSON input must be the JSON encoding of a single JSON value, which can be a list or map containing other values.
Throws FormatException if the input is not valid JSON text.
Example:
const JsonDecoder decoder = JsonDecoder();
const String jsonString = '''
{
"data": [{"text": "foo", "value": 1 },
{"text": "bar", "value": 2 }],
"text": "Raya"
}
''';
final Map<String, dynamic> object = decoder.convert(jsonString);
final item = object['data'][0];
print(item['text']); // foo
print(item['value']); // 1
print(object['text']); // Raya
When used as a StreamTransformer, the input stream may emit multiple strings. The concatenation of all of these strings must be a valid JSON encoding of a single JSON value.
Constructors
const JsonDecoder([Object? Function(Object? key, Object? value)? reviver])Constructs a new JsonDecoder.
The reviver may be null.
import 'raya:convert';
void main() {
final dec = JsonDecoder((k, v) => v is String ? v.toUpperCase() : v);
print(dec.convert('{"name": "ada", "n": 1}'));
}{name: ADA, n: 1}Methods
dynamic convert(String input)Converts the given JSON-string input to its corresponding object.
Parsed JSON values are of the types num, String, bool, Null, Lists of parsed JSON values or Maps from String to parsed JSON values.
If this was initialized with a reviver, then the parsing operation invokes the reviver on every object or list property that has been parsed. The arguments are the property name (String) or list index (int), and the value is the parsed value. The return value of the reviver is used as the value of that property instead the parsed value.
Throws FormatException if the input is not valid JSON text.
import 'raya:convert';
void main() {
print(const JsonDecoder().convert('[1, 2.5, "x", null, true]'));
try {
const JsonDecoder().convert('{bad}');
} on FormatException {
print('invalid JSON: FormatException');
}
}[1, 2.5, x, null, true] invalid JSON: FormatException
external StringConversionSink startChunkedConversion(Sink<Object?> sink)Starts a conversion from a chunked JSON string to its corresponding object.
The output sink receives exactly one decoded element through add.
import 'raya:convert';
void main() {
final out = ChunkedConversionSink<Object?>.withCallback((all) => print('decoded: ${all.single}'));
final sink = const JsonDecoder().startChunkedConversion(out);
sink.add('{"a": [1, ');
sink.add('2, 3], "b": "c"}');
sink.close();
}decoded: {a: [1, 2, 3], b: c}Stream<Object?> bind(Stream<String> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final pieces = Stream.fromIterable(['[10, ', '20, 30]']);
print('decoded: ${await const JsonDecoder().bind(pieces).single}');
}decoded: [10, 20, 30]
Latin1Codec
final class Latin1Codec extends Encoding
A Latin1Codec encodes strings to ISO Latin-1 (aka ISO-8859-1) bytes and decodes Latin-1 bytes to strings.
Constructors
const Latin1Codec({this._allowInvalid = false})Instantiates a new Latin1Codec.
If _allowInvalid is true, the decode method and the converter returned by decoder will default to allowing invalid values. Invalid values are decoded into the Unicode Replacement character (U+FFFD). Calls to the decode method can override this default.
Encoders will not accept invalid (non Latin-1) characters.
import 'raya:convert';
void main() {
const lenient = Latin1Codec(allowInvalid: true);
print('encode é: ${latin1.encode('é')}');
print('lenient decode of 300: ${lenient.decode([65, 300]).codeUnits}');
}encode é: [233] lenient decode of 300: [65, 65533]
Properties
Latin1Encoder get encoderLatin1Decoder get decoderMethods
Uint8List encode(String source)import 'raya:convert';
void main() {
print("encode('café'): ${latin1.encode('café')}");
try {
latin1.encode('€');
} on ArgumentError {
print("encode('€'): ArgumentError (outside Latin-1)");
}
}encode('café'): [99, 97, 102, 233]
encode('€'): ArgumentError (outside Latin-1)String decode(List<int> bytes, {bool? allowInvalid})Decodes the Latin-1 bytes (a list of unsigned 8-bit integers) to the corresponding string.
If bytes contains values that are not in the range 0.. 255, the decoder will eventually throw a FormatException.
If allowInvalid is not provided, it defaults to the value used to create this Latin1Codec.
import 'raya:convert';
void main() {
print('decode: ${latin1.decode([0x63, 0x61, 0x66, 0xe9])}');
print('every byte is valid: ${latin1.decode([0xa9, 0xb0]).codeUnits}');
}decode: café every byte is valid: [169, 176]
Latin1Encoder
final class Latin1Encoder extends _UnicodeSubsetEncoder
This class converts strings of only ISO Latin-1 characters to bytes.
Example:
final latin1Encoder = latin1.encoder;
const sample = 'àáâãäå';
final encoded = latin1Encoder.convert(sample);
print(encoded); // [224, 225, 226, 227, 228, 229]Constructors
const Latin1Encoder()import 'raya:convert';
void main() {
const enc = Latin1Encoder();
print('convert: ${enc.convert('ñandú')}');
}convert: [241, 97, 110, 100, 250]
Latin1Decoder
final class Latin1Decoder extends _UnicodeSubsetDecoder
This class converts Latin-1 bytes (lists of unsigned 8-bit integers) to a string.
Example:
final latin1Decoder = latin1.decoder;
const encodedBytes = [224, 225, 226, 227, 228, 229];
final decoded = latin1Decoder.convert(encodedBytes);
print(decoded); // àáâãäå
// Hexadecimal values as source
const hexBytes = [0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5];
final decodedHexBytes = latin1Decoder.convert(hexBytes);
print(decodedHexBytes); // àáâãäå
Throws a FormatException if the encoded input contains values that are not in the range 0.. 255 and allowInvalid is false ( the default ).
If allowInvalid is true, invalid bytes are converted to Unicode Replacement character U+FFFD (�).
Example with allowInvalid set to true:
const latin1Decoder = Latin1Decoder(allowInvalid: true);
const encodedBytes = [300];
final decoded = latin1Decoder.convert(encodedBytes);
print(decoded); // �Constructors
const Latin1Decoder({bool allowInvalid = false})Instantiates a new Latin1Decoder.
The optional allowInvalid argument defines how convert deals with invalid bytes.
If it is true, convert replaces invalid bytes with the Unicode Replacement character U+FFFD (�). Otherwise it throws a FormatException.
import 'raya:convert';
void main() {
const dec = Latin1Decoder();
print('convert: ${dec.convert([0xbf, 0x51, 0x75, 0xe9, 0x3f])}');
}convert: ¿Qué?
Methods
ByteConversionSink startChunkedConversion(Sink<String> sink)Starts a chunked conversion.
The converter works more efficiently if the given sink is a StringConversionSink.
import 'raya:convert';
void main() {
final out = StringConversionSink.withCallback((s) => print('decoded: $s'));
final sink = latin1.decoder.startChunkedConversion(out);
sink.add([0x63, 0x61]);
sink.add([0x66, 0xe9]);
sink.close();
}decoded: café
LineSplitter
final class LineSplitter extends StreamTransformerBase<String, String>
A StreamTransformer that splits a String into individual lines.
A line is terminated by either:
- A CR, carriage return: U+000D ('\r')
- A LF, line feed (Unix line break): U+000A ('\n') or
- A CR+LF sequence (DOS/Windows line break), and
- A final non-empty line can be ended by the end of the input.
The resulting lines do not contain the line terminators.
Example:
const splitter = LineSplitter();
const sampleText =
'Raya is: \r an object-oriented \n class-based \n garbage-collected '
'\r\n language with C-style syntax \r\n';
final sampleTextLines = splitter.convert(sampleText);
for (var i = 0; i < sampleTextLines.length; i++) {
print('$i: ${sampleTextLines[i]}');
}
// 0: Raya is:
// 1: an object-oriented
// 2: class-based
// 3: garbage-collected
// 4: language with C-style syntaximport 'raya:convert';
void main() {
const text = 'first line\r\nsecond line\nthird line';
final lines = const LineSplitter().convert(text);
for (final (i, l) in lines.indexed) {
print('${i + 1}: $l');
}
}1: first line 2: second line 3: third line
Constructors
const LineSplitter()import 'raya:convert';
void main() {
const splitter = LineSplitter();
print(splitter.convert('one\ntwo\r\nthree\rfour'));
}[one, two, three, four]
Static
static Iterable<String> split(String lines, [int start = 0, int? end])Split lines into individual lines.
If start and end are provided, only split the contents of lines.substring(start, end). The start and end values must specify a valid sub-range of lines (0 <= start <= end <= lines.length).
import 'raya:convert';
void main() {
final n = LineSplitter.split('a\nb\n\nc').length;
print('lines: $n');
print(LineSplitter.split('x\ny').toList());
}lines: 4 [x, y]
Methods
List<String> convert(String data)import 'raya:convert';
void main() {
final lines = const LineSplitter().convert('a\n\nb\n');
print('lines: $lines (no trailing empty line)');
print('count: ${lines.length}');
}lines: [a, , b] (no trailing empty line) count: 3
StringConversionSink startChunkedConversion(Sink<String> sink)import 'raya:convert';
void main() {
final out = ChunkedConversionSink<String>.withCallback((l) => print('lines: $l'));
final sink = const LineSplitter().startChunkedConversion(out);
sink.add('al');
sink.add('pha\r');
sink.add('\nbeta');
sink.close();
}lines: [alpha, beta]
Stream<String> bind(Stream<String> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final text = Stream.fromIterable(['first\nsec', 'ond\nthird']);
var n = 0;
await for (final line in const LineSplitter().bind(text)) {
print('${++n}: $line');
}
}1: first 2: second 3: third
StringConversionSink
abstract mixin class StringConversionSink implements ChunkedConversionSink<String>
A sink for converters to efficiently transmit String data.
Instead of limiting the interface to one non-chunked String it accepts partial strings or can be transformed into a byte sink that accepts UTF-8 code units.
The StringConversionSink class provides a default implementation of add, asUtf8Sink and asStringSink.
Constructors
const StringConversionSink()import 'raya:convert';
class Shout extends StringConversionSink {
final out = StringBuffer();
@override
void addSlice(String s, int start, int end, bool isLast) {
out.write(s.substring(start, end).toUpperCase());
if (isLast) close();
}
@override
void close() => print('shout: $out');
}
void main() {
final s = Shout()..add('hello ');
s.addSlice('xxworld!', 2, 8, true);
}shout: HELLO WORLD!
factory StringConversionSink.withCallback(void Function(String accumulated) callback) = _StringCallbackSinkimport 'raya:convert';
void main() {
final sink = StringConversionSink.withCallback((all) => print('accumulated: "$all"'));
sink.add('Ra');
sink.add('ya');
sink.close();
}accumulated: "Raya"
factory StringConversionSink.from(Sink<String> sink) = _StringAdapterSinkimport 'raya:convert';
class Lines implements Sink<String> {
final got = <String>[];
@override
void add(String s) => got.add(s);
@override
void close() => print('chunks: $got');
}
void main() {
final sink = StringConversionSink.from(Lines());
sink.add('one');
sink.addSlice('xtwox', 1, 4, false);
sink.close();
}chunks: [one, two]
factory StringConversionSink.fromStringSink(StringSink sink) = _StringSinkConversionSink<StringSink>Creates a new instance wrapping the given sink.
Every string that is added to the returned instance is forwarded to the sink. The instance is allowed to buffer and is not required to forward immediately.
import 'raya:convert';
void main() {
final buffer = StringBuffer();
final sink = StringConversionSink.fromStringSink(buffer);
sink.add('abc');
sink.addSlice('--def--', 2, 5, true);
print('buffer: $buffer');
}buffer: abcdef
Methods
void addSlice(String chunk, int start, int end, bool isLast)Adds the next chunk to this.
Adds the substring defined by start and end-exclusive to this.
If isLast is true closes this.
import 'raya:convert';
void main() {
final sink = StringConversionSink.withCallback((s) => print('got: $s'));
const text = 'ignore[keep]ignore';
sink.addSlice(text, 7, 11, false);
sink.addSlice('!', 0, 1, true);
}got: keep!
void add(String str)import 'raya:convert';
void main() {
final sink = StringConversionSink.withCallback((s) => print('total: ${s.length} chars, "$s"'));
for (final w in ['a', 'bc', 'def']) {
sink.add(w);
}
sink.close();
}total: 6 chars, "abcdef"
ByteConversionSink asUtf8Sink(bool allowMalformed)Returns this as a sink that accepts UTF-8 input.
If used, this method must be the first and only call to this. It invalidates this. All further operations must be performed on the result.
import 'raya:convert';
void main() {
final strings = StringConversionSink.withCallback((s) => print('text: $s'));
final bytes = strings.asUtf8Sink(false);
bytes.add([0x63, 0x61, 0x66, 0xc3]); // é is split in two
bytes.add([0xa9]);
bytes.close();
}text: café
ClosableStringSink asStringSink()Returns this as a ClosableStringSink.
If used, this method must be the first and only call to this. It invalidates this. All further operations must be performed on the result.
import 'raya:convert';
void main() {
final sink = StringConversionSink.withCallback((s) => print('collected: $s'));
final ClosableStringSink out = sink.asStringSink();
out.write('n=');
out.write(42);
out.writeCharCode(0x21);
out.close();
}collected: n=42!
ClosableStringSink
abstract interface class ClosableStringSink implements StringSink
A ClosableStringSink extends the StringSink interface by adding a close method.
Constructors
factory ClosableStringSink.fromStringSink(StringSink sink, void Function() onClose) = _ClosableStringSinkCreates a new instance combining a StringSink sink and a callback onClose which is invoked when the returned instance is closed.
import 'raya:convert';
void main() {
final buffer = StringBuffer();
final sink = ClosableStringSink.fromStringSink(buffer, () => print('closed; buffer = "$buffer"'));
sink.writeAll(['x', 'y', 'z'], ',');
sink.close();
}closed; buffer = "x,y,z"
Methods
void close()Closes this and flushes any outstanding data.
import 'raya:convert';
void main() {
var closed = false;
final sink = ClosableStringSink.fromStringSink(StringBuffer(), () => closed = true);
sink.writeln('line');
print('closed before: $closed');
sink.close();
print('closed after: $closed');
}closed before: false closed after: true
Utf8Codec
final class Utf8Codec extends Encoding
A Utf8Codec encodes strings to utf-8 code units (bytes) and decodes UTF-8 code units to strings.
Constructors
const Utf8Codec({this._allowMalformed = false})Instantiates a new Utf8Codec.
The optional _allowMalformed argument defines how decoder (and decode) deal with invalid or unterminated character sequences.
If it is true (and not overridden at the method invocation) decode and the decoder replace invalid (or unterminated) octet sequences with the Unicode Replacement character U+FFFD (�). Otherwise they throw a FormatException.
import 'raya:convert';
void main() {
const lenient = Utf8Codec(allowMalformed: true);
print('lenient: ${lenient.decode([0x61, 0xff, 0x62]).codeUnits}');
try {
utf8.decode([0x61, 0xff]);
} on FormatException {
print('strict: FormatException');
}
}lenient: [97, 65533, 98] strict: FormatException
Properties
Utf8Encoder get encoderUtf8Decoder get decoderMethods
String decode(List<int> codeUnits, {bool? allowMalformed})Decodes the UTF-8 codeUnits (a list of unsigned 8-bit integers) to the corresponding string.
If the codeUnits start with the encoding of a unicodeBomCharacterRune, that character is discarded.
If allowMalformed is true, the decoder replaces invalid (or unterminated) character sequences with the Unicode Replacement character U+FFFD (�). Otherwise it throws a FormatException.
If allowMalformed is not given, it defaults to the allowMalformed that was used to instantiate this.
import 'raya:convert';
void main() {
final bad = [0x48, 0x69, 0xFF];
print(utf8.decode(bad, allowMalformed: true));
try {
utf8.decode(bad);
} on FormatException catch (e) {
print('strict decode failed: ${e.message}');
}
}Hi� strict decode failed: Invalid UTF-8 byte
Uint8List encode(String string)Encodes the string as UTF-8.
import 'raya:convert';
void main() {
for (final s in ['A', 'é', '€', '😀']) {
print('$s -> ${utf8.encode(s)}');
}
}A -> [65] é -> [195, 169] € -> [226, 130, 172] 😀 -> [240, 159, 152, 128]
Utf8Encoder
final class Utf8Encoder extends Converter<String, List<int>>
This class converts strings to their UTF-8 code units (a list of unsigned 8-bit integers).
Example:
final utf8Encoder = utf8.encoder;
const sample = 'Îñţérñåţîöñåļîžåţîờñ';
final encodedSample = utf8Encoder.convert(sample);
print(encodedSample);Constructors
const Utf8Encoder()import 'raya:convert';
void main() {
const enc = Utf8Encoder();
print('convert: ${enc.convert('Ωmega')}');
}convert: [206, 169, 109, 101, 103, 97]
Methods
Uint8List convert(String string, [int start = 0, int? end])Converts string to its UTF-8 code units (a list of unsigned 8-bit integers).
If start and end are provided, only the substring string.substring(start, end) is converted.
Any unpaired surrogate character (U+D800-U+DFFF) in the input string is encoded as a Unicode Replacement character U+FFFD (�).
import 'raya:convert';
void main() {
print("whole: ${utf8.encoder.convert('a€b')}");
print("range 1..2: ${utf8.encoder.convert('a€b', 1, 2)}");
}whole: [97, 226, 130, 172, 98] range 1..2: [226, 130, 172]
StringConversionSink startChunkedConversion(Sink<List<int>> sink)Starts a chunked conversion.
The converter works more efficiently if the given sink is a ByteConversionSink.
import 'raya:convert';
void main() {
final out = ByteConversionSink.withCallback((b) => print('bytes: $b'));
final sink = utf8.encoder.startChunkedConversion(out);
sink.add('h');
sink.add('é');
sink.close();
}bytes: [104, 195, 169]
Stream<List<int>> bind(Stream<String> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final chunks = await utf8.encoder.bind(Stream.fromIterable(['a', 'ü'])).toList();
print('byte chunks: $chunks');
}byte chunks: [[97], [195, 188]]
Utf8Decoder
final class Utf8Decoder extends Converter<List<int>, String>
This class converts UTF-8 code units (lists of unsigned 8-bit integers) to a string.
Example:
final utf8Decoder = utf8.decoder;
const encodedBytes = [
195, 142, 195, 177, 197, 163, 195, 169, 114, 195, 177, 195, 165, 197,
163, 195, 174, 195, 182, 195, 177, 195, 165, 196, 188, 195, 174, 197,
190, 195, 165, 197, 163, 195, 174, 225, 187, 157, 195, 177];
final decodedBytes = utf8Decoder.convert(encodedBytes);
print(decodedBytes); // Îñţérñåţîöñåļîžåţîờñ
Throws a FormatException if the encoded input contains invalid UTF-8 byte sequences and allowMalformed is false (the default).
If allowMalformed is true, invalid byte sequences are converted into one or more Unicode replacement characters, U+FFFD ('�').
Example with allowMalformed set to true:
const utf8Decoder = Utf8Decoder(allowMalformed: true);
const encodedBytes = [0xFF];
final decodedBytes = utf8Decoder.convert(encodedBytes);
print(decodedBytes); // �Constructors
const Utf8Decoder({this._allowMalformed = false})Instantiates a new Utf8Decoder.
The optional _allowMalformed argument defines how convert deals with invalid or unterminated character sequences.
If it is true, convert replaces invalid (or unterminated) character sequences with the Unicode Replacement character U+FFFD (�). Otherwise it throws a FormatException.
import 'raya:convert';
void main() {
const dec = Utf8Decoder(allowMalformed: true);
print(dec.convert([0x68, 0x69, 0xc0]).codeUnits);
}[104, 105, 65533]
Methods
String convert(List<int> codeUnits, [int start = 0, int? end])Converts the UTF-8 codeUnits (a list of unsigned 8-bit integers) to the corresponding string.
Uses the code units from start to, but not including, end. If end is omitted, it defaults to codeUnits.length.
If the codeUnits start with the encoding of a unicodeBomCharacterRune, that character is discarded.
import 'raya:convert';
void main() {
final bytes = utf8.encode('xx€yy');
print('slice 2..5: ${utf8.decoder.convert(bytes, 2, 5)}');
}slice 2..5: €
ByteConversionSink startChunkedConversion(Sink<String> sink)Starts a chunked conversion.
The converter works more efficiently if the given sink is a StringConversionSink.
import 'raya:convert';
void main() {
final out = StringConversionSink.withCallback((s) => print('decoded: $s'));
final sink = utf8.decoder.startChunkedConversion(out);
sink.add([0xf0, 0x9f]); // half of 😀
sink.add([0x98, 0x80, 0x21]);
sink.close();
}decoded: 😀!
Stream<String> bind(Stream<List<int>> stream)import 'raya:async';
import 'raya:convert';
Future<void> main() async {
final bytes = Stream.fromIterable([
[0x63, 0xc3],
[0xa9]
]);
print('text: ${await utf8.decoder.bind(bytes).join()}');
}text: cé
external Converter<List<int>, T> fuse<T>(Converter<String, T> next)import 'raya:convert';
void main() {
// Bytes straight to JSON values.
final decode = utf8.decoder.fuse(json.decoder);
print(decode.convert(utf8.encode('{"π": 3.14}')));
}{π: 3.14}