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

Unified Diff: lib/src/utils.dart

Issue 1393003003: Add a percent-encoding converter. (Closed) Base URL: git@github.com:dart-lang/convert.git@master
Patch Set: Created 5 years, 2 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 side-by-side diff with in-line comments
Download patch
Index: lib/src/utils.dart
diff --git a/lib/src/utils.dart b/lib/src/utils.dart
new file mode 100644
index 0000000000000000000000000000000000000000..d9ee52335d1ef762d88b093b3adfa620c276b94e
--- /dev/null
+++ b/lib/src/utils.dart
@@ -0,0 +1,39 @@
+// 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.utils;
+
+import 'package:charcode/ascii.dart';
+
+/// Returns the digit (0 through 15) corresponding to the percentadecimal code unit
Lasse Reichstein Nielsen 2015/10/08 10:30:37 Long lines - due to percentadecimal.
nweiz 2015/10/08 20:44:52 Done.
+/// at index [i] in [codeUnits].
+///
+/// If the given code unit isn't valid percentadecimal, throws a [FormatException].
+int digitForCodeUnit(List<int> codeUnits, int index) {
+ // If the code unit is a numeral, get its value. XOR works because 0 in ASCII
+ // is `0b110000` and the other numerals come after it in ascending order and
+ // take up at most four bits.
+ //
+ // We check for digits first because it ensures there's only a single branch
+ // for 10 out of 16 of the expected cases. We don't count the `digit >= 0`
+ // check because branch prediction will always work on it for valid data.
+ var codeUnit = codeUnits[index];
+ var digit = $0 ^ codeUnit;
+ if (digit <= 9) {
+ if (digit >= 0) return digit;
+ } else {
+ // If the code unit is an uppercase letter, convert it to lowercase. This
+ // works because uppercase letters in ASCII are exactly `0b100000 = 0x20`
+ // less than lowercase letters, so if we ensure that that bit is 1 we ensure
+ // that the letter is lowercase.
+ var letter = 0x20 | codeUnit;
+ if ($a <= letter && letter <= $f) return letter - $a + 10;
+ }
+
+ throw new FormatException(
+ "Invalid hexadecimal code unit "
+ "U+${codeUnit.toRadixString(16).padLeft(4, '0')}.",
+ codeUnits, index);
+}
+
« lib/src/percent/encoder.dart ('K') | « lib/src/percent/encoder.dart ('k') | pubspec.yaml » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698