unilib_utf8_utils.h 2.4 KB

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