RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Core libraries

JSON, UTF-8 and encodings

Codecs and converters: JSON, UTF-8, Latin-1, ASCII, Base64, HTML escaping and line splitting.

import 'raya:convert';
28 classes123 functions and methods121 of 176 documented110 runnable examples

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 &gt; 1 and 1 &lt; 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

base64Encodefunction
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.

Example
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])}');
}
Output
base64:     SGVsbG8sIFJheWEh
decoded:    Hello, Raya!
url-safe:   -__-
standard:   +//+
String base64UrlEncode(List<int> bytes)

Encodes bytes using base64url encoding.

Shorthand for base64url.encode(bytes).

Example
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))}');
}
Output
url-safe: -_-_AAE=
standard: +/+/AAE=
decodes back: [251, 255, 191, 0, 1]
base64Decodefunction
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.

Example
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}');
  }
}
Output
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
jsonEncodefunction
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}}
}
Example
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']));
}
Output
{"name":"Raya","year":2026,"tags":["exact","fast"],"stable":true,"parent":null}
[1,2.5,"three"]
jsonDecodefunction
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']); // false
Example
import '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}');
}
Output
id:     7
scores: [9.5, 8]
name:   Ada
types:  int, List<dynamic>

Constants and variables

asciiconstant
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]);
base64constant
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.

Example
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'));
}
Output
AAECAwQF
[0, 1, 2, 3, 4, 5]
AAECAwQF
base64Urlconstant
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=");
htmlEscapeconstant
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 &amp; 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.

Example
import 'raya:convert';

void main() {
  print(htmlEscape.convert('<a href="x">Tom & Jerry</a>'));
}
Output
&lt;a href=&quot;x&quot;&gt;Tom &amp; Jerry&lt;&#47;a&gt;
jsonconstant
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.

latin1constant
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]);
Example
import 'raya:convert';

void main() {
  print(latin1.encode('café'));
  print(latin1.decode([99, 97, 102, 233]));
  print(ascii.encode('ABC'));
}
Output
[99, 97, 102, 233]
café
[65, 66, 67]
const int unicodeReplacementCharacterRune = 0xFFFD

The Unicode Replacement character U+FFFD (�).

const int unicodeBomCharacterRune = 0xFEFF

The Unicode Byte Order Marker (BOM) character U+FEFF.

utf8constant
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]);
Example
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)}');
}
Output
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 = ByteConversionSink

This class provides a base-class for converters that need to accept byte inputs.

typedef StringConversionSinkBase = StringConversionSink

This class provides a base-class for converters that need to accept String inputs.

typedef StringConversionSinkMixin = StringConversionSink

This class provides a mixin for converters that need to accept String inputs.

Classes

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 &ge; 128 as an invalid input to decoding.

Constructors

AsciiCodecconstructor
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.

Example
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');
  }
}
Output
encode: [72, 105, 33]
lenient decode of 200: [72, 65533, 105]
strict decode of 200: FormatException

Properties

namegetter
String get name

The name of this codec is "us-ascii".

encodergetter
AsciiEncoder get encoder
decodergetter
AsciiDecoder get decoder

Methods

encodemethod
Uint8List encode(String source)
Example
import 'raya:convert';

void main() {
  print("encode('ABC'): ${ascii.encode('ABC')}");
  try {
    ascii.encode('café');
  } on ArgumentError {
    print("encode('café'): ArgumentError (é is not ASCII)");
  }
}
Output
encode('ABC'): [65, 66, 67]
encode('café'): ArgumentError (é is not ASCII)
decodemethod
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.

Example
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)');
}
Output
decode: Raya
allowInvalid: [79, 75, 65533] (255 -> U+FFFD = 65533)
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

AsciiEncoderconstructor
const AsciiEncoder()
Example
import 'raya:convert';

void main() {
  const enc = AsciiEncoder();
  print('convert: ${enc.convert('Raya')}');
  print('range 1..3: ${enc.convert('Raya', 1, 3)}');
}
Output
convert: [82, 97, 121, 97]
range 1..3: [97, 121]
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)); // fffd

Constructors

AsciiDecoderconstructor
const AsciiDecoder({bool allowInvalid = false})
Example
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}');
}
Output
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.

Example
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();
}
Output
decoded: Hello
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

