Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(256)

Side by Side Diff: lib/src/base64.dart

Issue 1159093002: Implement a Base64 codec (Closed) Base URL: https://github.com/dart-lang/crypto.git@master
Patch Set: Address some more stylistic/documentation comments from the codereview. Created 5 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 part of crypto;
2
3 const Base64Codec BASE64 = const Base64Codec();
4
5 const List<int> _decodeTable =
6 const [ -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -1, -2, -2,
7 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
8 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, 62, -2, 63,
9 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, 0, -2, -2,
10 -2, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
11 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -2, -2, -2, -2, 63,
12 -2, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
13 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -2, -2, -2, -2, -2,
14 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
15 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
16 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
17 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
18 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
19 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
20 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2,
21 -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 ];
22
23 const String _encodeTableUrlSafe =
24 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
25
26 const String _encodeTable =
27 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
28
29 const int _LINE_LENGTH = 76;
30 const int _PAD = 61; // '='
31 const int _CR = 13; // '\r'
32 const int _LF = 10; // '\n'
33
34 class Base64Codec extends Codec<List<int>, String> {
35
36 final bool _urlSafe;
37 final bool _addLineSeparator;
38
39 /**
40 * Instantiates a new [Base64Codec].
41 *
42 * The optional [urlSafe] argument specifies if [encoder] and [encode]
43 * should generate a string, that is safe to use in an URL.
44 *
45 * If `urlSafe` is `true` (and not overriden at the method invocation)
46 * the [encoder] and [encode] use '-' instead of '+' and '_' instead of '/'.
Søren Gjesse 2015/06/01 12:20:58 Please add a paragraph stating what the default va
Alexander Ivanov 2015/06/03 09:19:46 Done.
47 *
48 * The optional [addLineSeparator] argument specifies if the [encoder] and
49 * [encode] should add line separators.
50 *
51 * If `addLineSeparator` is `true` `encode` adds an
52 * optional line separator (CR + LF) for each 76 char output.
Søren Gjesse 2015/06/01 12:20:58 Should the line length be configurable. According
Søren Gjesse 2015/06/01 12:20:59 Please add a paragraph stating what the default va
Alexander Ivanov 2015/06/03 09:19:46 We can do that in a separate change.
Alexander Ivanov 2015/06/03 09:19:46 Done.
53 */
54 const Base64Codec({bool urlSafe: false, bool addLineSeparator: false})
55 : _urlSafe = urlSafe,
56 _addLineSeparator = addLineSeparator;
57
58 String get name => "base64";
59
60 String encode(List<int> bytes,
61 {bool urlSafe,
62 bool addLineSeparator}) {
63 if (urlSafe == null) urlSafe = _urlSafe;
64 if (addLineSeparator == null) addLineSeparator = _addLineSeparator;
65 return new Base64Encoder(urlSafe: urlSafe,
66 addLineSeparator: addLineSeparator).convert(bytes);
67
68
69 }
70
71 Base64Encoder get encoder => new Base64Encoder(
72 urlSafe: _urlSafe,
73 addLineSeparator: _addLineSeparator);
74
75 Base64Decoder get decoder => new Base64Decoder();
Søren Gjesse 2015/06/01 12:20:59 The decoder does not take _urlSafe. Should it and
Alexander Ivanov 2015/06/03 09:14:58 Done.
76
77 }
78
79 /**
80 * This class encodes byte strings (lists of unsigned
81 * 8-bit integers) to strings according to Base64.
82 */
83 class Base64Encoder extends Converter<List<int>, String> {
84 final bool _urlSafe;
85 final bool _addLineSeparator;
86
87 const Base64Encoder({bool urlSafe: false, bool addLineSeparator: false})
Søren Gjesse 2015/06/01 12:20:59 As this is also public it should have the same inf
Alexander Ivanov 2015/06/03 09:19:46 Done.
88 : _urlSafe = urlSafe,
89 _addLineSeparator = addLineSeparator;
90
91 /**
92 * Converts [bytes] to its Base64 representation as a string.
93 *
94 * if [start] and [end] are provided, only the sublist
95 * `bytes.sublist(start, end)` is converted.
96 */
97
98 String convert(List<int> bytes, [int start = 0, int end]) {
99 int bytes_length = bytes.length;
100 RangeError.checkValidRange(start, end, bytes_length);
101 if (end == null) end = bytes_length;
102 int length = end - start;
103 if (length == 0) {
104 return "";
105 }
106 final String lookup = _urlSafe ? _encodeTableUrlSafe : _encodeTable;
107 // Size of 24 bit chunks.
108 final int remainderLength = length.remainder(3);
109 final int chunkLength = length - remainderLength;
110 // Size of base output.
111 int baseOutputLength = ((length ~/3) * 4);
Søren Gjesse 2015/06/01 12:20:59 nit: Space before 3.
Alexander Ivanov 2015/06/03 09:19:47 Done.
112 int remainderOutputLength = ((remainderLength > 0) ? 4 : 0);
113 int outputLength = baseOutputLength + remainderOutputLength;
114 // Add extra for line separators.
115 if (_addLineSeparator) {
116 outputLength += ((outputLength - 1) ~/ _LINE_LENGTH) << 1;
117 }
118 List<int> out = new List<int>(outputLength);
119
120 // Encode 24 bit chunks.
121 int j = 0, i = start, c = 0;
122 while (i < chunkLength) {
123 int x = ((bytes[i++] << 16) & 0xFFFFFF) |
Søren Gjesse 2015/06/01 12:20:58 nit: Maybe write 0x00FFFFFF for "completeness".
Alexander Ivanov 2015/06/03 09:19:46 Done.
124 ((bytes[i++] << 8) & 0xFFFFFF) |
125 bytes[i++];
126 out[j++] = lookup.codeUnitAt(x >> 18);
127 out[j++] = lookup.codeUnitAt((x >> 12) & 0x3F);
128 out[j++] = lookup.codeUnitAt((x >> 6) & 0x3F);
129 out[j++] = lookup.codeUnitAt(x & 0x3f);
Søren Gjesse 2015/06/01 12:20:59 nit: Please be consistent 0x3f -> 0x3F
Alexander Ivanov 2015/06/03 09:19:47 Done.
130 // Add optional line separator for each 76 char output.
131 if (_addLineSeparator && ++c == 19 && j < outputLength - 2) {
132 out[j++] = _CR;
133 out[j++] = _LF;
134 c = 0;
135 }
136 }
137
138 // If input length if not a multiple of 3, encode remaining bytes and
139 // add padding.
140 if (remainderLength == 1) {
141 int x = bytes[i];
142 out[j++] = lookup.codeUnitAt(x >> 2);
143 out[j++] = lookup.codeUnitAt((x << 4) & 0x3F);
144 out[j++] = _PAD;
145 out[j++] = _PAD;
146 } else if (remainderLength == 2) {
147 int x = bytes[i];
148 int y = bytes[i + 1];
149 out[j++] = lookup.codeUnitAt(x >> 2);
150 out[j++] = lookup.codeUnitAt(((x << 4) | (y >> 4)) & 0x3F);
151 out[j++] = lookup.codeUnitAt((y << 2) & 0x3F);
152 out[j++] = _PAD;
153 }
154
155 return new String.fromCharCodes(out);
156 }
157
158 _Base64EncoderSink startChunkedConversion(Sink<String> sink) {
159 StringConversionSink stringSink;
160 if (sink is StringConversionSink) {
161 stringSink = sink;
162 } else {
163 stringSink = new StringConversionSink.from(sink);
164 }
165 return new _Base64EncoderSink(stringSink, _urlSafe, _addLineSeparator);
166 }
167 }
168
169 class _Base64EncoderSink extends ChunkedConversionSink<List<int>> {
170
171 final Base64Encoder _encoder;
172 final ChunkedConversionSink<String> _outSink;
173 final List<int> _buffer = new List<int>();
174 int _bufferCount = 0;
175
176 _Base64EncoderSink(this._outSink, urlSafe, addLineSeparator)
177 : _encoder = new Base64Encoder(urlSafe: urlSafe,
178 addLineSeparator: addLineSeparator);
179
180
181 void add(List<int> chunk) {
182 var nextBufferCount = (chunk.length + _bufferCount) % 3;
183
184 int decodableLength = _bufferCount + chunk.length - nextBufferCount;
185
186 if (_bufferCount + chunk.length > _buffer.length) {
187 _buffer.replaceRange(_bufferCount,
188 _buffer.length,
189 chunk.sublist(0, _buffer.length - _bufferCount));
190 _buffer.addAll(chunk.sublist(_buffer.length - _bufferCount));
191 } else {
192 _buffer.replaceRange(_bufferCount, _bufferCount + chunk.length, chunk);
193 }
194
195 _outSink.add(_encoder.convert(_buffer, 0, decodableLength));
196 _buffer.removeRange(0, decodableLength);
197 _bufferCount = nextBufferCount;
198 }
199
200 void close() {
201 if (_bufferCount > 0) {
202 _outSink.add(_encoder.convert(_buffer.sublist(0, _bufferCount)));
203 }
204 _outSink.close();
205 }
206 }
207
208 /**
209 * This class decodes strings to lists of bytes(lists of
210 * unsigned 8-bit integers) according to Base64.
211 */
212 class Base64Decoder extends Converter<String, List<int>> {
213 const Base64Decoder();
214
215 List<int> convert(String input, {bool alwaysPadding: false}) {
216 int length = input.length;
217 if (length == 0) {
218 return new List<int>(0);
219 }
220
221 // Count '\r', '\n' and illegal characters, For illegal characters,
222 // throw an exception.
223 int extrasLength = 0;
224 for (int i = 0; i < length; i++) {
225 int c = _decodeTable[input.codeUnitAt(i)];
226 if (c < 0) {
227 extrasLength++;
228 if (c == -2) {
229 throw new FormatException('Invalid character: ${input[i]}');
230 }
231 }
232 }
233
234 if ((length - extrasLength) % 4 != 0) {
235 throw new FormatException('''Size of Base 64 characters in Input
236 must be a multiple of 4''', input, length - extrasLength);
237 }
238
239 // Count pad characters.
240 int padLength = 0;
241 for (int i = length - 1; i >= 0; i--) {
242 int currentCodeUnit = input.codeUnitAt(i);
243 if (_decodeTable[currentCodeUnit] > 0) break;
244 if (currentCodeUnit == _PAD) padLength++;
245 }
246 int outputLength = (((length - extrasLength) * 6) >> 3) - padLength;
247 List<int> out = new List<int>(outputLength);
248
249 for (int i = 0, o = 0; o < outputLength; ) {
250 // Accumulate 4 valid 6 bit Base 64 characters into an int.
251 int x = 0;
252 for (int j = 4; j > 0; ) {
253 int c = _decodeTable[input.codeUnitAt(i++)];
254 if (c >= 0) {
255 x = ((x << 6) & 0xFFFFFF) | c;
256 j--;
257 }
258 }
259 out[o++] = x >> 16;
260 if (o < outputLength) {
261 out[o++] = (x >> 8) & 0xFF;
262 if (o < outputLength) out[o++] = x & 0xFF;
263 }
264 }
265
266 return out;
267 }
268
269 _Base64DecoderSink startChunkedConversion(Sink<List<int>> sink) {
270 if (sink is! ByteConversionSink) {
271 sink = new ByteConversionSink.from(sink);
272 }
273 return new _Base64DecoderSink(sink);
274 }
275 }
276
277
278 class _Base64DecoderSink extends ChunkedConversionSink<String> {
279
280 final Base64Decoder _decoder = new Base64Decoder();
281 final ChunkedConversionSink<List<int>> _outSink;
282 String _buffer = "";
283
284 _Base64DecoderSink(this._outSink);
285
286 void add(String chunk) {
287 int nextBufferLength = (chunk.length + _buffer.length) % 4;
288
289 if (chunk.length + _buffer.length >= 4) {
290 int remainder = chunk.length - nextBufferLength;
291 String decodable = _buffer + chunk.substring(0, remainder);
292 _buffer = chunk.substring(remainder);
293
294 _outSink.add(_decoder.convert(decodable));
295 } else {
296 _buffer += chunk;
297 }
298 }
299
300 void close() {
301 if (!_buffer.isEmpty) {
302 throw new FormatException(
303 "Size of Base 64 input must be a multiple of 4",
304 _buffer,
305 _buffer.length);
306 }
307 _outSink.close();
308 }
309 }
310
OLDNEW
« no previous file with comments | « lib/crypto.dart ('k') | lib/src/crypto_utils.dart » ('j') | test/base64_test.dart » ('J')

Powered by Google App Engine
This is Rietveld 408576698