1 // Copyright (C) 2006 Google Inc.
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 // http://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 // Author: Jim Meehan
16
17 #include <algorithm>
18 #include <sstream>
19 #include <cassert>
20 #include <cstdio>
21
22 #include "phonenumbers/default_logger.h"
23 #include "phonenumbers/utf/unicodetext.h"
24 #include "phonenumbers/utf/stringpiece.h"
25 #include "phonenumbers/utf/utf.h"
26 #include "phonenumbers/utf/unilib.h"
27
28 namespace i18n {
29 namespace phonenumbers {
30
31 using std::string;
32 using std::stringstream;
33 using std::max;
34 using std::hex;
35 using std::dec;
36
CodepointDistance(const char * start,const char * end)37 static int CodepointDistance(const char* start, const char* end) {
38 int n = 0;
39 // Increment n on every non-trail-byte.
40 for (const char* p = start; p < end; ++p) {
41 n += (*reinterpret_cast<const signed char*>(p) >= -0x40);
42 }
43 return n;
44 }
45
CodepointCount(const char * utf8,int len)46 static int CodepointCount(const char* utf8, int len) {
47 return CodepointDistance(utf8, utf8 + len);
48 }
49
50 UnicodeText::const_iterator::difference_type
distance(const UnicodeText::const_iterator & first,const UnicodeText::const_iterator & last)51 distance(const UnicodeText::const_iterator& first,
52 const UnicodeText::const_iterator& last) {
53 return CodepointDistance(first.it_, last.it_);
54 }
55
56 // ---------- Utility ----------
57
ConvertToInterchangeValid(char * start,int len)58 static int ConvertToInterchangeValid(char* start, int len) {
59 // This routine is called only when we've discovered that a UTF-8 buffer
60 // that was passed to CopyUTF8, TakeOwnershipOfUTF8, or PointToUTF8
61 // was not interchange valid. This indicates a bug in the caller, and
62 // a LOG(WARNING) is done in that case.
63 // This is similar to CoerceToInterchangeValid, but it replaces each
64 // structurally valid byte with a space, and each non-interchange
65 // character with a space, even when that character requires more
66 // than one byte in UTF8. E.g., "\xEF\xB7\x90" (U+FDD0) is
67 // structurally valid UTF8, but U+FDD0 is not an interchange-valid
68 // code point. The result should contain one space, not three.
69 //
70 // Since the conversion never needs to write more data than it
71 // reads, it is safe to change the buffer in place. It returns the
72 // number of bytes written.
73 char* const in = start;
74 char* out = start;
75 char* const end = start + len;
76 while (start < end) {
77 int good = UniLib::SpanInterchangeValid(start, static_cast<int>(end - start));
78 if (good > 0) {
79 if (out != start) {
80 memmove(out, start, good);
81 }
82 out += good;
83 start += good;
84 if (start == end) {
85 break;
86 }
87 }
88 // Is the current string invalid UTF8 or just non-interchange UTF8?
89 Rune rune;
90 int n;
91 if (isvalidcharntorune(start, static_cast<int>(end - start), &rune, &n)) {
92 // structurally valid UTF8, but not interchange valid
93 start += n; // Skip over the whole character.
94 } else { // bad UTF8
95 start += 1; // Skip over just one byte
96 }
97 *out++ = ' ';
98 }
99 return static_cast<int>(out - in);
100 }
101
102
103 // *************** Data representation **********
104
105 // Note: the copy constructor is undefined.
106
107 // After reserve(), resize(), or clear(), we're an owner, not an alias.
108
reserve(int new_capacity)109 void UnicodeText::Repr::reserve(int new_capacity) {
110 // If there's already enough capacity, and we're an owner, do nothing.
111 if (capacity_ >= new_capacity && ours_) return;
112
113 // Otherwise, allocate a new buffer.
114 capacity_ = max(new_capacity, (3 * capacity_) / 2 + 20);
115 char* new_data = new char[capacity_];
116
117 // If there is an old buffer, copy it into the new buffer.
118 if (data_) {
119 memcpy(new_data, data_, size_);
120 if (ours_) delete[] data_; // If we owned the old buffer, free it.
121 }
122 data_ = new_data;
123 ours_ = true; // We own the new buffer.
124 // size_ is unchanged.
125 }
126
resize(int new_size)127 void UnicodeText::Repr::resize(int new_size) {
128 if (new_size == 0) {
129 clear();
130 } else {
131 if (!ours_ || new_size > capacity_) reserve(new_size);
132 // Clear the memory in the expanded part.
133 if (size_ < new_size) memset(data_ + size_, 0, new_size - size_);
134 size_ = new_size;
135 ours_ = true;
136 }
137 }
138
139 // This implementation of clear() deallocates the buffer if we're an owner.
140 // That's not strictly necessary; we could just set size_ to 0.
clear()141 void UnicodeText::Repr::clear() {
142 if (ours_) delete[] data_;
143 data_ = NULL;
144 size_ = capacity_ = 0;
145 ours_ = true;
146 }
147
Copy(const char * data,int size)148 void UnicodeText::Repr::Copy(const char* data, int size) {
149 resize(size);
150 memcpy(data_, data, size);
151 }
152
TakeOwnershipOf(char * data,int size,int capacity)153 void UnicodeText::Repr::TakeOwnershipOf(char* data, int size, int capacity) {
154 if (data == data_) return; // We already own this memory. (Weird case.)
155 if (ours_ && data_) delete[] data_; // If we owned the old buffer, free it.
156 data_ = data;
157 size_ = size;
158 capacity_ = capacity;
159 ours_ = true;
160 }
161
PointTo(const char * data,int size)162 void UnicodeText::Repr::PointTo(const char* data, int size) {
163 if (ours_ && data_) delete[] data_; // If we owned the old buffer, free it.
164 data_ = const_cast<char*>(data);
165 size_ = size;
166 capacity_ = size;
167 ours_ = false;
168 }
169
append(const char * bytes,int byte_length)170 void UnicodeText::Repr::append(const char* bytes, int byte_length) {
171 reserve(size_ + byte_length);
172 memcpy(data_ + size_, bytes, byte_length);
173 size_ += byte_length;
174 }
175
DebugString() const176 string UnicodeText::Repr::DebugString() const {
177 stringstream ss;
178
179 ss << "{Repr " << hex << this << " data=" << data_ << " size=" << dec
180 << size_ << " capacity=" << capacity_ << " "
181 << (ours_ ? "Owned" : "Alias") << "}";
182
183 string result;
184 ss >> result;
185
186 return result;
187 }
188
189
190
191 // *************** UnicodeText ******************
192
193 // ----- Constructors -----
194
195 // Default constructor
UnicodeText()196 UnicodeText::UnicodeText() {
197 }
198
199 // Copy constructor
UnicodeText(const UnicodeText & src)200 UnicodeText::UnicodeText(const UnicodeText& src) {
201 Copy(src);
202 }
203
204 // Substring constructor
UnicodeText(const UnicodeText::const_iterator & first,const UnicodeText::const_iterator & last)205 UnicodeText::UnicodeText(const UnicodeText::const_iterator& first,
206 const UnicodeText::const_iterator& last) {
207 assert(first <= last && "Incompatible iterators");
208 repr_.append(first.it_, static_cast<int>(last.it_ - first.it_));
209 }
210
UTF8Substring(const const_iterator & first,const const_iterator & last)211 string UnicodeText::UTF8Substring(const const_iterator& first,
212 const const_iterator& last) {
213 assert(first <= last && "Incompatible iterators");
214 return string(first.it_, last.it_ - first.it_);
215 }
216
217
218 // ----- Copy -----
219
operator =(const UnicodeText & src)220 UnicodeText& UnicodeText::operator=(const UnicodeText& src) {
221 if (this != &src) {
222 Copy(src);
223 }
224 return *this;
225 }
226
Copy(const UnicodeText & src)227 UnicodeText& UnicodeText::Copy(const UnicodeText& src) {
228 repr_.Copy(src.repr_.data_, src.repr_.size_);
229 return *this;
230 }
231
CopyUTF8(const char * buffer,int byte_length)232 UnicodeText& UnicodeText::CopyUTF8(const char* buffer, int byte_length) {
233 repr_.Copy(buffer, byte_length);
234 repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
235 if (!repr_.utf8_was_valid_) {
236 LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
237 repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
238 }
239 return *this;
240 }
241
UnsafeCopyUTF8(const char * buffer,int byte_length)242 UnicodeText& UnicodeText::UnsafeCopyUTF8(const char* buffer,
243 int byte_length) {
244 repr_.Copy(buffer, byte_length);
245 return *this;
246 }
247
248 // ----- TakeOwnershipOf -----
249
TakeOwnershipOfUTF8(char * buffer,int byte_length,int byte_capacity)250 UnicodeText& UnicodeText::TakeOwnershipOfUTF8(char* buffer,
251 int byte_length,
252 int byte_capacity) {
253 repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
254 repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
255 if (!repr_.utf8_was_valid_) {
256 LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
257 repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
258 }
259 return *this;
260 }
261
UnsafeTakeOwnershipOfUTF8(char * buffer,int byte_length,int byte_capacity)262 UnicodeText& UnicodeText::UnsafeTakeOwnershipOfUTF8(char* buffer,
263 int byte_length,
264 int byte_capacity) {
265 repr_.TakeOwnershipOf(buffer, byte_length, byte_capacity);
266 return *this;
267 }
268
269 // ----- PointTo -----
270
PointToUTF8(const char * buffer,int byte_length)271 UnicodeText& UnicodeText::PointToUTF8(const char* buffer, int byte_length) {
272 repr_.utf8_was_valid_ = UniLib:: IsInterchangeValid(buffer, byte_length);
273 if (repr_.utf8_was_valid_) {
274 repr_.PointTo(buffer, byte_length);
275 } else {
276 LOG(WARNING) << "UTF-8 buffer is not interchange-valid.";
277 repr_.Copy(buffer, byte_length);
278 repr_.size_ = ConvertToInterchangeValid(repr_.data_, byte_length);
279 }
280 return *this;
281 }
282
UnsafePointToUTF8(const char * buffer,int byte_length)283 UnicodeText& UnicodeText::UnsafePointToUTF8(const char* buffer,
284 int byte_length) {
285 repr_.PointTo(buffer, byte_length);
286 return *this;
287 }
288
PointTo(const UnicodeText & src)289 UnicodeText& UnicodeText::PointTo(const UnicodeText& src) {
290 repr_.PointTo(src.repr_.data_, src.repr_.size_);
291 return *this;
292 }
293
PointTo(const const_iterator & first,const const_iterator & last)294 UnicodeText& UnicodeText::PointTo(const const_iterator &first,
295 const const_iterator &last) {
296 assert(first <= last && " Incompatible iterators");
297 repr_.PointTo(first.utf8_data(), static_cast<int>(last.utf8_data() - first.utf8_data()));
298 return *this;
299 }
300
301 // ----- Append -----
302
append(const UnicodeText & u)303 UnicodeText& UnicodeText::append(const UnicodeText& u) {
304 repr_.append(u.repr_.data_, u.repr_.size_);
305 return *this;
306 }
307
append(const const_iterator & first,const const_iterator & last)308 UnicodeText& UnicodeText::append(const const_iterator& first,
309 const const_iterator& last) {
310 assert(first <= last && "Incompatible iterators");
311 repr_.append(first.it_, static_cast<int>(last.it_ - first.it_));
312 return *this;
313 }
314
UnsafeAppendUTF8(const char * utf8,int len)315 UnicodeText& UnicodeText::UnsafeAppendUTF8(const char* utf8, int len) {
316 repr_.append(utf8, len);
317 return *this;
318 }
319
320 // ----- substring searching -----
321
find(const UnicodeText & look,const_iterator start_pos) const322 UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look,
323 const_iterator start_pos) const {
324 assert(start_pos.utf8_data() >= utf8_data());
325 assert(start_pos.utf8_data() <= utf8_data() + utf8_length());
326 return UnsafeFind(look, start_pos);
327 }
328
find(const UnicodeText & look) const329 UnicodeText::const_iterator UnicodeText::find(const UnicodeText& look) const {
330 return UnsafeFind(look, begin());
331 }
332
UnsafeFind(const UnicodeText & look,const_iterator start_pos) const333 UnicodeText::const_iterator UnicodeText::UnsafeFind(
334 const UnicodeText& look, const_iterator start_pos) const {
335 // Due to the magic of the UTF8 encoding, searching for a sequence of
336 // letters is equivalent to substring search.
337 StringPiece searching(utf8_data(), utf8_length());
338 StringPiece look_piece(look.utf8_data(), look.utf8_length());
339 StringPiece::size_type found =
340 searching.find(look_piece, start_pos.utf8_data() - utf8_data());
341 if (found == StringPiece::npos) return end();
342 return const_iterator(utf8_data() + found);
343 }
344
HasReplacementChar() const345 bool UnicodeText::HasReplacementChar() const {
346 // Equivalent to:
347 // UnicodeText replacement_char;
348 // replacement_char.push_back(0xFFFD);
349 // return find(replacement_char) != end();
350 StringPiece searching(utf8_data(), utf8_length());
351 StringPiece looking_for("\xEF\xBF\xBD", 3);
352 return searching.find(looking_for) != StringPiece::npos;
353 }
354
355 // ----- other methods -----
356
357 // Clear operator
clear()358 void UnicodeText::clear() {
359 repr_.clear();
360 }
361
362 // Destructor
~UnicodeText()363 UnicodeText::~UnicodeText() {}
364
365
push_back(char32 c)366 void UnicodeText::push_back(char32 c) {
367 if (UniLib::IsValidCodepoint(c)) {
368 char buf[UTFmax];
369 Rune rune = c;
370 int len = runetochar(buf, &rune);
371 if (UniLib::IsInterchangeValid(buf, len)) {
372 repr_.append(buf, len);
373 } else {
374 fprintf(stderr, "Unicode value 0x%x is not valid for interchange\n", c);
375 repr_.append(" ", 1);
376 }
377 } else {
378 fprintf(stderr, "Illegal Unicode value: 0x%x\n", c);
379 repr_.append(" ", 1);
380 }
381 }
382
size() const383 int UnicodeText::size() const {
384 return CodepointCount(repr_.data_, repr_.size_);
385 }
386
operator ==(const UnicodeText & lhs,const UnicodeText & rhs)387 bool operator==(const UnicodeText& lhs, const UnicodeText& rhs) {
388 if (&lhs == &rhs) return true;
389 if (lhs.repr_.size_ != rhs.repr_.size_) return false;
390 return memcmp(lhs.repr_.data_, rhs.repr_.data_, lhs.repr_.size_) == 0;
391 }
392
DebugString() const393 string UnicodeText::DebugString() const {
394 stringstream ss;
395
396 ss << "{UnicodeText " << hex << this << dec << " chars="
397 << size() << " repr=" << repr_.DebugString() << "}";
398 #if 0
399 return StringPrintf("{UnicodeText %p chars=%d repr=%s}",
400 this,
401 size(),
402 repr_.DebugString().c_str());
403 #endif
404 string result;
405 ss >> result;
406
407 return result;
408 }
409
410
411 // ******************* UnicodeText::const_iterator *********************
412
413 // The implementation of const_iterator would be nicer if it
414 // inherited from boost::iterator_facade
415 // (http://boost.org/libs/iterator/doc/iterator_facade.html).
416
const_iterator()417 UnicodeText::const_iterator::const_iterator() : it_(0) {}
418
const_iterator(const const_iterator & other)419 UnicodeText::const_iterator::const_iterator(const const_iterator& other)
420 : it_(other.it_) {
421 }
422
423 UnicodeText::const_iterator&
operator =(const const_iterator & other)424 UnicodeText::const_iterator::operator=(const const_iterator& other) {
425 if (&other != this)
426 it_ = other.it_;
427 return *this;
428 }
429
begin() const430 UnicodeText::const_iterator UnicodeText::begin() const {
431 return const_iterator(repr_.data_);
432 }
433
end() const434 UnicodeText::const_iterator UnicodeText::end() const {
435 return const_iterator(repr_.data_ + repr_.size_);
436 }
437
operator <(const UnicodeText::const_iterator & lhs,const UnicodeText::const_iterator & rhs)438 bool operator<(const UnicodeText::const_iterator& lhs,
439 const UnicodeText::const_iterator& rhs) {
440 return lhs.it_ < rhs.it_;
441 }
442
operator *() const443 char32 UnicodeText::const_iterator::operator*() const {
444 // (We could call chartorune here, but that does some
445 // error-checking, and we're guaranteed that our data is valid
446 // UTF-8. Also, we expect this routine to be called very often. So
447 // for speed, we do the calculation ourselves.)
448
449 // Convert from UTF-8
450 uint8 byte1 = static_cast<uint8>(it_[0]);
451 if (byte1 < 0x80)
452 return byte1;
453
454 uint8 byte2 = static_cast<uint8>(it_[1]);
455 if (byte1 < 0xE0)
456 return ((byte1 & 0x1F) << 6)
457 | (byte2 & 0x3F);
458
459 uint8 byte3 = static_cast<uint8>(it_[2]);
460 if (byte1 < 0xF0)
461 return ((byte1 & 0x0F) << 12)
462 | ((byte2 & 0x3F) << 6)
463 | (byte3 & 0x3F);
464
465 uint8 byte4 = static_cast<uint8>(it_[3]);
466 return ((byte1 & 0x07) << 18)
467 | ((byte2 & 0x3F) << 12)
468 | ((byte3 & 0x3F) << 6)
469 | (byte4 & 0x3F);
470 }
471
operator ++()472 UnicodeText::const_iterator& UnicodeText::const_iterator::operator++() {
473 it_ += UniLib::OneCharLen(it_);
474 return *this;
475 }
476
operator --()477 UnicodeText::const_iterator& UnicodeText::const_iterator::operator--() {
478 while (UniLib::IsTrailByte(*--it_)) { }
479 return *this;
480 }
481
get_utf8(char * utf8_output) const482 int UnicodeText::const_iterator::get_utf8(char* utf8_output) const {
483 utf8_output[0] = it_[0];
484 if (static_cast<unsigned char>(it_[0]) < 0x80)
485 return 1;
486
487 utf8_output[1] = it_[1];
488 if (static_cast<unsigned char>(it_[0]) < 0xE0)
489 return 2;
490
491 utf8_output[2] = it_[2];
492 if (static_cast<unsigned char>(it_[0]) < 0xF0)
493 return 3;
494
495 utf8_output[3] = it_[3];
496 return 4;
497 }
498
499
MakeIterator(const char * p) const500 UnicodeText::const_iterator UnicodeText::MakeIterator(const char* p) const {
501 #ifndef NDEBUG
502 assert(p != NULL);
503 const char* start = utf8_data();
504 int len = utf8_length();
505 const char* end = start + len;
506 assert(p >= start);
507 assert(p <= end);
508 assert(p == end || !UniLib::IsTrailByte(*p));
509 #endif
510 return const_iterator(p);
511 }
512
DebugString() const513 string UnicodeText::const_iterator::DebugString() const {
514 stringstream ss;
515
516 ss << "{iter " << hex << it_ << "}";
517 string result;
518 ss >> result;
519
520 return result;
521 }
522
523 } // namespace phonenumbers
524 } // namespace i18n
525