utf8.h 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. Basic UTF-8 manipulation routines
  3. by Jeff Bezanson
  4. placed in the public domain Fall 2005
  5. This code is designed to provide the utilities you need to manipulate
  6. UTF-8 as an internal string encoding. These functions do not perform the
  7. error checking normally needed when handling UTF-8 data, so if you happen
  8. to be from the Unicode Consortium you will want to flay me alive.
  9. I do this because error checking can be performed at the boundaries (I/O),
  10. with these routines reserved for higher performance on data known to be
  11. valid.
  12. */
  13. // Further modified, and C++ stuff added, by hrydgard@gmail.com.
  14. #pragma once
  15. #include "common/common_types.h"
  16. #include <string>
  17. u32 u8_nextchar(const char *s, int *i);
  18. int u8_wc_toutf8(char *dest, u32 ch);
  19. int u8_strlen(const char *s);
  20. class UTF8 {
  21. public:
  22. static const u32 INVALID = (u32)-1;
  23. UTF8(const char *c) : c_(c), index_(0) {}
  24. bool end() const { return c_[index_] == 0; }
  25. u32 next() {
  26. return u8_nextchar(c_, &index_);
  27. }
  28. u32 peek() {
  29. int tempIndex = index_;
  30. return u8_nextchar(c_, &tempIndex);
  31. }
  32. int length() const {
  33. return u8_strlen(c_);
  34. }
  35. int byteIndex() const {
  36. return index_;
  37. }
  38. static int encode(char *dest, u32 ch) {
  39. return u8_wc_toutf8(dest, ch);
  40. }
  41. private:
  42. const char *c_;
  43. int index_;
  44. };
  45. int UTF8StringNonASCIICount(const char *utf8string);
  46. bool UTF8StringHasNonASCII(const char *utf8string);
  47. // UTF8 to Win32 UTF-16
  48. // Should be used when calling Win32 api calls
  49. #ifdef _WIN32
  50. std::string ConvertWStringToUTF8(const std::wstring &wstr);
  51. std::string ConvertWStringToUTF8(const wchar_t *wstr);
  52. void ConvertUTF8ToWString(wchar_t *dest, size_t destSize, const std::string &source);
  53. std::wstring ConvertUTF8ToWString(const std::string &source);
  54. #endif