1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "ui/gfx/utf16_indexing.h"
7 #include "base/logging.h"
8 #include "base/third_party/icu/icu_utf.h"
12 bool IsValidCodePointIndex(const base::string16
& s
, size_t index
) {
13 return index
== 0 || index
== s
.length() ||
14 !(CBU16_IS_TRAIL(s
[index
]) && CBU16_IS_LEAD(s
[index
- 1]));
17 ptrdiff_t UTF16IndexToOffset(const base::string16
& s
, size_t base
, size_t pos
) {
18 // The indices point between UTF-16 words (range 0 to s.length() inclusive).
19 // In order to consistently handle indices that point to the middle of a
20 // surrogate pair, we count the first word in that surrogate pair and not
21 // the second. The test "s[i] is not the second half of a surrogate pair" is
22 // "IsValidCodePointIndex(s, i)".
23 DCHECK_LE(base
, s
.length());
24 DCHECK_LE(pos
, s
.length());
27 delta
+= IsValidCodePointIndex(s
, base
++) ? 1 : 0;
29 delta
-= IsValidCodePointIndex(s
, pos
++) ? 1 : 0;
33 size_t UTF16OffsetToIndex(const base::string16
& s
,
36 DCHECK_LE(base
, s
.length());
37 // As in UTF16IndexToOffset, we count the first half of a surrogate pair, not
38 // the second. When stepping from pos to pos+1 we check s[pos:pos+1] == s[pos]
39 // (Python syntax), hence pos++. When stepping from pos to pos-1 we check
40 // s[pos-1], hence --pos.
42 while (offset
> 0 && pos
< s
.length())
43 offset
-= IsValidCodePointIndex(s
, pos
++) ? 1 : 0;
44 while (offset
< 0 && pos
> 0)
45 offset
+= IsValidCodePointIndex(s
, --pos
) ? 1 : 0;
46 // If offset != 0 then we ran off the edge of the string, which is a contract
47 // violation but is handled anyway (by clamping) in release for safety.
49 // Since the second half of a surrogate pair has "length" zero, there is an
50 // ambiguity in the returned position. Resolve it by always returning a valid
52 if (!IsValidCodePointIndex(s
, pos
))