1 // Copyright 2011 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/i18n/char_iterator.h"
7 #include "base/check_op.h"
8 #include "base/third_party/icu/icu_utf.h"
13 // UTF8CharIterator ------------------------------------------------------------
15 UTF8CharIterator::UTF8CharIterator(base::StringPiece str)
16 : str_(str), array_pos_(0), next_pos_(0), char_pos_(0), char_(0) {
18 CBU8_NEXT(str_.data(), next_pos_, str_.length(), char_);
21 UTF8CharIterator::~UTF8CharIterator() = default;
23 bool UTF8CharIterator::Advance() {
24 if (array_pos_ >= str_.length())
27 array_pos_ = next_pos_;
29 if (next_pos_ < str_.length())
30 CBU8_NEXT(str_.data(), next_pos_, str_.length(), char_);
35 // UTF16CharIterator -----------------------------------------------------------
37 UTF16CharIterator::UTF16CharIterator(StringPiece16 str)
38 : UTF16CharIterator(str, 0) {}
40 UTF16CharIterator::UTF16CharIterator(UTF16CharIterator&& to_move) = default;
42 UTF16CharIterator::~UTF16CharIterator() = default;
44 UTF16CharIterator& UTF16CharIterator::operator=(UTF16CharIterator&& to_move) =
48 UTF16CharIterator UTF16CharIterator::LowerBound(StringPiece16 str,
50 DCHECK_LE(array_index, str.length());
51 CBU16_SET_CP_START(str.data(), 0, array_index);
52 return UTF16CharIterator(str, array_index);
56 UTF16CharIterator UTF16CharIterator::UpperBound(StringPiece16 str,
58 DCHECK_LE(array_index, str.length());
59 CBU16_SET_CP_LIMIT(str.data(), 0, array_index, str.length());
60 return UTF16CharIterator(str, array_index);
63 int32_t UTF16CharIterator::NextCodePoint() const {
64 if (next_pos_ >= str_.length())
68 CBU16_GET(str_.data(), 0, next_pos_, str_.length(), c);
72 int32_t UTF16CharIterator::PreviousCodePoint() const {
76 uint32_t pos = array_pos_;
78 CBU16_PREV(str_.data(), 0, pos, c);
82 bool UTF16CharIterator::Advance() {
83 if (array_pos_ >= str_.length())
86 array_pos_ = next_pos_;
88 if (next_pos_ < str_.length())
94 bool UTF16CharIterator::Rewind() {
98 next_pos_ = array_pos_;
100 CBU16_PREV(str_.data(), 0, array_pos_, char_);
104 UTF16CharIterator::UTF16CharIterator(StringPiece16 str, size_t initial_pos)
106 array_pos_(initial_pos),
107 next_pos_(initial_pos),
110 // This has the side-effect of advancing |next_pos_|.
111 if (array_pos_ < str_.length())
115 void UTF16CharIterator::ReadChar() {
116 // This is actually a huge macro, so is worth having in a separate function.
117 CBU16_NEXT(str_.data(), next_pos_, str_.length(), char_);