Skip to content

Commit

Permalink
Performance fix for Guid initializers (pauldemarco#552)
Browse files Browse the repository at this point in the history
* faster implementation of Guid._fromString

* also improved Guid._fromMacString

* faster non-hex char replacement method
  • Loading branch information
ezamagni authored Apr 18, 2020
1 parent 69db6dc commit 47067e4
Showing 1 changed file with 19 additions and 30 deletions.
49 changes: 19 additions & 30 deletions lib/src/guid.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,55 +18,44 @@ class Guid {

Guid.empty() : this._internal(new List.filled(16, 0));

static List<int> _fromMacString(input) {
var bytes = new List<int>.filled(16, 0);

static List<int> _fromMacString(String input) {
if (input == null) {
throw new ArgumentError("Input was null");
}
input = input.toLowerCase();

final RegExp regex = new RegExp('[0-9a-f]{2}');
Iterable<Match> matches = regex.allMatches(input);
input = _removeNonHexCharacters(input);
final bytes = hex.decode(input);

if (matches.length != 6) {
if (bytes.length != 6) {
throw new FormatException("The format is invalid: " + input);
}

int i = 0;
for (Match match in matches) {
var hexString = input.substring(match.start, match.end);
bytes[i] = hex.decode(hexString)[0];
i++;
}

return bytes;
return bytes + List<int>.filled(10, 0);
}

static List<int> _fromString(input) {
var bytes = new List<int>.filled(16, 0);
static List<int> _fromString(String input) {
if (input == null) {
throw new ArgumentError("Input was null");
}
if (input.length < 32) {
throw new FormatException("The format is invalid");
}
input = input.toLowerCase();

final RegExp regex = new RegExp('[0-9a-f]{2}');
Iterable<Match> matches = regex.allMatches(input);
if (matches.length != 16) {
input = _removeNonHexCharacters(input);
final bytes = hex.decode(input);

if (bytes.length != 16) {
throw new FormatException("The format is invalid");
}
int i = 0;
for (Match match in matches) {
var hexString = input.substring(match.start, match.end);
bytes[i] = hex.decode(hexString)[0];
i++;
}

return bytes;
}

static String _removeNonHexCharacters(String sourceString) {
return String.fromCharCodes(sourceString.runes.where((r) =>
(r >= 48 && r <= 57) // characters 0 to 9
|| (r >= 65 && r <= 70) // characters A to F
|| (r >= 97 && r <= 102) // characters a to f
));
}

static int _calcHashCode(List<int> bytes) {
const equality = const ListEquality<int>();
return equality.hash(bytes);
Expand Down

0 comments on commit 47067e4

Please sign in to comment.