Base64Codecconstructor
const Base64Codec()
Example
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))}');
}
Output
encode: UmF5YQ==
decode: Raya
const Base64Codec.urlSafe()
Example
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 /)');
}
Output
url-safe: -__- (uses - and _)
standard: +//+ (uses + and /)

Properties

encodergetter
Base64Encoder get encoder
decodergetter
Base64Decoder get decoder

Methods

decodemethod
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.

Example
import 'raya:convert';

void main() {
  print('decode: ${base64.decode('AQID')}');
  // Decoding accepts both alphabets.
  print('url-safe input: ${base64.decode('-_8=')}');
}
Output
decode: [1, 2, 3]
url-safe input: [251, 255]
normalizemethod
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).
Example
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'))}");
}
Output
normalize('SGk'): SGk= (padding added)
normalize('-_8'): +/8= (url-safe chars mapped)
base64Url.normalize('-_8'): +/8=
decodes the same: [251, 255]
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

Base64Encoderconstructor
const Base64Encoder()
Example
import 'raya:convert';

void main() {
  const enc = Base64Encoder();
  print('convert: ${enc.convert([1, 2, 3, 4])}');
}
Output
convert: AQIDBA==
const Base64Encoder.urlSafe()
Example
import 'raya:convert';

void main() {
  const enc = Base64Encoder.urlSafe();
  print('urlSafe: ${enc.convert([0xff, 0xef])}');
  print('default: ${const Base64Encoder().convert([0xff, 0xef])}');
}
Output
urlSafe: _-8=
default: /+8=

Methods

convertmethod
String convert(List<int> input)
Example
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))}');
  }
}
Output
1 byte(s): TQ==
2 byte(s): TU0=
3 byte(s): TU1N
ByteConversionSink startChunkedConversion(Sink<String> sink)
Example
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'))}');
}
Output
chunks: [SGVs, bG8=]
joined: SGVsbG8= == SGVsbG8=
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 source

Constructors

Base64Decoderconstructor
const Base64Decoder()
Example
import 'raya:convert';

void main() {
  const dec = Base64Decoder();
  print('convert: ${dec.convert('AAEC')}');
}
Output
convert: [0, 1, 2]

Methods

convertmethod
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.

Example
import 'raya:convert';

void main() {
  const text = 'data=SGVsbG8=;';
  print('slice 5..13: ${utf8.decode(base64.decoder.convert(text, 5, 13))}');
}
Output
slice 5..13: Hello
StringConversionSink startChunkedConversion(Sink<List<int>> sink)
Example
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();
}
Output
bytes: [72, 101, 108, 108, 111] -> Hello
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()
Example
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);
}
Output
closed after 5 bytes
factory ByteConversionSink.withCallback(void Function(List<int> accumulated) callback) = _ByteCallbackSink
Example
import '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();
}
Output
nothing delivered yet
all bytes at close: [1, 2, 3]
factory ByteConversionSink.from(Sink<List<int>> sink) = _ByteAdapterSink
Example
import '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();
}
Output
chunks: [[1, 2], [7, 8]]

Methods

addSlicemethod
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.

Example
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
}
Output
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()
Example
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();
}
Output
total: 15
factory ChunkedConversionSink.withCallback(void Function(List<T> accumulated) callback) = _SimpleCallbackSink<T>
Example
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();
}
Output
got 2 chunks: [a, b]

Methods

addmethod
void add(T chunk)

Adds chunked data to this sink.

This method is also used when converters are used as StreamTransformers.

Example
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();
}
Output
lines: [first line, second, third]
closemethod
void close()

Closes the sink.

This signals the end of the chunked conversion. This method is called when converters are used as StreamTransformer's.

Example
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');
}
Output
before close
callback runs on close: [1]
after close
class

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.

Example
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)}');
}
Output
bytes: [123, 34, 110, 34, 58, 49, 44, 34, 115, 34, 58, 34, 195, 169, 34, 125]
back:  {n: 1, s: é}

Constructors

Codecconstructor
const Codec()
Example
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'))}');
}
Output
encode: Uryyb, Enln
decode: Hello, Raya

Properties

encodergetter
Converter<S, T> get encoder

Returns the encoder from S to T.

It may be stateful and should not be reused.

decodergetter
Converter<T, S> get decoder

Returns the decoder of this, converting from T to S.

It may be stateful and should not be reused.

invertedgetter
Codec<T, S> get inverted

Inverts this.

The encoder and decoder of the resulting codec are swapped.

