utf8.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /**
  2. * Using strings in Ethereum (or any security-basd system) requires
  3. * additional care. These utilities attempt to mitigate some of the
  4. * safety issues as well as provide the ability to recover and analyse
  5. * strings.
  6. *
  7. * @_subsection api/utils:Strings and UTF-8 [about-strings]
  8. */
  9. import { getBytes } from "./data.js";
  10. import { assertArgument, assertNormalize } from "./errors.js";
  11. function errorFunc(reason, offset, bytes, output, badCodepoint) {
  12. assertArgument(false, `invalid codepoint at offset ${offset}; ${reason}`, "bytes", bytes);
  13. }
  14. function ignoreFunc(reason, offset, bytes, output, badCodepoint) {
  15. // If there is an invalid prefix (including stray continuation), skip any additional continuation bytes
  16. if (reason === "BAD_PREFIX" || reason === "UNEXPECTED_CONTINUE") {
  17. let i = 0;
  18. for (let o = offset + 1; o < bytes.length; o++) {
  19. if (bytes[o] >> 6 !== 0x02) {
  20. break;
  21. }
  22. i++;
  23. }
  24. return i;
  25. }
  26. // This byte runs us past the end of the string, so just jump to the end
  27. // (but the first byte was read already read and therefore skipped)
  28. if (reason === "OVERRUN") {
  29. return bytes.length - offset - 1;
  30. }
  31. // Nothing to skip
  32. return 0;
  33. }
  34. function replaceFunc(reason, offset, bytes, output, badCodepoint) {
  35. // Overlong representations are otherwise "valid" code points; just non-deistingtished
  36. if (reason === "OVERLONG") {
  37. assertArgument(typeof (badCodepoint) === "number", "invalid bad code point for replacement", "badCodepoint", badCodepoint);
  38. output.push(badCodepoint);
  39. return 0;
  40. }
  41. // Put the replacement character into the output
  42. output.push(0xfffd);
  43. // Otherwise, process as if ignoring errors
  44. return ignoreFunc(reason, offset, bytes, output, badCodepoint);
  45. }
  46. /**
  47. * A handful of popular, built-in UTF-8 error handling strategies.
  48. *
  49. * **``"error"``** - throws on ANY illegal UTF-8 sequence or
  50. * non-canonical (overlong) codepoints (this is the default)
  51. *
  52. * **``"ignore"``** - silently drops any illegal UTF-8 sequence
  53. * and accepts non-canonical (overlong) codepoints
  54. *
  55. * **``"replace"``** - replace any illegal UTF-8 sequence with the
  56. * UTF-8 replacement character (i.e. ``"\\ufffd"``) and accepts
  57. * non-canonical (overlong) codepoints
  58. *
  59. * @returns: Record<"error" | "ignore" | "replace", Utf8ErrorFunc>
  60. */
  61. export const Utf8ErrorFuncs = Object.freeze({
  62. error: errorFunc,
  63. ignore: ignoreFunc,
  64. replace: replaceFunc
  65. });
  66. // http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
  67. function getUtf8CodePoints(_bytes, onError) {
  68. if (onError == null) {
  69. onError = Utf8ErrorFuncs.error;
  70. }
  71. const bytes = getBytes(_bytes, "bytes");
  72. const result = [];
  73. let i = 0;
  74. // Invalid bytes are ignored
  75. while (i < bytes.length) {
  76. const c = bytes[i++];
  77. // 0xxx xxxx
  78. if (c >> 7 === 0) {
  79. result.push(c);
  80. continue;
  81. }
  82. // Multibyte; how many bytes left for this character?
  83. let extraLength = null;
  84. let overlongMask = null;
  85. // 110x xxxx 10xx xxxx
  86. if ((c & 0xe0) === 0xc0) {
  87. extraLength = 1;
  88. overlongMask = 0x7f;
  89. // 1110 xxxx 10xx xxxx 10xx xxxx
  90. }
  91. else if ((c & 0xf0) === 0xe0) {
  92. extraLength = 2;
  93. overlongMask = 0x7ff;
  94. // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
  95. }
  96. else if ((c & 0xf8) === 0xf0) {
  97. extraLength = 3;
  98. overlongMask = 0xffff;
  99. }
  100. else {
  101. if ((c & 0xc0) === 0x80) {
  102. i += onError("UNEXPECTED_CONTINUE", i - 1, bytes, result);
  103. }
  104. else {
  105. i += onError("BAD_PREFIX", i - 1, bytes, result);
  106. }
  107. continue;
  108. }
  109. // Do we have enough bytes in our data?
  110. if (i - 1 + extraLength >= bytes.length) {
  111. i += onError("OVERRUN", i - 1, bytes, result);
  112. continue;
  113. }
  114. // Remove the length prefix from the char
  115. let res = c & ((1 << (8 - extraLength - 1)) - 1);
  116. for (let j = 0; j < extraLength; j++) {
  117. let nextChar = bytes[i];
  118. // Invalid continuation byte
  119. if ((nextChar & 0xc0) != 0x80) {
  120. i += onError("MISSING_CONTINUE", i, bytes, result);
  121. res = null;
  122. break;
  123. }
  124. ;
  125. res = (res << 6) | (nextChar & 0x3f);
  126. i++;
  127. }
  128. // See above loop for invalid continuation byte
  129. if (res === null) {
  130. continue;
  131. }
  132. // Maximum code point
  133. if (res > 0x10ffff) {
  134. i += onError("OUT_OF_RANGE", i - 1 - extraLength, bytes, result, res);
  135. continue;
  136. }
  137. // Reserved for UTF-16 surrogate halves
  138. if (res >= 0xd800 && res <= 0xdfff) {
  139. i += onError("UTF16_SURROGATE", i - 1 - extraLength, bytes, result, res);
  140. continue;
  141. }
  142. // Check for overlong sequences (more bytes than needed)
  143. if (res <= overlongMask) {
  144. i += onError("OVERLONG", i - 1 - extraLength, bytes, result, res);
  145. continue;
  146. }
  147. result.push(res);
  148. }
  149. return result;
  150. }
  151. // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
  152. /**
  153. * Returns the UTF-8 byte representation of %%str%%.
  154. *
  155. * If %%form%% is specified, the string is normalized.
  156. */
  157. export function toUtf8Bytes(str, form) {
  158. assertArgument(typeof (str) === "string", "invalid string value", "str", str);
  159. if (form != null) {
  160. assertNormalize(form);
  161. str = str.normalize(form);
  162. }
  163. let result = [];
  164. for (let i = 0; i < str.length; i++) {
  165. const c = str.charCodeAt(i);
  166. if (c < 0x80) {
  167. result.push(c);
  168. }
  169. else if (c < 0x800) {
  170. result.push((c >> 6) | 0xc0);
  171. result.push((c & 0x3f) | 0x80);
  172. }
  173. else if ((c & 0xfc00) == 0xd800) {
  174. i++;
  175. const c2 = str.charCodeAt(i);
  176. assertArgument(i < str.length && ((c2 & 0xfc00) === 0xdc00), "invalid surrogate pair", "str", str);
  177. // Surrogate Pair
  178. const pair = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
  179. result.push((pair >> 18) | 0xf0);
  180. result.push(((pair >> 12) & 0x3f) | 0x80);
  181. result.push(((pair >> 6) & 0x3f) | 0x80);
  182. result.push((pair & 0x3f) | 0x80);
  183. }
  184. else {
  185. result.push((c >> 12) | 0xe0);
  186. result.push(((c >> 6) & 0x3f) | 0x80);
  187. result.push((c & 0x3f) | 0x80);
  188. }
  189. }
  190. return new Uint8Array(result);
  191. }
  192. ;
  193. //export
  194. function _toUtf8String(codePoints) {
  195. return codePoints.map((codePoint) => {
  196. if (codePoint <= 0xffff) {
  197. return String.fromCharCode(codePoint);
  198. }
  199. codePoint -= 0x10000;
  200. return String.fromCharCode((((codePoint >> 10) & 0x3ff) + 0xd800), ((codePoint & 0x3ff) + 0xdc00));
  201. }).join("");
  202. }
  203. /**
  204. * Returns the string represented by the UTF-8 data %%bytes%%.
  205. *
  206. * When %%onError%% function is specified, it is called on UTF-8
  207. * errors allowing recovery using the [[Utf8ErrorFunc]] API.
  208. * (default: [error](Utf8ErrorFuncs))
  209. */
  210. export function toUtf8String(bytes, onError) {
  211. return _toUtf8String(getUtf8CodePoints(bytes, onError));
  212. }
  213. /**
  214. * Returns the UTF-8 code-points for %%str%%.
  215. *
  216. * If %%form%% is specified, the string is normalized.
  217. */
  218. export function toUtf8CodePoints(str, form) {
  219. return getUtf8CodePoints(toUtf8Bytes(str, form));
  220. }
  221. //# sourceMappingURL=utf8.js.map