UnicodeUtils.js.flow 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule UnicodeUtils
  8. * @typechecks
  9. */
  10. /**
  11. * Unicode-enabled replacesments for basic String functions.
  12. *
  13. * All the functions in this module assume that the input string is a valid
  14. * UTF-16 encoding of a Unicode sequence. If it's not the case, the behavior
  15. * will be undefined.
  16. *
  17. * WARNING: Since this module is typechecks-enforced, you may find new bugs
  18. * when replacing normal String functions with ones provided here.
  19. */
  20. 'use strict';
  21. const invariant = require('./invariant');
  22. // These two ranges are consecutive so anything in [HIGH_START, LOW_END] is a
  23. // surrogate code unit.
  24. const SURROGATE_HIGH_START = 0xD800;
  25. const SURROGATE_HIGH_END = 0xDBFF;
  26. const SURROGATE_LOW_START = 0xDC00;
  27. const SURROGATE_LOW_END = 0xDFFF;
  28. const SURROGATE_UNITS_REGEX = /[\uD800-\uDFFF]/;
  29. /**
  30. * @param {number} codeUnit A Unicode code-unit, in range [0, 0x10FFFF]
  31. * @return {boolean} Whether code-unit is in a surrogate (hi/low) range
  32. */
  33. function isCodeUnitInSurrogateRange(codeUnit) {
  34. return SURROGATE_HIGH_START <= codeUnit && codeUnit <= SURROGATE_LOW_END;
  35. }
  36. /**
  37. * Returns whether the two characters starting at `index` form a surrogate pair.
  38. * For example, given the string s = "\uD83D\uDE0A", (s, 0) returns true and
  39. * (s, 1) returns false.
  40. *
  41. * @param {string} str
  42. * @param {number} index
  43. * @return {boolean}
  44. */
  45. function isSurrogatePair(str, index) {
  46. invariant(0 <= index && index < str.length, 'isSurrogatePair: Invalid index %s for string length %s.', index, str.length);
  47. if (index + 1 === str.length) {
  48. return false;
  49. }
  50. const first = str.charCodeAt(index);
  51. const second = str.charCodeAt(index + 1);
  52. return SURROGATE_HIGH_START <= first && first <= SURROGATE_HIGH_END && SURROGATE_LOW_START <= second && second <= SURROGATE_LOW_END;
  53. }
  54. /**
  55. * @param {string} str Non-empty string
  56. * @return {boolean} True if the input includes any surrogate code units
  57. */
  58. function hasSurrogateUnit(str) {
  59. return SURROGATE_UNITS_REGEX.test(str);
  60. }
  61. /**
  62. * Return the length of the original Unicode character at given position in the
  63. * String by looking into the UTF-16 code unit; that is equal to 1 for any
  64. * non-surrogate characters in BMP ([U+0000..U+D7FF] and [U+E000, U+FFFF]); and
  65. * returns 2 for the hi/low surrogates ([U+D800..U+DFFF]), which are in fact
  66. * representing non-BMP characters ([U+10000..U+10FFFF]).
  67. *
  68. * Examples:
  69. * - '\u0020' => 1
  70. * - '\u3020' => 1
  71. * - '\uD835' => 2
  72. * - '\uD835\uDDEF' => 2
  73. * - '\uDDEF' => 2
  74. *
  75. * @param {string} str Non-empty string
  76. * @param {number} pos Position in the string to look for one code unit
  77. * @return {number} Number 1 or 2
  78. */
  79. function getUTF16Length(str, pos) {
  80. return 1 + isCodeUnitInSurrogateRange(str.charCodeAt(pos));
  81. }
  82. /**
  83. * Fully Unicode-enabled replacement for String#length
  84. *
  85. * @param {string} str Valid Unicode string
  86. * @return {number} The number of Unicode characters in the string
  87. */
  88. function strlen(str) {
  89. // Call the native functions if there's no surrogate char
  90. if (!hasSurrogateUnit(str)) {
  91. return str.length;
  92. }
  93. let len = 0;
  94. for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  95. len++;
  96. }
  97. return len;
  98. }
  99. /**
  100. * Fully Unicode-enabled replacement for String#substr()
  101. *
  102. * @param {string} str Valid Unicode string
  103. * @param {number} start Location in Unicode sequence to begin extracting
  104. * @param {?number} length The number of Unicode characters to extract
  105. * (default: to the end of the string)
  106. * @return {string} Extracted sub-string
  107. */
  108. function substr(str, start, length) {
  109. start = start || 0;
  110. length = length === undefined ? Infinity : length || 0;
  111. // Call the native functions if there's no surrogate char
  112. if (!hasSurrogateUnit(str)) {
  113. return str.substr(start, length);
  114. }
  115. // Obvious cases
  116. const size = str.length;
  117. if (size <= 0 || start > size || length <= 0) {
  118. return '';
  119. }
  120. // Find the actual starting position
  121. let posA = 0;
  122. if (start > 0) {
  123. for (; start > 0 && posA < size; start--) {
  124. posA += getUTF16Length(str, posA);
  125. }
  126. if (posA >= size) {
  127. return '';
  128. }
  129. } else if (start < 0) {
  130. for (posA = size; start < 0 && 0 < posA; start++) {
  131. posA -= getUTF16Length(str, posA - 1);
  132. }
  133. if (posA < 0) {
  134. posA = 0;
  135. }
  136. }
  137. // Find the actual ending position
  138. let posB = size;
  139. if (length < size) {
  140. for (posB = posA; length > 0 && posB < size; length--) {
  141. posB += getUTF16Length(str, posB);
  142. }
  143. }
  144. return str.substring(posA, posB);
  145. }
  146. /**
  147. * Fully Unicode-enabled replacement for String#substring()
  148. *
  149. * @param {string} str Valid Unicode string
  150. * @param {number} start Location in Unicode sequence to begin extracting
  151. * @param {?number} end Location in Unicode sequence to end extracting
  152. * (default: end of the string)
  153. * @return {string} Extracted sub-string
  154. */
  155. function substring(str, start, end) {
  156. start = start || 0;
  157. end = end === undefined ? Infinity : end || 0;
  158. if (start < 0) {
  159. start = 0;
  160. }
  161. if (end < 0) {
  162. end = 0;
  163. }
  164. const length = Math.abs(end - start);
  165. start = start < end ? start : end;
  166. return substr(str, start, length);
  167. }
  168. /**
  169. * Get a list of Unicode code-points from a String
  170. *
  171. * @param {string} str Valid Unicode string
  172. * @return {array<number>} A list of code-points in [0..0x10FFFF]
  173. */
  174. function getCodePoints(str) {
  175. const codePoints = [];
  176. for (let pos = 0; pos < str.length; pos += getUTF16Length(str, pos)) {
  177. codePoints.push(str.codePointAt(pos));
  178. }
  179. return codePoints;
  180. }
  181. const UnicodeUtils = {
  182. getCodePoints: getCodePoints,
  183. getUTF16Length: getUTF16Length,
  184. hasSurrogateUnit: hasSurrogateUnit,
  185. isCodeUnitInSurrogateRange: isCodeUnitInSurrogateRange,
  186. isSurrogatePair: isSurrogatePair,
  187. strlen: strlen,
  188. substring: substring,
  189. substr: substr
  190. };
  191. module.exports = UnicodeUtils;