Methods

encodemethod
T encode(S input)

Encodes input.

The input is encoded as if by encoder.convert.

Example
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})}");
}
Output
utf8.encode('€1'): [226, 130, 172, 49]
json.encode: {"n":1}
decodemethod
S decode(T encoded)

Decodes encoded data.

The input is decoded as if by decoder.convert.

Example
import 'raya:convert';

void main() {
  print('utf8.decode: ${utf8.decode([0xe2, 0x82, 0xac, 0x31])}');
  print("json.decode: ${json.decode('[1, 2, 3]')}");
}
Output
utf8.decode: €1
json.decode: [1, 2, 3]
fusemethod
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);
Example
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)}');
}
Output
encoded: eyJpZCI6Nywib2siOnRydWV9
decoded: {id: 7, ok: true}
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

Converterconstructor
const Converter()
Example
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');
  }
}
Output
32.0 F = 0.0 C
98.6 F = 37.0 C
212.0 F = 100.0 C

Static

castFromstaticmethod
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.

Example
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')}');
}
Output
through Object?: [104, 105]

Methods

convertmethod
T convert(S input)

Converts input and returns the result of the conversion.

Example
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')}');
}
Output
ascii: [111, 107]
utf8: é!
lines: [a, b, c]
fusemethod
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.

Example
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')}");
}
Output
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.

Example
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();
}
Output
base64: SGVsbG8=
bindmethod
Stream<T> bind(Stream<S> stream)
Example
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()}');
}
Output
chunks: [UmF5, YSE=]
castmethod
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.

Example
import 'raya:convert';

void main() {
  final Converter<String, Object?> c = const JsonDecoder().cast<String, Object?>();
  print('cast converter: ${c.convert('{"a": [1, 2]}')}');
}
Output
cast converter: {a: [1, 2]}
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

Encodingconstructor
const Encoding()
Example
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])}');
}
Output
western: encode café -> [99, 97, 102, 233]
decode: café

Static

getByNamestaticmethod
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.

Example
import 'raya:convert';

void main() {
  for (final n in ['utf-8', 'UTF8', 'iso-8859-1', 'us-ascii', 'klingon']) {
    print('$n -> ${Encoding.getByName(n)?.name}');
  }
}
Output
utf-8 -> utf-8
UTF8 -> null
iso-8859-1 -> iso-8859-1
us-ascii -> us-ascii
klingon -> null

Properties

encodergetter
Converter<String, List<int>> get encoder

Returns the encoder from String to List<int>.

It may be stateful and should not be reused.

decodergetter
Converter<List<int>, String> get decoder

Returns the decoder of this, converting from List<int> to String.

It may be stateful and should not be reused.

namegetter
String get name

Name 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)
Example
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)}');
}
Output
decoded: 1€!
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 &amp; subject

unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 &gt; 1 and 1 &lt; 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

HtmlEscapeModeconstructor
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).

Example
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');
}
Output
&lt;b&gt;"Tom" &amp; Jerry&lt;/b&gt;
mode: angles

Static

unknownconstant
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.

attributeconstant
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

sqAttributeconstant
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.

elementconstant
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 escapeLtGt

Whether to escape '<' and '>'.

final bool escapeQuot

Whether to escape '"' (quote).

final bool escapeApos

Whether to escape "'" (apostrophe).

final bool escapeSlash

Whether 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

toStringmethod
String toString()
Example
import 'raya:convert';

void main() {
  print(HtmlEscapeMode.unknown);
  print(HtmlEscapeMode.attribute);
  print(HtmlEscapeMode.element);
  print(const HtmlEscapeMode(name: 'mine'));
}
Output
unknown
attribute
element
mine
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 &#39; instead of &apos; since not all browsers understand &apos;.
  • / (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 &amp; subject

unescaped = '10 > 1 and 1 < 10';
escaped = htmlEscape.convert(unescaped);
print(escaped); // 10 &gt; 1 and 1 &lt; 10

unescaped = "Single-quoted: 'text'";
escaped = htmlEscape.convert(unescaped);
print(escaped); // Single-quoted: &#39;text&#39;

unescaped = 'Double-quoted: "text"';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Double-quoted: &quot;text&quot;

unescaped = 'Path: /system/';
escaped = htmlEscape.convert(unescaped);
print(escaped); // Path: &#47;system&#47;

Constructors

HtmlEscapeconstructor
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.

Example
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)}');
}
Output
unknown:   &lt;a href=&quot;x&quot;&gt;Tom&#39;s &amp; Jerry&lt;&#47;a&gt;
attribute: &lt;a href=&quot;x&quot;&gt;Tom's &amp; Jerry&lt;/a&gt;
element:   &lt;a href="x"&gt;Tom's &amp; Jerry&lt;/a&gt;

