-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
ascii.dart
291 lines (255 loc) · 9.49 KB
/
ascii.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
part of dart.convert;
/// An instance of the default implementation of the [AsciiCodec].
///
/// This instance provides a convenient access to the most common ASCII
/// use cases.
///
/// Examples:
/// ```dart
/// 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 AsciiCodec ascii = AsciiCodec();
const int _asciiMask = 0x7F;
/// An [AsciiCodec] allows encoding strings as ASCII bytes
/// and decoding ASCII bytes to strings.
class AsciiCodec extends Encoding {
final bool _allowInvalid;
/// Instantiates a new [AsciiCodec].
///
/// If [allowInvalid] is true, the [decode] method and the converter
/// returned by [decoder] will default to allowing invalid values.
/// If allowing invalid values, the values will be decoded into the Unicode
/// Replacement character (U+FFFD). If not, an exception will be thrown.
/// Calls to the [decode] method can choose to override this default.
///
/// Encoders will not accept invalid (non ASCII) characters.
const AsciiCodec({bool allowInvalid = false}) : _allowInvalid = allowInvalid;
/// The name of this codec, "us-ascii".
String get name => "us-ascii";
Uint8List encode(String source) => encoder.convert(source);
/// 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].
String decode(List<int> bytes, {bool? allowInvalid}) {
if (allowInvalid ?? _allowInvalid) {
return const AsciiDecoder(allowInvalid: true).convert(bytes);
} else {
return const AsciiDecoder(allowInvalid: false).convert(bytes);
}
}
AsciiEncoder get encoder => const AsciiEncoder();
AsciiDecoder get decoder => _allowInvalid
? const AsciiDecoder(allowInvalid: true)
: const AsciiDecoder(allowInvalid: false);
}
// Superclass for [AsciiEncoder] and [Latin1Encoder].
// Generalizes common operations that only differ by a mask;
class _UnicodeSubsetEncoder extends Converter<String, List<int>> {
final int _subsetMask;
const _UnicodeSubsetEncoder(this._subsetMask);
/// Converts the [String] into a list of its code units.
///
/// If [start] and [end] are provided, only the substring
/// `string.substring(start, end)` is used as input to the conversion.
Uint8List convert(String string, [int start = 0, int? end]) {
var stringLength = string.length;
end = RangeError.checkValidRange(start, end, stringLength);
// TODO(38725): Remove workaround when assignment promotion is implemented
if (end == null) {
throw RangeError("Invalid range");
}
var length = end - start;
var result = Uint8List(length);
for (var i = 0; i < length; i++) {
var codeUnit = string.codeUnitAt(start + i);
if ((codeUnit & ~_subsetMask) != 0) {
throw ArgumentError.value(
string, "string", "Contains invalid characters.");
}
result[i] = codeUnit;
}
return result;
}
/// Starts a chunked conversion.
///
/// The converter works more efficiently if the given [sink] is a
/// [ByteConversionSink].
StringConversionSink startChunkedConversion(Sink<List<int>> sink) {
return _UnicodeSubsetEncoderSink(_subsetMask,
sink is ByteConversionSink ? sink : ByteConversionSink.from(sink));
}
// Override the base-class' bind, to provide a better type.
Stream<List<int>> bind(Stream<String> stream) => super.bind(stream);
}
/// This class converts strings of only ASCII characters to bytes.
class AsciiEncoder extends _UnicodeSubsetEncoder {
const AsciiEncoder() : super(_asciiMask);
}
/// This class encodes chunked strings to bytes (unsigned 8-bit
/// integers).
class _UnicodeSubsetEncoderSink extends StringConversionSinkBase {
final ByteConversionSink _sink;
final int _subsetMask;
_UnicodeSubsetEncoderSink(this._subsetMask, this._sink);
void close() {
_sink.close();
}
void addSlice(String source, int start, int end, bool isLast) {
RangeError.checkValidRange(start, end, source.length);
for (var i = start; i < end; i++) {
var codeUnit = source.codeUnitAt(i);
if ((codeUnit & ~_subsetMask) != 0) {
throw ArgumentError(
"Source contains invalid character with code point: $codeUnit.");
}
}
_sink.add(source.codeUnits.sublist(start, end));
if (isLast) {
close();
}
}
}
/// This class converts Latin-1 bytes (lists of unsigned 8-bit integers)
/// to a string.
abstract class _UnicodeSubsetDecoder extends Converter<List<int>, String> {
final bool _allowInvalid;
final int _subsetMask;
/// Instantiates a new decoder.
///
/// The [_allowInvalid] argument defines how [convert] deals
/// with invalid bytes.
///
/// The [_subsetMask] argument is a bit mask used to define the subset
/// of Unicode being decoded. Use [_LATIN1_MASK] for Latin-1 (8-bit) or
/// [_asciiMask] for ASCII (7-bit).
///
/// If [_allowInvalid] is `true`, [convert] replaces invalid bytes with the
/// Unicode Replacement character `U+FFFD` (�).
/// Otherwise it throws a [FormatException].
const _UnicodeSubsetDecoder(this._allowInvalid, this._subsetMask);
/// Converts the [bytes] (a list of unsigned 7- or 8-bit integers) to the
/// corresponding string.
///
/// If [start] and [end] are provided, only the sub-list of bytes from
/// `start` to `end` (`end` not inclusive) is used as input to the conversion.
String convert(List<int> bytes, [int start = 0, int? end]) {
end = RangeError.checkValidRange(start, end, bytes.length);
// TODO(38725): Remove workaround when assignment promotion is implemented
if (end == null) {
throw RangeError("Invalid range");
}
for (var i = start; i < end; i++) {
var byte = bytes[i];
if ((byte & ~_subsetMask) != 0) {
if (!_allowInvalid) {
throw FormatException("Invalid value in input: $byte");
}
return _convertInvalid(bytes, start, end);
}
}
return String.fromCharCodes(bytes, start, end);
}
String _convertInvalid(List<int> bytes, int start, int end) {
var buffer = StringBuffer();
for (var i = start; i < end; i++) {
var value = bytes[i];
if ((value & ~_subsetMask) != 0) value = 0xFFFD;
buffer.writeCharCode(value);
}
return buffer.toString();
}
/// Starts a chunked conversion.
///
/// The converter works more efficiently if the given [sink] is a
/// [StringConversionSink].
ByteConversionSink startChunkedConversion(Sink<String> sink);
// Override the base-class's bind, to provide a better type.
Stream<String> bind(Stream<List<int>> stream) => super.bind(stream);
}
class AsciiDecoder extends _UnicodeSubsetDecoder {
const AsciiDecoder({bool allowInvalid = false})
: super(allowInvalid, _asciiMask);
/// Starts a chunked conversion.
///
/// The converter works more efficiently if the given [sink] is a
/// [StringConversionSink].
ByteConversionSink startChunkedConversion(Sink<String> sink) {
StringConversionSink stringSink;
if (sink is StringConversionSink) {
stringSink = sink;
} else {
stringSink = StringConversionSink.from(sink);
}
// TODO(lrn): Use asUtf16Sink when it becomes available. It
// works just as well, is likely to have less decoding overhead,
// and make adding U+FFFD easier.
// At that time, merge this with _Latin1DecoderSink;
if (_allowInvalid) {
return _ErrorHandlingAsciiDecoderSink(stringSink.asUtf8Sink(false));
} else {
return _SimpleAsciiDecoderSink(stringSink);
}
}
}
class _ErrorHandlingAsciiDecoderSink extends ByteConversionSinkBase {
ByteConversionSink _utf8Sink;
_ErrorHandlingAsciiDecoderSink(this._utf8Sink);
void close() {
_utf8Sink.close();
}
void add(List<int> source) {
addSlice(source, 0, source.length, false);
}
void addSlice(List<int> source, int start, int end, bool isLast) {
RangeError.checkValidRange(start, end, source.length);
for (var i = start; i < end; i++) {
if ((source[i] & ~_asciiMask) != 0) {
if (i > start) _utf8Sink.addSlice(source, start, i, false);
// Add UTF-8 encoding of U+FFFD.
_utf8Sink.add(const <int>[0xEF, 0xBF, 0xBD]);
start = i + 1;
}
}
if (start < end) {
_utf8Sink.addSlice(source, start, end, isLast);
} else if (isLast) {
close();
}
}
}
class _SimpleAsciiDecoderSink extends ByteConversionSinkBase {
Sink _sink;
_SimpleAsciiDecoderSink(this._sink);
void close() {
_sink.close();
}
void add(List<int> source) {
for (var i = 0; i < source.length; i++) {
if ((source[i] & ~_asciiMask) != 0) {
throw FormatException("Source contains non-ASCII bytes.");
}
}
_sink.add(String.fromCharCodes(source));
}
void addSlice(List<int> source, int start, int end, bool isLast) {
final length = source.length;
RangeError.checkValidRange(start, end, length);
if (start < end) {
if (start != 0 || end != length) {
source = source.sublist(start, end);
}
add(source);
}
if (isLast) close();
}
}