Chromium Code Reviews| Index: lib/src/hex/encoder.dart |
| diff --git a/lib/src/hex/encoder.dart b/lib/src/hex/encoder.dart |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..cae55a09afcbe5180ec97fbf7d267ff5421fe61c |
| --- /dev/null |
| +++ b/lib/src/hex/encoder.dart |
| @@ -0,0 +1,53 @@ |
| +// Copyright (c) 2015, 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. |
| + |
| +library convert.hex.encoder; |
| + |
| +import 'dart:convert'; |
| + |
| +import 'package:charcode/ascii.dart'; |
| + |
| +/// The canonical instance of [HexEncoder]. |
| +const hexEncoder = const HexEncoder._(); |
| + |
| +/// A converter that encodes byte arrays into hexadecimal strings. |
| +/// |
| +/// This will throw a [RangeError] if the byte array has any digits that don't |
| +/// fit in the gamut of a byte. |
| +class HexEncoder extends Converter<List<int>, String> { |
| + const HexEncoder._(); |
| + |
| + String convert(List<int> bytes) { |
| + var buffer = new StringBuffer(); |
|
Lasse Reichstein Nielsen
2015/09/23 08:32:04
Use an Uint8List instead of a StringBuffer. String
nweiz
2015/09/23 22:04:21
Done.
|
| + for (var byte in bytes) { |
| + RangeError.checkValueInInterval(byte, 0, 255); |
| + buffer.writeCharCode(_codeUnitForDigit(byte ~/ 16)); |
| + buffer.writeCharCode(_codeUnitForDigit(byte % 16)); |
| + } |
| + return buffer.toString(); |
| + } |
| + |
| + /// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit |
| + /// [digit]. |
| + int _codeUnitForDigit(int digit) => digit < 10 ? digit + $0 : digit + $a - 10; |
|
Lasse Reichstein Nielsen
2015/09/23 08:32:04
Maybe just use "0123456789abcdef".codeUnitAt(digit
nweiz
2015/09/23 22:04:21
Will a memory read really be better than simple ar
Lasse Reichstein Nielsen
2015/09/24 08:07:01
It's not simple arithmetic - there is an unpredict
nweiz
2015/09/24 23:23:42
I'm going to leave this as-is for now. We can come
|
| + |
| + ByteConversionSink startChunkedConversion(Sink<String> sink) => |
| + new _HexEncoderSink(sink); |
| +} |
| + |
| +/// A sink for chunked hexadecimal encoding. |
| +class _HexEncoderSink extends ByteConversionSinkBase { |
| + /// The underlying sink to which decoded byte arrays will be passed. |
| + final Sink<String> _sink; |
| + |
| + _HexEncoderSink(this._sink); |
| + |
| + void add(List<int> chunk) { |
| + _sink.add(hexEncoder.convert(chunk)); |
| + } |
|
Lasse Reichstein Nielsen
2015/09/23 08:32:04
Consider implementing the addSlice function (and h
nweiz
2015/09/23 22:04:21
Done.
|
| + |
| + void close() { |
| + _sink.close(); |
| + } |
| +} |