Properties

modefield
final HtmlEscapeMode mode

The HtmlEscapeMode used by the converter.

Methods

convertmethod
String convert(String text)
Example
import 'raya:convert';

void main() {
  final user = '<script>alert(1)</script>';
  print('<p>${htmlEscape.convert(user)}</p>');
}
Output
<p>&lt;script&gt;alert(1)&lt;&#47;script&gt;</p>
StringConversionSink startChunkedConversion(Sink<String> sink)
Example
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();
}
Output
escaped: 1 &lt; 2 &amp; 3 &gt; 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})
Example
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}');
}
Output
unsupported: true
cause: no toJson

Properties

final Object? unsupportedObject

The object that could not be serialized.

causefield
final Object? cause

The exception thrown when trying to convert the object.

final String? partialResult

The partial result of the conversion, up until the error happened.

May be null.

Methods

toStringmethod
String toString()
Example
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}');
}
Output
true
cause: symbols have no JSON form
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

JsonCyclicErrorconstructor
JsonCyclicError(super.object)

The first object that was detected as part of a cycle.

Example
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)}');
  }
}
Output
cyclic: true

Methods

toStringmethod
String toString()
Example
import 'raya:convert';

void main() {
  final m = <String, Object>{};
  m['self'] = m;
  try {
    jsonEncode(m);
  } on JsonCyclicError catch (e) {
    print(e.toString());
  }
}
Output
Cyclic error in JSON stringify
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

JsonCodecconstructor
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.

Example
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}');
}
Output
encoded: {"when":"2026-11-29T00:00:00.000Z"}
revived year: 2026
JsonCodec.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.

Example
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);
}
Output
DateTime
2026

Properties

encodergetter
JsonEncoder get encoder
decodergetter
JsonDecoder get decoder

Methods

decodemethod
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.

Example
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');
}
Output
name: Ada, langs: [en, fr]
reviver doubled: [2, 4, 6]
encodemethod
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.

Example
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));
}
Output
{"a":1,"b":[true,null,2.5],"c":"x\"y"}
2026
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

JsonEncoderconstructor
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.

Example
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)}));
}
Output
{"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.

Example
import 'raya:convert';

void main() {
  const pretty = JsonEncoder.withIndent('  ');
  print(pretty.convert({
    'library': 'raya:convert',
    'codecs': ['json', 'utf8', 'base64'],
  }));
}
Output
{
  "library": "raya:convert",
  "codecs": [
    "json",
    "utf8",
    "base64"
  ]
}

Properties

indentfield
final String? indent

The 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

convertmethod
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.

Example
import 'raya:convert';

void main() {
  print(const JsonEncoder().convert([1, 'two', {'three': 3}]));
  print(const JsonEncoder.withIndent('  ').convert({'k': [1, 2]}));
}
Output
[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.

Example
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();
}
Output
json: {"chunked":true,"n":[1,2]}
bindmethod
Stream<String> bind(Stream<Object?> stream)
Example
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);
  }
}
Output
{
"
id
":
1
}
fusemethod
Converter<Object?, T> fuse<T>(Converter<String, T> other)
Example
import 'raya:convert';

void main() {
  final toBytes = const JsonEncoder().fuse(utf8.encoder);
  final bytes = toBytes.convert({'é': 1});
  print('UTF-8 JSON bytes: $bytes');
}
Output
UTF-8 JSON bytes: [123, 34, 195, 169, 34, 58, 49, 125]
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

JsonUtf8Encoderconstructor
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.

Example
import 'raya:convert';

void main() {
  final enc = JsonUtf8Encoder(' ');
  final bytes = enc.convert({'a': [1, 2]});
  print(utf8.decode(bytes));
  print('${bytes.length} bytes');
}
Output
{
 "a": [
  1,
  2
 ]
}
23 bytes

Methods

convertmethod
List<int> convert(Object? object)

Convert object into UTF-8 encoded JSON.

Example
import 'raya:convert';

