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

Side by Side Diff: utils/string_encoding/utf8_impl.dart

Issue 9462001: Unify most of our utf8 implementations. This takes the implementation (Closed) Base URL: http://dart.googlecode.com/svn/branches/bleeding_edge/dart/
Patch Set: Created 8 years, 9 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 unified diff | Download patch | Annotate | Revision Log
« no previous file with comments | « utils/string_encoding/utf8.dart ('k') | utils/tests/string_encoding/unicode_tests.dart » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file
2 // for details. All rights reserved. Use of this source code is governed by a
3 // BSD-style license that can be found in the LICENSE file.
4
5 final int _UTF8_ONE_BYTE_MAX = 0x7f;
6 final int _UTF8_TWO_BYTE_MAX = 0x7ff;
7 final int _UTF8_THREE_BYTE_MAX = 0xffff;
8
9 final int _UTF8_LO_SIX_BIT_MASK = 0x3f;
10
11 final int _UTF8_FIRST_BYTE_OF_TWO_BASE = 0xc0;
12 final int _UTF8_FIRST_BYTE_OF_THREE_BASE = 0xe0;
13 final int _UTF8_FIRST_BYTE_OF_FOUR_BASE = 0xf0;
14 final int _UTF8_FIRST_BYTE_OF_FIVE_BASE = 0xf8;
15 final int _UTF8_FIRST_BYTE_OF_SIX_BASE = 0xfc;
16
17 final int _UTF8_FIRST_BYTE_OF_TWO_MASK = 0x1f;
18 final int _UTF8_FIRST_BYTE_OF_THREE_MASK = 0xf;
19 final int _UTF8_FIRST_BYTE_OF_FOUR_MASK = 0x7;
20
21 final int _UTF8_FIRST_BYTE_BOUND_EXCL = 0xfe;
22 final int _UTF8_SUBSEQUENT_BYTE_BASE = 0x80;
23
24 /**
25 * Decodes the UTF-8 bytes as an iterable. Thus, the consumer can only convert
26 * as much of the input as needed. Set the replacementCharacter to null to
27 * throw an IllegalArgumentException rather than replace the bad value.
28 */
29 IterableUtf8Decoder decodeUtf8AsIterable(List<int> bytes, [int offset = 0,
30 int length,
31 int replacementCodepoint = UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]) {
32 return new IterableUtf8Decoder(bytes, offset, length, replacementCodepoint);
33 }
34
35 /**
36 * Produce a String from a List of UTF-8 encoded bytes. The parameters
37 * can set an offset into a list of bytes (as int), limit the length of the
38 * values to be decoded, and override the default Unicode replacement character.
39 * Set the replacementCharacter to null to throw an IllegalArgumentException
40 * rather than replace the bad value.
41 */
42 String decodeUtf8(List<int> bytes, [int offset = 0, int length,
43 int replacementCodepoint = UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]) {
44 return codepointsToString(
45 (new Utf8Decoder(bytes, offset, length, replacementCodepoint))
46 .decodeRest());
47 }
48
49 /**
50 * Produce a sequence of UTF-8 encoded bytes from the provided string.
51 */
52 List<int> encodeUtf8(String str) =>
53 _codepointsToUtf8(stringToCodepoints(str));
54
55 int _addToEncoding(int offset, int bytes, int value, List<int> buffer) {
56 while (bytes > 0) {
57 buffer[offset + bytes] = _UTF8_SUBSEQUENT_BYTE_BASE |
58 (value & _UTF8_LO_SIX_BIT_MASK);
59 value = value >> 6;
60 bytes--;
61 }
62 return value;
63 }
64
65 /**
66 * Encode code points as UTF-8 code units.
67 */
68 List<int> _codepointsToUtf8(
69 List<int> codepoints, [int offset = 0, int length]) {
70 ListRange<int> source = new ListRange(codepoints, offset, length);
71
72 int encodedLength = 0;
73 for (int value in source) {
74 if (value < 0 || value > UNICODE_VALID_RANGE_MAX) {
75 encodedLength += 3;
76 } else if (value <= _UTF8_ONE_BYTE_MAX) {
77 encodedLength++;
78 } else if (value <= _UTF8_TWO_BYTE_MAX) {
79 encodedLength += 2;
80 } else if (value <= _UTF8_THREE_BYTE_MAX) {
81 encodedLength += 3;
82 } else if (value <= UNICODE_VALID_RANGE_MAX) {
83 encodedLength += 4;
84 }
85 }
86
87 List<int> encoded = new List<int>(encodedLength);
88 int insertAt = 0;
89 for (int value in source) {
90 if (value < 0 || value > UNICODE_VALID_RANGE_MAX) {
91 encoded.setRange(insertAt, 3, [0xef, 0xbf, 0xbd]);
92 insertAt += 3;
93 } else if (value <= _UTF8_ONE_BYTE_MAX) {
94 encoded[insertAt] = value;
95 insertAt++;
96 } else if (value <= _UTF8_TWO_BYTE_MAX) {
97 encoded[insertAt] = _UTF8_FIRST_BYTE_OF_TWO_BASE | (
98 _UTF8_FIRST_BYTE_OF_TWO_MASK &
99 _addToEncoding(insertAt, 1, value, encoded));
100 insertAt += 2;
101 } else if (value <= _UTF8_THREE_BYTE_MAX) {
102 encoded[insertAt] = _UTF8_FIRST_BYTE_OF_THREE_BASE | (
103 _UTF8_FIRST_BYTE_OF_THREE_MASK &
104 _addToEncoding(insertAt, 2, value, encoded));
105 insertAt += 3;
106 } else if (value <= UNICODE_VALID_RANGE_MAX) {
107 encoded[insertAt] = _UTF8_FIRST_BYTE_OF_FOUR_BASE | (
108 _UTF8_FIRST_BYTE_OF_FOUR_MASK &
109 _addToEncoding(insertAt, 3, value, encoded));
110 insertAt += 4;
111 }
112 }
113 return encoded;
114 }
115
116 // Because UTF-8 specifies byte order, we do not have to follow the pattern
117 // used by UTF-16 & UTF-32 regarding byte order.
118 List<int> _utf8ToCodepoints(
119 List<int> utf8EncodedBytes, [int offset = 0, int length,
120 int replacementCodepoint = UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]) {
121 return new Utf8Decoder(utf8EncodedBytes, offset, length,
122 replacementCodepoint).decodeRest();
123 }
124
125 /**
126 * Return type of [decodeUtf8AsIterable] and variants. The Iterable type
127 * provides an iterator on demand and the iterator will only translate bytes
128 * as requested by the user of the iterator. (Note: results are not cached.)
129 */
130 class IterableUtf8Decoder implements Iterable<int> {
131 final List<int> bytes;
132 final int offset;
133 final int length;
134 final int replacementCodepoint;
135
136 IterableUtf8Decoder(List<int> this.bytes, [int this.offset = 0,
137 int this.length = null,
138 int this.replacementCodepoint = UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]);
139
140 Utf8Decoder iterator() => new Utf8Decoder(bytes, offset, length,
141 replacementCodepoint);
142 }
143
144 /**
145 * Provides an iterator of Unicode codepoints from UTF-8 encoded bytes. The
146 * parameters can set an offset into a list of bytes (as int), limit the length
147 * of the values to be decoded, and override the default Unicode replacement
148 * character. Set the replacementCharacter to null to throw an
149 * IllegalArgumentException rather than replace the bad value. The return value
150 * from this method can be used as an Iterable (e.g. in a for-loop).
151 */
152 class Utf8Decoder implements Iterator<int> {
153 final ListRangeIterator<int> utf8EncodedBytesIterator;
154 final int replacementCodepoint;
155
156 Utf8Decoder(List<int> utf8EncodedBytes, [int offset = 0, int length,
157 int this.replacementCodepoint =
158 UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]) :
159 utf8EncodedBytesIterator = (new ListRange(utf8EncodedBytes, offset,
160 length)).iterator();
161
162
163 Utf8Decoder._fromListRangeIterator(ListRange<int> source, [
164 int this.replacementCodepoint =
165 UNICODE_REPLACEMENT_CHARACTER_CODEPOINT]) :
166 utf8EncodedBytesIterator = source.iterator();
167
168 /** Decode the remaininder of the characters in this decoder
169 * into a [List<int>].
170 */
171 List<int> decodeRest() {
172 List<int> codepoints = new List<int>(utf8EncodedBytesIterator.remaining);
173 int i = 0;
174 while (hasNext()) {
175 codepoints[i++] = next();
176 }
177 if (i == codepoints.length) {
178 return codepoints;
179 } else {
180 List<int> truncCodepoints = new List<int>(i);
181 truncCodepoints.setRange(0, i, codepoints);
182 return truncCodepoints;
183 }
184 }
185
186 bool hasNext() => utf8EncodedBytesIterator.hasNext();
187
188 int next() {
189 int value = utf8EncodedBytesIterator.next();
190 int additionalBytes = 0;
191
192 if (value < 0) {
193 if (replacementCodepoint != null) {
194 return replacementCodepoint;
195 } else {
196 throw new IllegalArgumentException(
197 "Invalid UTF8 at ${utf8EncodedBytesIterator.position}");
198 }
199 } else if (value <= _UTF8_ONE_BYTE_MAX) {
200 return value;
201 } else if (value < _UTF8_FIRST_BYTE_OF_TWO_BASE) {
202 if (replacementCodepoint != null) {
203 return replacementCodepoint;
204 } else {
205 throw new IllegalArgumentException(
206 "Invalid UTF8 at ${utf8EncodedBytesIterator.position}");
207 }
208 } else if (value < _UTF8_FIRST_BYTE_OF_THREE_BASE) {
209 value -= _UTF8_FIRST_BYTE_OF_TWO_BASE;
210 additionalBytes = 1;
211 } else if (value < _UTF8_FIRST_BYTE_OF_FOUR_BASE) {
212 value -= _UTF8_FIRST_BYTE_OF_THREE_BASE;
213 additionalBytes = 2;
214 } else if (value < _UTF8_FIRST_BYTE_OF_FIVE_BASE) {
215 value -= _UTF8_FIRST_BYTE_OF_FOUR_BASE;
216 additionalBytes = 3;
217 } else if (value < _UTF8_FIRST_BYTE_OF_SIX_BASE) {
218 value -= _UTF8_FIRST_BYTE_OF_FIVE_BASE;
219 additionalBytes = 4;
220 } else if (value < _UTF8_FIRST_BYTE_BOUND_EXCL) {
221 value -= _UTF8_FIRST_BYTE_OF_SIX_BASE;
222 additionalBytes = 5;
223 } else if (replacementCodepoint != null) {
224 return replacementCodepoint;
225 } else {
226 throw new IllegalArgumentException(
227 "Invalid UTF8 at ${utf8EncodedBytesIterator.position}");
228 }
229 int j = 0;
230 while (j < additionalBytes && utf8EncodedBytesIterator.hasNext()) {
231 int nextValue = utf8EncodedBytesIterator.next();
232 if (nextValue > _UTF8_ONE_BYTE_MAX &&
233 nextValue < _UTF8_FIRST_BYTE_OF_TWO_BASE) {
234 value = ((value << 6) | (nextValue & _UTF8_LO_SIX_BIT_MASK));
235 } else {
236 // if sequence-starting code unit, reposition cursor to start here
237 if (nextValue >= _UTF8_FIRST_BYTE_OF_TWO_BASE) {
238 utf8EncodedBytesIterator.backup();
239 }
240 break;
241 }
242 j++;
243 }
244 bool validSequence = (j == additionalBytes && (
245 value < UNICODE_UTF16_RESERVED_LO ||
246 value > UNICODE_UTF16_RESERVED_HI));
247 bool nonOverlong =
248 (additionalBytes == 1 && value > _UTF8_ONE_BYTE_MAX) ||
249 (additionalBytes == 2 && value > _UTF8_TWO_BYTE_MAX) ||
250 (additionalBytes == 3 && value > _UTF8_THREE_BYTE_MAX);
251 bool inRange = value <= UNICODE_VALID_RANGE_MAX;
252 if (validSequence && nonOverlong && inRange) {
253 return value;
254 } else if (replacementCodepoint != null) {
255 return replacementCodepoint;
256 } else {
257 throw new IllegalArgumentException(
258 "Invalid UTF8 at ${utf8EncodedBytesIterator.position - j}");
259 }
260 }
261 }
OLDNEW
« no previous file with comments | « utils/string_encoding/utf8.dart ('k') | utils/tests/string_encoding/unicode_tests.dart » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698