utf8.cc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // UTF8 utilities, implemented to reduce dependencies.
  15. #include "absl/strings/internal/utf8.h"
  16. namespace absl {
  17. ABSL_NAMESPACE_BEGIN
  18. namespace strings_internal {
  19. size_t EncodeUTF8Char(char *buffer, char32_t utf8_char) {
  20. if (utf8_char <= 0x7F) {
  21. *buffer = static_cast<char>(utf8_char);
  22. return 1;
  23. } else if (utf8_char <= 0x7FF) {
  24. buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  25. utf8_char >>= 6;
  26. buffer[0] = static_cast<char>(0xC0 | utf8_char);
  27. return 2;
  28. } else if (utf8_char <= 0xFFFF) {
  29. buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  30. utf8_char >>= 6;
  31. buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  32. utf8_char >>= 6;
  33. buffer[0] = static_cast<char>(0xE0 | utf8_char);
  34. return 3;
  35. } else {
  36. buffer[3] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  37. utf8_char >>= 6;
  38. buffer[2] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  39. utf8_char >>= 6;
  40. buffer[1] = static_cast<char>(0x80 | (utf8_char & 0x3F));
  41. utf8_char >>= 6;
  42. buffer[0] = static_cast<char>(0xF0 | utf8_char);
  43. return 4;
  44. }
  45. }
  46. } // namespace strings_internal
  47. ABSL_NAMESPACE_END
  48. } // namespace absl