tesseract v5.3.3.20231005
unilib_utf8_utils.h
Go to the documentation of this file.
1
17#ifndef UTIL_UTF8_PUBLIC_UNILIB_UTF8_UTILS_H_
18#define UTIL_UTF8_PUBLIC_UNILIB_UTF8_UTILS_H_
19
20// These definitions are self-contained and have no dependencies.
21// They are also exported from unilib.h for legacy reasons.
22
23#include "syntaxnet/base.h"
24#include "third_party/utf/utf.h"
25
26namespace UniLib {
27
28// Returns true if 'c' is in the range [0, 0xD800) or [0xE000, 0x10FFFF]
29// (i.e., is not a surrogate codepoint). See also
30// IsValidCodepoint(const char* src) in util/utf8/public/unilib.h.
31inline bool IsValidCodepoint(char32 c) {
32 return (static_cast<uint32_t>(c) < 0xD800) || (c >= 0xE000 && c <= 0x10FFFF);
33}
34
35// Returns true if 'str' is the start of a structurally valid UTF-8
36// sequence and is not a surrogate codepoint. Returns false if str.empty()
37// or if str.length() < UniLib::OneCharLen(str[0]). Otherwise, this function
38// will access 1-4 bytes of src, where n is UniLib::OneCharLen(src[0]).
39#ifdef INCLUDE_TENSORFLOW
40inline bool IsUTF8ValidCodepoint(StringPiece str) {
41 char32 c;
42 int consumed;
43 // It's OK if str.length() > consumed.
44 return !str.empty() && isvalidcharntorune(str.data(), str.size(), &c, &consumed) &&
46}
47#endif
48
49// Returns the length (number of bytes) of the Unicode code point
50// starting at src, based on inspecting just that one byte. This
51// requires that src point to a well-formed UTF-8 string; the result
52// is undefined otherwise.
53inline int OneCharLen(const char *src) {
54 return "\1\1\1\1\1\1\1\1\1\1\1\1\2\2\3\4"[(*src & 0xFF) >> 4];
55}
56
57// Returns true if this byte is a trailing UTF-8 byte (10xx xxxx)
58inline bool IsTrailByte(char x) {
59 // return (x & 0xC0) == 0x80;
60 // Since trail bytes are always in [0x80, 0xBF], we can optimize:
61 return static_cast<signed char>(x) < -0x40;
62}
63
64} // namespace UniLib
65
66#endif // UTIL_UTF8_PUBLIC_UNILIB_UTF8_UTILS_H_
signed int char32
int isvalidcharntorune(const char *str, int length, Rune *rune, int *consumed)
Definition: rune.c:239
Definition: unilib.cc:24
bool IsValidCodepoint(char32 c)
bool IsTrailByte(char x)
int OneCharLen(const char *src)