utf16_indexing.h 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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.
  4. #ifndef UI_GFX_UTF16_INDEXING_H_
  5. #define UI_GFX_UTF16_INDEXING_H_
  6. #include <stddef.h>
  7. #include <string>
  8. #include "ui/gfx/gfx_export.h"
  9. namespace gfx {
  10. // Returns false if s[index-1] is a high surrogate and s[index] is a low
  11. // surrogate, true otherwise.
  12. GFX_EXPORT bool IsValidCodePointIndex(const std::u16string& s, size_t index);
  13. // |UTF16IndexToOffset| returns the number of code points between |base| and
  14. // |pos| in the given string. |UTF16OffsetToIndex| returns the index that is
  15. // |offset| code points away from the given |base| index. These functions are
  16. // named after glib's |g_utf8_pointer_to_offset| and |g_utf8_offset_to_pointer|,
  17. // which perform the same function for UTF-8. As in glib, it is an error to
  18. // pass an |offset| that walks off the edge of the string.
  19. //
  20. // These functions attempt to deal with invalid use of UTF-16 surrogates in a
  21. // way that makes as much sense as possible: unpaired surrogates are treated as
  22. // single characters, and if an argument index points to the middle of a valid
  23. // surrogate pair, it is treated as though it pointed to the end of that pair.
  24. // The index returned by |UTF16OffsetToIndex| never points to the middle of a
  25. // surrogate pair.
  26. //
  27. // The following identities hold:
  28. // If |s| contains no surrogate pairs, then
  29. // UTF16IndexToOffset(s, base, pos) == pos - base
  30. // UTF16OffsetToIndex(s, base, offset) == base + offset
  31. // If |pos| does not point to the middle of a surrogate pair, then
  32. // UTF16OffsetToIndex(s, base, UTF16IndexToOffset(s, base, pos)) == pos
  33. // Always,
  34. // UTF16IndexToOffset(s, base, UTF16OffsetToIndex(s, base, ofs)) == ofs
  35. // UTF16IndexToOffset(s, i, j) == -UTF16IndexToOffset(s, j, i)
  36. GFX_EXPORT ptrdiff_t UTF16IndexToOffset(const std::u16string& s,
  37. size_t base,
  38. size_t pos);
  39. GFX_EXPORT size_t UTF16OffsetToIndex(const std::u16string& s,
  40. size_t base,
  41. ptrdiff_t offset);
  42. } // namespace gfx
  43. #endif // UI_GFX_UTF16_INDEXING_H_