Utf8Codex.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #pragma once
  6. #ifdef _WIN32
  7. #include <windows.h>
  8. #include <wtypes.h>
  9. #else
  10. // TODO: Abstract out into it's own file
  11. #include "pal.h"
  12. #include "inc/rt/palrt.h"
  13. #include <stdint.h>
  14. #endif
  15. // Utf8Codex.h needs to be self contained, so these type defs are duplicated from CommonTypeDefs.h
  16. #ifdef _WIN32
  17. typedef WCHAR char16;
  18. #define _u(s) L##s
  19. #else
  20. #define _u(s) u##s
  21. #endif
  22. typedef char16 wchar;
  23. #ifndef Unused
  24. #define Unused(var) var
  25. #endif
  26. #ifndef _WIN32
  27. // Templates are defined here in order to avoid a dependency on C++
  28. // <type_traits> header file,
  29. // or on compiler-specific contructs.
  30. extern "C++" {
  31. template <size_t S>
  32. struct _ENUM_FLAG_INTEGER_FOR_SIZE;
  33. template <>
  34. struct _ENUM_FLAG_INTEGER_FOR_SIZE<1>
  35. {
  36. typedef int8_t type;
  37. };
  38. template <>
  39. struct _ENUM_FLAG_INTEGER_FOR_SIZE<2>
  40. {
  41. typedef int16_t type;
  42. };
  43. template <>
  44. struct _ENUM_FLAG_INTEGER_FOR_SIZE<4>
  45. {
  46. typedef int32_t type;
  47. };
  48. // used as an approximation of std::underlying_type<T>
  49. template <class T>
  50. struct _ENUM_FLAG_SIZED_INTEGER
  51. {
  52. typedef typename _ENUM_FLAG_INTEGER_FOR_SIZE<sizeof(T)>::type
  53. type;
  54. };
  55. }
  56. #define DEFINE_ENUM_FLAG_OPERATORS(ENUMTYPE) \
  57. extern "C++" { \
  58. inline ENUMTYPE operator | (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)a) | ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  59. inline ENUMTYPE &operator |= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type &)a) |= ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  60. inline ENUMTYPE operator & (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)a) & ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  61. inline ENUMTYPE &operator &= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type &)a) &= ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  62. inline ENUMTYPE operator ~ (ENUMTYPE a) { return ENUMTYPE(~((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)a)); } \
  63. inline ENUMTYPE operator ^ (ENUMTYPE a, ENUMTYPE b) { return ENUMTYPE(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)a) ^ ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  64. inline ENUMTYPE &operator ^= (ENUMTYPE &a, ENUMTYPE b) { return (ENUMTYPE &)(((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type &)a) ^= ((_ENUM_FLAG_SIZED_INTEGER<ENUMTYPE>::type)b)); } \
  65. }
  66. #endif
  67. typedef unsigned __int32 uint32;
  68. // charcount_t represents a count of characters in a String
  69. // It is unsigned and the maximum value is (INT_MAX-1)
  70. typedef uint32 charcount_t;
  71. typedef BYTE utf8char_t;
  72. typedef const utf8char_t CUTF8;
  73. typedef utf8char_t* LPUTF8;
  74. typedef const utf8char_t *LPCUTF8;
  75. // Unicode 4.0, unknown char should be converted to replace mark, U+FFFD.
  76. #define UNICODE_UNKNOWN_CHAR_MARK 0xFFFD
  77. #define UNICODE_TCHAR_UKNOWN_CHAR_MARK _T('\xFFFD')
  78. namespace utf8
  79. {
  80. // Terminology -
  81. // Code point - A ordinal value mapped to a standard ideograph as defined by ISO/IEC 10646-1. Here
  82. // also referred to as a UCS code point but can also be often be referred to as a UNICODE
  83. // code point.
  84. // UTF-8 - An encoding of UCS code points as defined by RFC-3629.
  85. // UTF-16 - An encoding of UCS code points as defined by RFC-2781. Use as a synonym for UNICODE or
  86. // UCS-2. This is technically incorrect but usually harmless. This file assumes char16 *
  87. // maps to an UTF-16LE (little-endian) encoded sequence of words.
  88. // Unit - The unit of encoding. For UTF-8 it is a byte (octet). For UTF-16 it is a word (two octets).
  89. // Valid - A UTF-8 byte sequence conforming to RFC-3629.
  90. // Well-formed - A sequence of bytes that conform to the encoding pattern of UTF8 but might be too long or
  91. // otherwise invalid. For example C0 80 is a well-formed but invalid encoding of U+0000.
  92. // Start byte - A byte can start a well-formed UTF-8 sequence.
  93. // Lead byte - A byte can start a well-formed multi-unit sequence but not a single byte sequence.
  94. // Trail byte - A byte that can appear after a lead-byte in a well-formed multi-unit sequence.
  95. // Surrogate pair - A UTF-16 word pair to encode characters outside the Unicode base plain as defined by
  96. // RFC-2781. Two char16 values are used to encode one UCS code point.
  97. // character index - The index into a UTF-16 sequence.
  98. // byte index - The index into a UTF-8 sequence.
  99. // Return the number of bytes needed to encode the given character (ignoring surrogate pairs)
  100. inline size_t EncodedSize(char16 ch)
  101. {
  102. if (ch < 0x0080) return 1;
  103. if (ch < 0x0800) return 2;
  104. return 3;
  105. }
  106. enum DecodeOptions
  107. {
  108. doDefault = 0x00,
  109. doAllowThreeByteSurrogates = 0x01, // Allow invalid 3 byte encodings as would be encoded by CSEU-8
  110. doChunkedEncoding = 0x02, // For sequences at the end of a buffer do not advance into incomplete sequences
  111. // If incomplete UTF-8 sequence is encountered at the end of a buffer, this
  112. // option will cause Decode() to not advance the ptr value and DecodeTail to
  113. // move the pointer back one position so it again points to where c1 was read by
  114. // Decode(). In effect, incomplete sequences are treated as if end pointed to the
  115. // beginning incomplete sequence instead of in the middle of it.
  116. doSecondSurrogatePair = 0x04, // A previous call to DecodeTail returned the first word of a UTF-16
  117. // surrogate pair. The second call will return the second word and reset
  118. // this 'option'.
  119. doAllowInvalidWCHARs = 0x08, // Don't replace invalid wide chars with 0xFFFD
  120. };
  121. DEFINE_ENUM_FLAG_OPERATORS(DecodeOptions);
  122. // Decode the trail bytes after the UTF8 lead byte c1 but returning 0xFFFD if trail bytes are expected after end.
  123. _At_(ptr, _In_reads_(end - ptr) _Post_satisfies_(ptr >= _Old_(ptr) - 1 && ptr <= end))
  124. char16 DecodeTail(char16 c1, LPCUTF8& ptr, LPCUTF8 end, DecodeOptions& options);
  125. // Decode the UTF8 sequence into a UTF16 encoding. Code points outside the Unicode base plain will generate
  126. // surrogate pairs, using the 'doSecondSurrogatePair' option to remember the first word has already been returned.
  127. // If ptr == end 0x0000 is emitted. If ptr < end but the lead byte of the UTF8 sequence
  128. // expects trail bytes past end then 0xFFFD are emitted until ptr == end.
  129. _At_(ptr, _In_reads_(end - ptr) _Post_satisfies_(ptr >= _Old_(ptr) && ptr <= end))
  130. inline char16 Decode(LPCUTF8& ptr, LPCUTF8 end, DecodeOptions& options)
  131. {
  132. if (ptr >= end) return 0;
  133. utf8char_t c1 = *ptr++;
  134. if (c1 < 0x80) return static_cast<char16>(c1);
  135. return DecodeTail(c1, ptr, end, options);
  136. }
  137. // Encode ch into a UTF8 sequence ignoring surrogate pairs (which are encoded as two
  138. // separate code points). Use Encode() instead of EncodeFull() directly because it
  139. // special cases ASCII to avoid a call the most common characters.
  140. LPUTF8 EncodeFull(char16 ch, __out_ecount(3) LPUTF8 ptr);
  141. // Encode a surrogate pair into a utf8 sequence
  142. LPUTF8 EncodeSurrogatePair(char16 surrogateHigh, char16 surrogateLow, __out_ecount(4) LPUTF8 ptr);
  143. // Encode ch into a UTF8 sequence ignoring surrogate pairs (which are encoded as two
  144. // separate code points).
  145. inline LPUTF8 Encode(char16 ch, __out_ecount(3) LPUTF8 ptr)
  146. {
  147. if (ch < 0x80)
  148. {
  149. *ptr = static_cast<utf8char_t>(ch);
  150. return ptr + 1;
  151. }
  152. return EncodeFull(ch, ptr);
  153. }
  154. // Encode ch into a UTF8 sequence while being aware of surrogate pairs.
  155. inline LPUTF8 EncodeTrueUtf8(char16 ch, const char16** source, charcount_t* cch, __out_ecount((*cch + 1) * 3) LPUTF8 ptr)
  156. {
  157. if (ch < 0x80)
  158. {
  159. *ptr = static_cast<utf8char_t>(ch);
  160. return ptr + 1;
  161. }
  162. else if (ch < 0xD800 || (ch >= 0xE000 && ch <= 0xFFFF))
  163. {
  164. return EncodeFull(ch, ptr);
  165. }
  166. // We're now decoding a surrogate pair. If the input is malformed (eg. low surrogate is absent)
  167. // we'll instead encode the unicode replacement character as utf8
  168. if (*cch > 0)
  169. {
  170. char16 surrogateHigh = ch;
  171. char16 surrogateLow = **source;
  172. // Validate that the surrogate code units are within the appropriate
  173. // ranges for high and low surrogates
  174. if ((surrogateHigh >= 0xD800 && surrogateHigh <= 0xDBFF) &&
  175. (surrogateLow >= 0xDC00 && surrogateLow <= 0xDFFF))
  176. {
  177. LPUTF8 retptr = EncodeSurrogatePair(surrogateHigh, surrogateLow, ptr);
  178. // SAL analysis gets confused if we call EncodeSurrogatePair after
  179. // modifying cch
  180. // Consume the low surrogate
  181. *source = *source + 1;
  182. *cch = *cch - 1;
  183. return retptr;
  184. }
  185. }
  186. // Invalid input: insert the unicode replacement character instead
  187. ptr[0] = 0xEF;
  188. ptr[1] = 0xBF;
  189. ptr[2] = 0xBD;
  190. return ptr + 3;
  191. }
  192. // Return true if ch is a lead byte of a UTF8 multi-unit sequence.
  193. inline bool IsLeadByte(utf8char_t ch)
  194. {
  195. return ch >= 0xC0;
  196. }
  197. // Return true if ch is a byte that starts a well-formed UTF8 sequence (i.e. is an ASCII character or a valid UTF8 lead byte)
  198. inline bool IsStartByte(utf8char_t ch)
  199. {
  200. return ch < 0x80 || ch >= 0xC0;
  201. }
  202. // Returns true if ch is a UTF8 multi-unit sequence trail byte.
  203. inline bool IsTrailByte(utf8char_t ch)
  204. {
  205. return (ch & 0xC0) == 0x80;
  206. }
  207. // Returns true if ptr points to a well-formed UTF8
  208. inline bool IsCharStart(LPCUTF8 ptr)
  209. {
  210. return IsStartByte(*ptr);
  211. }
  212. // Return the start of the next well-formed UTF-8 sequence. Use NextChar() instead of
  213. // NextCharFull() since NextChar() avoid a call if ptr references a single byte sequence.
  214. LPCUTF8 NextCharFull(LPCUTF8 ptr);
  215. // Return the start of the next well-formed UTF-8 sequence.
  216. inline LPCUTF8 NextChar(LPCUTF8 ptr)
  217. {
  218. if (*ptr < 0x80) return ptr + 1;
  219. return NextCharFull(ptr);
  220. }
  221. // Return the start of the previous well-formed UTF-8 sequence prior to start or start if
  222. // if ptr is already start or no well-formed sequence starts a start. Use PrevChar() instead of
  223. // PrevCharFull() since PrevChar() avoids a call if the previous sequence is a single byte
  224. // sequence.
  225. LPCUTF8 PrevCharFull(LPCUTF8 ptr, LPCUTF8 start);
  226. // Return the start of the previous well-formed UTF-8 sequence prior to start or start if
  227. // if ptr is already start or no well-formed sequence starts a start.
  228. inline LPCUTF8 PrevChar(LPCUTF8 ptr, LPCUTF8 start)
  229. {
  230. if (ptr > start && *(ptr - 1) < 0x80) return ptr - 1;
  231. return PrevCharFull(ptr, start);
  232. }
  233. // Decode cb bytes from ptr to into buffer returning the number of characters converted and written to buffer
  234. _Ret_range_(0, pbEnd - _Old_(pbUtf8))
  235. size_t DecodeUnitsInto(_Out_writes_(pbEnd - pbUtf8) char16 *buffer, LPCUTF8& pbUtf8, LPCUTF8 pbEnd, DecodeOptions options = doDefault);
  236. // Decode cb bytes from ptr to into buffer returning the number of characters converted and written to buffer (excluding the null terminator)
  237. size_t DecodeUnitsIntoAndNullTerminate(__out_ecount(pbEnd - pbUtf8 + 1) __nullterminated char16 *buffer, LPCUTF8& pbUtf8, LPCUTF8 pbEnd, DecodeOptions options = doDefault);
  238. size_t DecodeUnitsIntoAndNullTerminateNoAdvance(__out_ecount(pbEnd - pbUtf8 + 1) __nullterminated char16 *buffer, LPCUTF8 pbUtf8, LPCUTF8 pbEnd, DecodeOptions options = doDefault);
  239. // Encode a UTF-8 sequence into a UTF-8 sequence (which is just a memcpy). This is included for convenience in templates
  240. // when the character encoding is a template parameter.
  241. __range(cch, cch)
  242. inline size_t EncodeInto(__out_ecount(cch) utf8char_t *buffer, const utf8char_t *source, size_t cch)
  243. {
  244. memcpy_s(buffer, cch * sizeof(utf8char_t), source, cch * sizeof(utf8char_t));
  245. return cch;
  246. }
  247. // Encode a UTF16-LE sequence of cch words into a UTF-8 sequence returning the number of bytes needed.
  248. // Since a UTF16 encoding can take up to 3 bytes buffer must refer to a buffer at least 3 times larger
  249. // than cch.
  250. // Returns the number of bytes copied into the buffer.
  251. __range(0, cch * 3)
  252. size_t EncodeInto(__out_ecount(cch * 3) LPUTF8 buffer, __in_ecount(cch) const char16 *source, charcount_t cch);
  253. // Like EncodeInto but ensures that buffer[return value] == 0.
  254. __range(0, cch * 3)
  255. size_t EncodeIntoAndNullTerminate(__out_ecount(cch * 3 + 1) utf8char_t *buffer, __in_ecount(cch) const char16 *source, charcount_t cch);
  256. // Like EncodeInto but ensures that buffer[return value] == 0.
  257. __range(0, cch * 3)
  258. size_t EncodeTrueUtf8IntoAndNullTerminate(__out_ecount(cch * 3 + 1) utf8char_t *buffer, __in_ecount(cch) const char16 *source, charcount_t cch);
  259. // Returns true if the pch refers to a UTF-16LE encoding of the given UTF-8 encoding bch.
  260. bool CharsAreEqual(LPCOLESTR pch, LPCUTF8 bch, LPCUTF8 end, DecodeOptions options = doDefault);
  261. // Convert the character index into a byte index.
  262. size_t CharacterIndexToByteIndex(__in_ecount(cbLength) LPCUTF8 pch, size_t cbLength, const charcount_t cchIndex, size_t cbStartIndex, charcount_t cchStartIndex, DecodeOptions options = doDefault);
  263. size_t CharacterIndexToByteIndex(__in_ecount(cbLength) LPCUTF8 pch, size_t cbLength, const charcount_t cchIndex, DecodeOptions options = doDefault);
  264. // Convert byte index into character index
  265. charcount_t ByteIndexIntoCharacterIndex(__in_ecount(cbIndex) LPCUTF8 pch, size_t cbIndex, DecodeOptions options = doDefault);
  266. }