Chromium Code Reviews| OLD | NEW |
|---|---|
| (Empty) | |
| 1 // Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 library convert.hex.encoder; | |
| 6 | |
| 7 import 'dart:convert'; | |
| 8 | |
| 9 import 'package:charcode/ascii.dart'; | |
| 10 | |
| 11 /// The canonical instance of [HexEncoder]. | |
| 12 const hexEncoder = const HexEncoder._(); | |
| 13 | |
| 14 /// A converter that encodes byte arrays into hexadecimal strings. | |
| 15 /// | |
| 16 /// This will throw a [RangeError] if the byte array has any digits that don't | |
| 17 /// fit in the gamut of a byte. | |
| 18 class HexEncoder extends Converter<List<int>, String> { | |
| 19 const HexEncoder._(); | |
| 20 | |
| 21 String convert(List<int> bytes) { | |
| 22 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.
| |
| 23 for (var byte in bytes) { | |
| 24 RangeError.checkValueInInterval(byte, 0, 255); | |
| 25 buffer.writeCharCode(_codeUnitForDigit(byte ~/ 16)); | |
| 26 buffer.writeCharCode(_codeUnitForDigit(byte % 16)); | |
| 27 } | |
| 28 return buffer.toString(); | |
| 29 } | |
| 30 | |
| 31 /// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit | |
| 32 /// [digit]. | |
| 33 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
| |
| 34 | |
| 35 ByteConversionSink startChunkedConversion(Sink<String> sink) => | |
| 36 new _HexEncoderSink(sink); | |
| 37 } | |
| 38 | |
| 39 /// A sink for chunked hexadecimal encoding. | |
| 40 class _HexEncoderSink extends ByteConversionSinkBase { | |
| 41 /// The underlying sink to which decoded byte arrays will be passed. | |
| 42 final Sink<String> _sink; | |
| 43 | |
| 44 _HexEncoderSink(this._sink); | |
| 45 | |
| 46 void add(List<int> chunk) { | |
| 47 _sink.add(hexEncoder.convert(chunk)); | |
| 48 } | |
|
Lasse Reichstein Nielsen
2015/09/23 08:32:04
Consider implementing the addSlice function (and h
nweiz
2015/09/23 22:04:21
Done.
| |
| 49 | |
| 50 void close() { | |
| 51 _sink.close(); | |
| 52 } | |
| 53 } | |
| OLD | NEW |