File: utf16_indexing.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (59 lines) | stat: -rw-r--r-- 2,216 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/utf16_indexing.h"

#include <string_view>

#include "base/check_op.h"
#include "base/third_party/icu/icu_utf.h"

namespace gfx {

bool IsValidCodePointIndex(std::u16string_view s, size_t index) {
  return index == 0 || index == s.length() ||
    !(CBU16_IS_TRAIL(s[index]) && CBU16_IS_LEAD(s[index - 1]));
}

ptrdiff_t UTF16IndexToOffset(std::u16string_view s, size_t base, size_t pos) {
  // The indices point between UTF-16 words (range 0 to s.length() inclusive).
  // In order to consistently handle indices that point to the middle of a
  // surrogate pair, we count the first word in that surrogate pair and not
  // the second. The test "s[i] is not the second half of a surrogate pair" is
  // "IsValidCodePointIndex(s, i)".
  DCHECK_LE(base, s.length());
  DCHECK_LE(pos, s.length());
  ptrdiff_t delta = 0;
  while (base < pos)
    delta += IsValidCodePointIndex(s, base++) ? 1 : 0;
  while (pos < base)
    delta -= IsValidCodePointIndex(s, pos++) ? 1 : 0;
  return delta;
}

size_t UTF16OffsetToIndex(std::u16string_view s,
                          size_t base,
                          ptrdiff_t offset) {
  DCHECK_LE(base, s.length());
  // As in UTF16IndexToOffset, we count the first half of a surrogate pair, not
  // the second. When stepping from pos to pos+1 we check s[pos:pos+1] == s[pos]
  // (Python syntax), hence pos++. When stepping from pos to pos-1 we check
  // s[pos-1], hence --pos.
  size_t pos = base;
  while (offset > 0 && pos < s.length())
    offset -= IsValidCodePointIndex(s, pos++) ? 1 : 0;
  while (offset < 0 && pos > 0)
    offset += IsValidCodePointIndex(s, --pos) ? 1 : 0;
  // If offset != 0 then we ran off the edge of the string, which is a contract
  // violation but is handled anyway (by clamping) in release for safety.
  DCHECK_EQ(offset, 0);
  // Since the second half of a surrogate pair has "length" zero, there is an
  // ambiguity in the returned position. Resolve it by always returning a valid
  // index.
  if (!IsValidCodePointIndex(s, pos))
    ++pos;
  return pos;
}

}  // namespace gfx