Line data Source code
1 : // Copyright 2026 The Authors
2 : //
3 : // Licensed under the Apache License, Version 2.0 (the "License");
4 : // you may not use this file except in compliance with the License.
5 : // You may obtain a copy of the License at
6 : //
7 : // https://www.apache.org/licenses/LICENSE-2.0
8 : //
9 : // Unless required by applicable law or agreed to in writing, software
10 : // distributed under the License is distributed on an "AS IS" BASIS,
11 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 : // See the License for the specific language governing permissions and
13 : // limitations under the License.
14 :
15 : import 'package:characters/characters.dart';
16 :
17 : /// Handle a string made up of hexidecimal characters (not witchcraft)
18 : class HexString {
19 : static const hexValues = {
20 : '0',
21 : '1',
22 : '2',
23 : '3',
24 : '4',
25 : '5',
26 : '6',
27 : '7',
28 : '8',
29 : '9',
30 : 'a',
31 : 'b',
32 : 'c',
33 : 'd',
34 : 'e',
35 : 'f',
36 : 'A',
37 : 'B',
38 : 'C',
39 : 'D',
40 : 'E',
41 : 'F',
42 : };
43 :
44 : final String value;
45 :
46 1 : HexString._(this.value);
47 :
48 1 : static HexString? tryParse(String input) {
49 : String test;
50 1 : if (input.startsWith('0x')) {
51 1 : test = input.substring(2);
52 : } else {
53 : test = input;
54 : }
55 2 : for (var c in test.characters) {
56 1 : if (!hexValues.contains(c)) {
57 : return null;
58 : }
59 : }
60 1 : return HexString._(input);
61 : }
62 :
63 2 : static bool isValid(String value) => tryParse(value) != null;
64 :
65 1 : static int unHex(int c) {
66 4 : if ('0'.codeUnitAt(0) <= c && c <= '9'.codeUnitAt(0)) {
67 2 : return c - '0'.codeUnitAt(0);
68 : }
69 4 : if ('a'.codeUnitAt(0) <= c && c <= 'f'.codeUnitAt(0)) {
70 3 : return c - 'a'.codeUnitAt(0) + 10;
71 : }
72 4 : if ('A'.codeUnitAt(0) <= c && c <= 'F'.codeUnitAt(0)) {
73 3 : return c - 'A'.codeUnitAt(0) + 10;
74 : }
75 : return 0;
76 : }
77 : }
|