This source file includes following definitions.
- IsValidCodePointIndex
- UTF16IndexToOffset
- UTF16OffsetToIndex
#include "ui/gfx/utf16_indexing.h"
#include "base/logging.h"
#include "base/third_party/icu/icu_utf.h"
namespace gfx {
bool IsValidCodePointIndex(const base::string16& s, size_t index) {
return index == 0 || index == s.length() ||
!(CBU16_IS_TRAIL(s[index]) && CBU16_IS_LEAD(s[index - 1]));
}
ptrdiff_t UTF16IndexToOffset(const base::string16& s, size_t base, size_t pos) {
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(const base::string16& s,
size_t base,
ptrdiff_t offset) {
DCHECK_LE(base, s.length());
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;
DCHECK_EQ(offset, 0);
if (!IsValidCodePointIndex(s, pos))
++pos;
return pos;
}
}