summaryrefslogtreecommitdiff
path: root/chromium/ui/base/ime/utf_offset.cc
blob: f6d4bd13d50a6e63a567c8fabe0c1c529927d840 (plain)
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
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/base/ime/utf_offset.h"

#include <string>

#include "base/strings/string16.h"
#include "base/strings/string_piece.h"
#include "base/strings/utf_string_conversions.h"

namespace ui {

base::Optional<size_t> Utf16OffsetFromUtf8Offset(base::StringPiece text,
                                                 size_t utf8_offset) {
  if (utf8_offset > text.length())
    return base::nullopt;

  // TODO(hidehiko): Update not to depend on UTF8ToUTF16 to avoid
  // unnecessary memory allocation.
  base::string16 converted;
  if (!base::UTF8ToUTF16(text.data(), utf8_offset, &converted))
    return base::nullopt;
  return converted.length();
}

base::Optional<size_t> Utf8OffsetFromUtf16Offset(base::StringPiece16 text,
                                                 size_t utf16_offset) {
  if (utf16_offset > text.length())
    return base::nullopt;

  // TODO(hidehiko): Update not to depend on UTF16ToUTF8 to avoid
  // unnecessary memory allocation.
  std::string converted;
  if (!base::UTF16ToUTF8(text.data(), utf16_offset, &converted))
    return base::nullopt;
  return converted.length();
}

}  // namespace ui