tesseract  5.0.0-alpha-619-ge9db
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 
26 namespace 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.
31 inline bool IsValidCodepoint(char32 c) {
32  return (static_cast<uint32>(c) < 0xD800)
33  || (c >= 0xE000 && c <= 0x10FFFF);
34 }
35 
36 // Returns true if 'str' is the start of a structurally valid UTF-8
37 // sequence and is not a surrogate codepoint. Returns false if str.empty()
38 // or if str.length() < UniLib::OneCharLen(str[0]). Otherwise, this function
39 // will access 1-4 bytes of src, where n is UniLib::OneCharLen(src[0]).
40 inline bool IsUTF8ValidCodepoint(StringPiece str) {
41  char32 c;
42  int consumed;
43  // It's OK if str.length() > consumed.
44  return !str.empty()
45  && isvalidcharntorune(str.data(), str.size(), &c, &consumed)
46  && IsValidCodepoint(c);
47 }
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.
53 inline 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)
58 inline 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_
base.h
UniLib::IsTrailByte
bool IsTrailByte(char x)
Definition: unilib_utf8_utils.h:58
UniLib::IsValidCodepoint
bool IsValidCodepoint(char32 c)
Definition: unilib_utf8_utils.h:31
char32
signed int char32
Definition: pango_font_info.h:33
UniLib
Definition: unilib.cc:24
isvalidcharntorune
int isvalidcharntorune(const char *str, int length, Rune *rune, int *consumed)
Definition: rune.c:247
utf.h
UniLib::OneCharLen
int OneCharLen(const char *src)
Definition: unilib_utf8_utils.h:53
UniLib::IsUTF8ValidCodepoint
bool IsUTF8ValidCodepoint(StringPiece str)
Definition: unilib_utf8_utils.h:40