Home | History | Annotate | Download | only in strings
      1 /*
      2  * Copyright (C) 2018 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 "utils/strings/utf8.h"
     18 
     19 namespace libtextclassifier3 {
     20 bool IsValidUTF8(const char *src, int size) {
     21   for (int i = 0; i < size;) {
     22     const int char_length = ValidUTF8CharLength(src + i, size - i);
     23     if (char_length <= 0) {
     24       return false;
     25     }
     26     i += char_length;
     27   }
     28   return true;
     29 }
     30 
     31 int ValidUTF8CharLength(const char *src, int size) {
     32   // Unexpected trail byte.
     33   if (IsTrailByte(src[0])) {
     34     return -1;
     35   }
     36 
     37   const int num_codepoint_bytes = GetNumBytesForUTF8Char(&src[0]);
     38   if (num_codepoint_bytes <= 0 || num_codepoint_bytes > size) {
     39     return -1;
     40   }
     41 
     42   // Check that remaining bytes in the codepoint are trailing bytes.
     43   for (int k = 1; k < num_codepoint_bytes; k++) {
     44     if (!IsTrailByte(src[k])) {
     45       return -1;
     46     }
     47   }
     48 
     49   return num_codepoint_bytes;
     50 }
     51 
     52 }  // namespace libtextclassifier3
     53