void main() {
  final bytes = JsonUtf8Encoder().convert(['€']);
  print('bytes: $bytes');
  print('same as utf8(jsonEncode): ${utf8.decode(bytes) == jsonEncode(['€'])}');
}
Output
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.

Example
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();
}
Output
7 bytes: {"x":1}
bindmethod
Stream<List<int>> bind(Stream<Object?> stream)
Example
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())}');
}
Output
decoded: {"ok":true}
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

JsonDecoderconstructor
const JsonDecoder([Object? Function(Object? key, Object? value)? reviver])

Constructs a new JsonDecoder.

The reviver may be null.

Example
import 'raya:convert';

void main() {
  final dec = JsonDecoder((k, v) => v is String ? v.toUpperCase() : v);
  print(dec.convert('{"name": "ada", "n": 1}'));
}
Output
{name: ADA, n: 1}

Methods

convertmethod
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.

Example
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');
  }
}
Output
[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.

Example
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();
}
Output
decoded: {a: [1, 2, 3], b: c}
bindmethod
Stream<Object?> bind(Stream<String> stream)
Example
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}');
}
Output
decoded: [10, 20, 30]
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

Latin1Codecconstructor
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.

Example
import 'raya:convert';

void main() {
  const lenient = Latin1Codec(allowInvalid: true);
  print('encode é: ${latin1.encode('é')}');
  print('lenient decode of 300: ${lenient.decode([65, 300]).codeUnits}');
}
Output
encode é: [233]
lenient decode of 300: [65, 65533]

Properties

namegetter
String get name

The name of this codec, "iso-8859-1".

encodergetter
Latin1Encoder get encoder
decodergetter
Latin1Decoder get decoder

Methods

encodemethod
Uint8List encode(String source)
Example
import 'raya:convert';

void main() {
  print("encode('café'): ${latin1.encode('café')}");
  try {
    latin1.encode('€');
  } on ArgumentError {
    print("encode('€'): ArgumentError (outside Latin-1)");
  }
}
Output
encode('café'): [99, 97, 102, 233]
encode('€'): ArgumentError (outside Latin-1)
decodemethod
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.

Example
import 'raya:convert';

void main() {
  print('decode: ${latin1.decode([0x63, 0x61, 0x66, 0xe9])}');
  print('every byte is valid: ${latin1.decode([0xa9, 0xb0]).codeUnits}');
}
Output
decode: café
every byte is valid: [169, 176]
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

Latin1Encoderconstructor
const Latin1Encoder()
Example
import 'raya:convert';

void main() {
  const enc = Latin1Encoder();
  print('convert: ${enc.convert('ñandú')}');
}
Output
convert: [241, 97, 110, 100, 250]
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

Latin1Decoderconstructor
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.

Example
import 'raya:convert';

void main() {
  const dec = Latin1Decoder();
  print('convert: ${dec.convert([0xbf, 0x51, 0x75, 0xe9, 0x3f])}');
}
Output
convert: ¿Qué?

Methods

ByteConversionSink startChunkedConversion(Sink<String> sink)

Starts a chunked conversion.

The converter works more efficiently if the given sink is a StringConversionSink.

Example
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();
}
Output
decoded: café
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 syntax
Example
import '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');
  }
}
Output
1: first line
2: second line
3: third line

Constructors

LineSplitterconstructor
const LineSplitter()
Example
import 'raya:convert';

void main() {
  const splitter = LineSplitter();
  print(splitter.convert('one\ntwo\r\nthree\rfour'));
}
Output
[one, two, three, four]

Static

splitstaticmethod
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).

Example
import 'raya:convert';

void main() {
  final n = LineSplitter.split('a\nb\n\nc').length;
  print('lines: $n');
  print(LineSplitter.split('x\ny').toList());
}
Output
lines: 4
[x, y]

Methods

convertmethod
List<String> convert(String data)
Example
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}');
}
Output
lines: [a, , b] (no trailing empty line)
count: 3
StringConversionSink startChunkedConversion(Sink<String> sink)
Example
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();
}
Output
lines: [alpha, beta]
bindmethod
Stream<String> bind(Stream<String> stream)
Example
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');
  }
}
Output
1: first
2: second
3: third
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()
Example
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);
}
Output
shout: HELLO WORLD!
factory StringConversionSink.withCallback(void Function(String accumulated) callback) = _StringCallbackSink
Example
import 'raya:convert';

