From 47067e41b921268ca8e257a0f7a45f45e0778f8e Mon Sep 17 00:00:00 2001 From: Enrico Zamagni Date: Sat, 18 Apr 2020 23:44:35 +0200 Subject: [PATCH] Performance fix for Guid initializers (#552) * faster implementation of Guid._fromString * also improved Guid._fromMacString * faster non-hex char replacement method --- lib/src/guid.dart | 49 ++++++++++++++++++----------------------------- 1 file changed, 19 insertions(+), 30 deletions(-) diff --git a/lib/src/guid.dart b/lib/src/guid.dart index 2a1b0457..10fbb350 100644 --- a/lib/src/guid.dart +++ b/lib/src/guid.dart @@ -18,55 +18,44 @@ class Guid { Guid.empty() : this._internal(new List.filled(16, 0)); - static List _fromMacString(input) { - var bytes = new List.filled(16, 0); - + static List _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 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.filled(10, 0); } - static List _fromString(input) { - var bytes = new List.filled(16, 0); + static List _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 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 bytes) { const equality = const ListEquality(); return equality.hash(bytes);