1/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "util/strings/utf8.h"
18
19namespace libtextclassifier2 {
20bool IsValidUTF8(const char *src, int size) {
21  for (int i = 0; i < size;) {
22    // Unexpected trail byte.
23    if (IsTrailByte(src[i])) {
24      return false;
25    }
26
27    const int num_codepoint_bytes = GetNumBytesForUTF8Char(&src[i]);
28    if (num_codepoint_bytes <= 0 || i + num_codepoint_bytes > size) {
29      return false;
30    }
31
32    // Check that remaining bytes in the codepoint are trailing bytes.
33    i++;
34    for (int k = 1; k < num_codepoint_bytes; k++, i++) {
35      if (!IsTrailByte(src[i])) {
36        return false;
37      }
38    }
39  }
40  return true;
41}
42}  // namespace libtextclassifier2
43