void main() {
  final sink = StringConversionSink.withCallback((all) => print('accumulated: "$all"'));
  sink.add('Ra');
  sink.add('ya');
  sink.close();
}
Output
accumulated: "Raya"
factory StringConversionSink.from(Sink<String> sink) = _StringAdapterSink
Example
import '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();
}
Output
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.

Example
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');
}
Output
buffer: abcdef

Methods

addSlicemethod
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.

Example
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);
}
Output
got: keep!
addmethod
void add(String str)
Example
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();
}
Output
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.

Example
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();
}
Output
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.

Example
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();
}
Output
collected: n=42!
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) = _ClosableStringSink

Creates a new instance combining a StringSink sink and a callback onClose which is invoked when the returned instance is closed.

Example
import 'raya:convert';

void main() {
  final buffer = StringBuffer();
  final sink = ClosableStringSink.fromStringSink(buffer, () => print('closed; buffer = "$buffer"'));
  sink.writeAll(['x', 'y', 'z'], ',');
  sink.close();
}
Output
closed; buffer = "x,y,z"

Methods

closemethod
void close()

Closes this and flushes any outstanding data.

Example
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');
}
Output
closed before: false
closed after:  true
final class Utf8Codec extends Encoding

A Utf8Codec encodes strings to utf-8 code units (bytes) and decodes UTF-8 code units to strings.

Constructors

Utf8Codecconstructor
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.

Example
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');
  }
}
Output
lenient: [97, 65533, 98]
strict: FormatException

Properties

namegetter
String get name

The name of this codec is "utf-8".

encodergetter
Utf8Encoder get encoder
decodergetter
Utf8Decoder get decoder

Methods

decodemethod
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.

Example
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}');
  }
}
Output
Hi�
strict decode failed: Invalid UTF-8 byte
encodemethod
Uint8List encode(String string)

Encodes the string as UTF-8.

Example
import 'raya:convert';

void main() {
  for (final s in ['A', 'é', '€', '😀']) {
    print('$s -> ${utf8.encode(s)}');
  }
}
Output
A -> [65]
é -> [195, 169]
€ -> [226, 130, 172]
😀 -> [240, 159, 152, 128]
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

Utf8Encoderconstructor
const Utf8Encoder()
Example
import 'raya:convert';

void main() {
  const enc = Utf8Encoder();
  print('convert: ${enc.convert('Ωmega')}');
}
Output
convert: [206, 169, 109, 101, 103, 97]

Methods

convertmethod
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 (�).

Example
import 'raya:convert';

void main() {
  print("whole: ${utf8.encoder.convert('a€b')}");
  print("range 1..2: ${utf8.encoder.convert('a€b', 1, 2)}");
}
Output
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.

Example
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();
}
Output
bytes: [104, 195, 169]
bindmethod
Stream<List<int>> bind(Stream<String> stream)
Example
import 'raya:async';
import 'raya:convert';

Future<void> main() async {
  final chunks = await utf8.encoder.bind(Stream.fromIterable(['a', 'ü'])).toList();
  print('byte chunks: $chunks');
}
Output
byte chunks: [[97], [195, 188]]
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

Utf8Decoderconstructor
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.

Example
import 'raya:convert';

void main() {
  const dec = Utf8Decoder(allowMalformed: true);
  print(dec.convert([0x68, 0x69, 0xc0]).codeUnits);
}
Output
[104, 105, 65533]

Methods

convertmethod
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.

Example
import 'raya:convert';

void main() {
  final bytes = utf8.encode('xx€yy');
  print('slice 2..5: ${utf8.decoder.convert(bytes, 2, 5)}');
}
Output
slice 2..5: €
ByteConversionSink startChunkedConversion(Sink<String> sink)

Starts a chunked conversion.

The converter works more efficiently if the given sink is a StringConversionSink.

Example
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();
}
Output
decoded: 😀!
bindmethod
Stream<String> bind(Stream<List<int>> stream)
Example
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()}');
}
Output
text: cé
fusemethod
external Converter<List<int>, T> fuse<T>(Converter<String, T> next)
Example
import 'raya:convert';

void main() {
  // Bytes straight to JSON values.
  final decode = utf8.decoder.fuse(json.decoder);
  print(decode.convert(utf8.encode('{"π": 3.14}')));
}
Output
{π: 3.14}