Line data Source code
1 : // Copyright 2026 The Authors. See the AUTHORS file for details.
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 : /// A string that only contains decimal (0-9)digits.
18 : ///
19 : /// Does not handle fingers, thumbs or toes.
20 : class DigitString {
21 : final String value;
22 :
23 3 : DigitString._(this.value);
24 :
25 2 : static DigitString? tryParse(String input) {
26 2 : var builder = StringBuffer();
27 :
28 4 : for (var c in input.characters) {
29 2 : var val = int.tryParse(c);
30 : if (val == null) {
31 : return null;
32 : }
33 2 : builder.write(c);
34 : }
35 4 : return DigitString._(builder.toString());
36 : }
37 :
38 : /// Extracts decimal digits from a string.
39 1 : factory DigitString.extract(String input) {
40 1 : var builder = StringBuffer();
41 :
42 2 : for (var c in input.characters) {
43 1 : var val = int.tryParse(c);
44 : if (val != null) {
45 1 : builder.write(c);
46 : }
47 : }
48 2 : return DigitString._(builder.toString());
49 : }
50 :
51 2 : @override
52 2 : String toString() => value;
53 :
54 1 : @override
55 : bool operator ==(Object other) =>
56 1 : (other is String && value == other) ||
57 4 : (other is DigitString && value == other.value);
58 :
59 1 : @override
60 2 : int get hashCode => value.hashCode;
61 :
62 3 : int get length => value.length;
63 :
64 3 : Characters get characters => value.characters;
65 :
66 1 : DigitString substring(int start, [int? end]) {
67 3 : return DigitString._(value.substring(start, end));
68 : }
69 :
70 1 : List<int> get intList =>
71 6 : value.split('').map((e) => int.parse(e)).toList(growable: false);
72 :
73 1 : DigitString valueAt(int index) {
74 3 : return DigitString._(value[index]);
75 : }
76 :
77 2 : int get intValue {
78 4 : return int.parse(value);
79 : }
80 :
81 1 : static DigitString concat(List<DigitString> values) {
82 5 : return DigitString._(values.map((e) => e.value).join(''));
83 : }
84 :
85 2 : static bool isValid(String value) => tryParse(value) != null;
86 :
87 : /*
88 : static bool inRange(DigitString value, DigitString start, DigitString end) {
89 : var v = value.intValue;
90 : return v >= start.intValue && v <= end.intValue;
91 : }
92 : */
93 : }
|