unilib_utf8_utils.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. namespace UniLib {
  22. // Returns true if 'c' is in the range [0, 0xD800) or [0xE000, 0x10FFFF]
  23. // (i.e., is not a surrogate codepoint). See also
  24. // IsValidCodepoint(const char* src) in util/utf8/public/unilib.h.
  25. inline bool IsValidCodepoint(char32 c) {
  26. return (static_cast<uint32>(c) < 0xD800)
  27. || (c >= 0xE000 && c <= 0x10FFFF);
  28. }
  29. // Returns the length (number of bytes) of the Unicode code point
  30. // starting at src, based on inspecting just that one byte. This
  31. // requires that src point to a well-formed UTF-8 string; the result
  32. // is undefined otherwise.
  33. inline int OneCharLen(const char* src) {
  34. return "\1\1\1\1\1\1\1\1\1\1\1\1\2\2\3\4"[(*src & 0xFF) >> 4];
  35. }
  36. // Returns true if this byte is a trailing UTF-8 byte (10xx xxxx)
  37. inline bool IsTrailByte(char x) {
  38. // return (x & 0xC0) == 0x80;
  39. // Since trail bytes are always in [0x80, 0xBF], we can optimize:
  40. return static_cast<signed char>(x) < -0x40;
  41. }
  42. } // namespace UniLib
  43. #endif // UTIL_UTF8_PUBLIC_UNILIB_UTF8_UTILS_H_