2
0

StringTools.hx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. /*
  2. * Copyright (C)2005-2019 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. import haxe.iterators.StringIterator;
  23. import haxe.iterators.StringKeyValueIterator;
  24. #if cpp
  25. using cpp.NativeString;
  26. #end
  27. /**
  28. This class provides advanced methods on Strings. It is ideally used with
  29. `using StringTools` and then acts as an [extension](https://haxe.org/manual/lf-static-extension.html)
  30. to the `String` class.
  31. If the first argument to any of the methods is null, the result is
  32. unspecified.
  33. **/
  34. class StringTools {
  35. /**
  36. Encode an URL by using the standard format.
  37. **/
  38. #if (!java && !cpp && !lua && !eval) inline #end public static function urlEncode(s:String):String {
  39. #if flash
  40. return untyped __global__["encodeURIComponent"](s);
  41. #elseif neko
  42. return untyped new String(_urlEncode(s.__s));
  43. #elseif js
  44. return untyped encodeURIComponent(s);
  45. #elseif cpp
  46. return untyped s.__URLEncode();
  47. #elseif java
  48. return postProcessUrlEncode(java.net.URLEncoder.encode(s, "UTF-8"));
  49. #elseif cs
  50. return untyped cs.system.Uri.EscapeDataString(s);
  51. #elseif python
  52. return python.lib.urllib.Parse.quote(s, "");
  53. #elseif hl
  54. var len = 0;
  55. var b = @:privateAccess s.bytes.urlEncode(len);
  56. return @:privateAccess String.__alloc__(b, len);
  57. #elseif lua
  58. s = lua.NativeStringTools.gsub(s, "\n", "\r\n");
  59. s = lua.NativeStringTools.gsub(s, "([^%w %-%_%.%~])", function(c) {
  60. return lua.NativeStringTools.format("%%%02X", lua.NativeStringTools.byte(c) + '');
  61. });
  62. s = lua.NativeStringTools.gsub(s, " ", "+");
  63. return s;
  64. #else
  65. return null;
  66. #end
  67. }
  68. #if java
  69. private static function postProcessUrlEncode(s:String):String {
  70. var ret = new StringBuf();
  71. var i = 0, len = s.length;
  72. while (i < len) {
  73. switch (_charAt(s, i++)) {
  74. case '+'.code:
  75. ret.add('%20');
  76. case '%'.code if (i <= len - 2):
  77. var c1 = _charAt(s, i++), c2 = _charAt(s, i++);
  78. switch [c1, c2] {
  79. case ['2'.code, '1'.code]:
  80. ret.addChar('!'.code);
  81. case ['2'.code, '7'.code]:
  82. ret.addChar('\''.code);
  83. case ['2'.code, '8'.code]:
  84. ret.addChar('('.code);
  85. case ['2'.code, '9'.code]:
  86. ret.addChar(')'.code);
  87. case ['7'.code, 'E'.code] | ['7'.code, 'e'.code]:
  88. ret.addChar('~'.code);
  89. case _:
  90. ret.addChar('%'.code);
  91. ret.addChar(cast c1);
  92. ret.addChar(cast c2);
  93. }
  94. case var chr:
  95. ret.addChar(cast chr);
  96. }
  97. }
  98. return ret.toString();
  99. }
  100. #end
  101. /**
  102. Decode an URL using the standard format.
  103. **/
  104. #if (!java && !cpp && !lua && !eval) inline #end public static function urlDecode(s:String):String {
  105. #if flash
  106. return untyped __global__["decodeURIComponent"](s.split("+").join(" "));
  107. #elseif neko
  108. return untyped new String(_urlDecode(s.__s));
  109. #elseif js
  110. return untyped decodeURIComponent(s.split("+").join(" "));
  111. #elseif cpp
  112. return untyped s.__URLDecode();
  113. #elseif java
  114. try
  115. return java.net.URLDecoder.decode(s, "UTF-8")
  116. catch (e:Dynamic)
  117. throw e;
  118. #elseif cs
  119. return untyped cs.system.Uri.UnescapeDataString(s);
  120. #elseif python
  121. return python.lib.urllib.Parse.unquote(s);
  122. #elseif hl
  123. var len = 0;
  124. var b = @:privateAccess s.bytes.urlDecode(len);
  125. return @:privateAccess String.__alloc__(b, len);
  126. #elseif lua
  127. s = lua.NativeStringTools.gsub(s, "+", " ");
  128. s = lua.NativeStringTools.gsub(s, "%%(%x%x)", function(h) {
  129. return lua.NativeStringTools.char(lua.Lua.tonumber(h, 16));
  130. });
  131. s = lua.NativeStringTools.gsub(s, "\r\n", "\n");
  132. return s;
  133. #else
  134. return null;
  135. #end
  136. }
  137. /**
  138. Escapes HTML special characters of the string `s`.
  139. The following replacements are made:
  140. - `&` becomes `&amp`;
  141. - `<` becomes `&lt`;
  142. - `>` becomes `&gt`;
  143. If `quotes` is true, the following characters are also replaced:
  144. - `"` becomes `&quot`;
  145. - `'` becomes `&#039`;
  146. **/
  147. public static function htmlEscape(s:String, ?quotes:Bool):String {
  148. var buf = new StringBuf();
  149. for (code in #if neko iterator(s) #else new haxe.iterators.StringIteratorUnicode(s) #end) {
  150. switch (code) {
  151. case '&'.code:
  152. buf.add("&amp;");
  153. case '<'.code:
  154. buf.add("&lt;");
  155. case '>'.code:
  156. buf.add("&gt;");
  157. case '"'.code if (quotes):
  158. buf.add("&quot;");
  159. case '\''.code if (quotes):
  160. buf.add("&#039;");
  161. case _:
  162. buf.addChar(code);
  163. }
  164. }
  165. return buf.toString();
  166. }
  167. /**
  168. Unescapes HTML special characters of the string `s`.
  169. This is the inverse operation to htmlEscape, i.e. the following always
  170. holds: `htmlUnescape(htmlEscape(s)) == s`
  171. The replacements follow:
  172. - `&amp;` becomes `&`
  173. - `&lt;` becomes `<`
  174. - `&gt;` becomes `>`
  175. - `&quot;` becomes `"`
  176. - `&#039;` becomes `'`
  177. **/
  178. public static function htmlUnescape(s:String):String {
  179. return s.split("&gt;")
  180. .join(">")
  181. .split("&lt;")
  182. .join("<")
  183. .split("&quot;")
  184. .join('"')
  185. .split("&#039;")
  186. .join("'")
  187. .split("&amp;")
  188. .join("&");
  189. }
  190. /**
  191. Returns `true` if `s` contains `value` and `false` otherwise.
  192. When `value` is `null`, the result is unspecified.
  193. **/
  194. public static inline function contains(s:String, value:String):Bool {
  195. #if (js && js_es >= 6)
  196. return (cast s).includes(value);
  197. #else
  198. return s.indexOf(value) != -1;
  199. #end
  200. }
  201. /**
  202. Tells if the string `s` starts with the string `start`.
  203. If `start` is `null`, the result is unspecified.
  204. If `start` is the empty String `""`, the result is true.
  205. **/
  206. public static #if (cs || java || python || (js && js_es >= 6)) inline #end function startsWith(s:String, start:String):Bool {
  207. #if java
  208. return (cast s : java.NativeString).startsWith(start);
  209. #elseif cs
  210. return untyped s.StartsWith(start);
  211. #elseif hl
  212. return @:privateAccess (s.length >= start.length && s.bytes.compare(0, start.bytes, 0, start.length << 1) == 0);
  213. #elseif python
  214. return python.NativeStringTools.startswith(s, start);
  215. #elseif (js && js_es >= 6)
  216. return (cast s).startsWith(start);
  217. #elseif lua
  218. return untyped __lua__("{0}:sub(1, #{1}) == {1}", s, start);
  219. #else
  220. return (s.length >= start.length && s.lastIndexOf(start, 0) == 0);
  221. #end
  222. }
  223. /**
  224. Tells if the string `s` ends with the string `end`.
  225. If `end` is `null`, the result is unspecified.
  226. If `end` is the empty String `""`, the result is true.
  227. **/
  228. public static #if (cs || java || python || (js && js_es >= 6)) inline #end function endsWith(s:String, end:String):Bool {
  229. #if java
  230. return (cast s : java.NativeString).endsWith(end);
  231. #elseif cs
  232. return untyped s.EndsWith(end);
  233. #elseif hl
  234. var elen = end.length;
  235. var slen = s.length;
  236. return @:privateAccess (slen >= elen && s.bytes.compare((slen - elen) << 1, end.bytes, 0, elen << 1) == 0);
  237. #elseif python
  238. return python.NativeStringTools.endswith(s, end);
  239. #elseif (js && js_es >= 6)
  240. return (cast s).endsWith(end);
  241. #elseif lua
  242. return end == "" || untyped __lua__("{0}:sub(-#{1}) == {1}", s, end);
  243. #else
  244. var elen = end.length;
  245. var slen = s.length;
  246. return (slen >= elen && s.indexOf(end, (slen - elen)) == (slen - elen));
  247. #end
  248. }
  249. /**
  250. Tells if the character in the string `s` at position `pos` is a space.
  251. A character is considered to be a space character if its character code
  252. is 9,10,11,12,13 or 32.
  253. If `s` is the empty String `""`, or if pos is not a valid position within
  254. `s`, the result is false.
  255. **/
  256. public static function isSpace(s:String, pos:Int):Bool {
  257. #if (python || lua)
  258. if (s.length == 0 || pos < 0 || pos >= s.length)
  259. return false;
  260. #end
  261. var c = s.charCodeAt(pos);
  262. return (c > 8 && c < 14) || c == 32;
  263. }
  264. /**
  265. Removes leading space characters of `s`.
  266. This function internally calls `isSpace()` to decide which characters to
  267. remove.
  268. If `s` is the empty String `""` or consists only of space characters, the
  269. result is the empty String `""`.
  270. **/
  271. public #if cs inline #end static function ltrim(s:String):String {
  272. #if cs
  273. return untyped s.TrimStart();
  274. #else
  275. var l = s.length;
  276. var r = 0;
  277. while (r < l && isSpace(s, r)) {
  278. r++;
  279. }
  280. if (r > 0)
  281. return s.substr(r, l - r);
  282. else
  283. return s;
  284. #end
  285. }
  286. /**
  287. Removes trailing space characters of `s`.
  288. This function internally calls `isSpace()` to decide which characters to
  289. remove.
  290. If `s` is the empty String `""` or consists only of space characters, the
  291. result is the empty String `""`.
  292. **/
  293. public #if cs inline #end static function rtrim(s:String):String {
  294. #if cs
  295. return untyped s.TrimEnd();
  296. #else
  297. var l = s.length;
  298. var r = 0;
  299. while (r < l && isSpace(s, l - r - 1)) {
  300. r++;
  301. }
  302. if (r > 0) {
  303. return s.substr(0, l - r);
  304. } else {
  305. return s;
  306. }
  307. #end
  308. }
  309. /**
  310. Removes leading and trailing space characters of `s`.
  311. This is a convenience function for `ltrim(rtrim(s))`.
  312. **/
  313. public #if (cs || java) inline #end static function trim(s:String):String {
  314. #if cs
  315. return untyped s.Trim();
  316. #elseif java
  317. return (cast s : java.NativeString).trim();
  318. #else
  319. return ltrim(rtrim(s));
  320. #end
  321. }
  322. /**
  323. Concatenates `c` to `s` until `s.length` is at least `l`.
  324. If `c` is the empty String `""` or if `l` does not exceed `s.length`,
  325. `s` is returned unchanged.
  326. If `c.length` is 1, the resulting String length is exactly `l`.
  327. Otherwise the length may exceed `l`.
  328. If `c` is null, the result is unspecified.
  329. **/
  330. public static function lpad(s:String, c:String, l:Int):String {
  331. if (c.length <= 0)
  332. return s;
  333. var buf = new StringBuf();
  334. l -= s.length;
  335. while (buf.length < l) {
  336. buf.add(c);
  337. }
  338. buf.add(s);
  339. return buf.toString();
  340. }
  341. /**
  342. Appends `c` to `s` until `s.length` is at least `l`.
  343. If `c` is the empty String `""` or if `l` does not exceed `s.length`,
  344. `s` is returned unchanged.
  345. If `c.length` is 1, the resulting String length is exactly `l`.
  346. Otherwise the length may exceed `l`.
  347. If `c` is null, the result is unspecified.
  348. **/
  349. public static function rpad(s:String, c:String, l:Int):String {
  350. if (c.length <= 0)
  351. return s;
  352. var buf = new StringBuf();
  353. buf.add(s);
  354. while (buf.length < l) {
  355. buf.add(c);
  356. }
  357. return buf.toString();
  358. }
  359. /**
  360. Replace all occurrences of the String `sub` in the String `s` by the
  361. String `by`.
  362. If `sub` is the empty String `""`, `by` is inserted after each character
  363. of `s` except the last one. If `by` is also the empty String `""`, `s`
  364. remains unchanged.
  365. If `sub` or `by` are null, the result is unspecified.
  366. **/
  367. public static function replace(s:String, sub:String, by:String):String {
  368. #if java
  369. if (sub.length == 0)
  370. return s.split(sub).join(by);
  371. else
  372. return (cast s : java.NativeString).replace(sub, by);
  373. #elseif cs
  374. if (sub.length == 0)
  375. return s.split(sub).join(by);
  376. else
  377. return untyped s.Replace(sub, by);
  378. #else
  379. return s.split(sub).join(by);
  380. #end
  381. }
  382. /**
  383. Encodes `n` into a hexadecimal representation.
  384. If `digits` is specified, the resulting String is padded with "0" until
  385. its `length` equals `digits`.
  386. **/
  387. public static function hex(n:Int, ?digits:Int) {
  388. #if flash
  389. var n:UInt = n;
  390. var s:String = untyped n.toString(16);
  391. s = s.toUpperCase();
  392. #else
  393. var s = "";
  394. var hexChars = "0123456789ABCDEF";
  395. do {
  396. s = hexChars.charAt(n & 15) + s;
  397. n >>>= 4;
  398. } while (n > 0);
  399. #end
  400. #if python
  401. if (digits != null && s.length < digits) {
  402. var diff = digits - s.length;
  403. for (_ in 0...diff) {
  404. s = "0" + s;
  405. }
  406. }
  407. #else
  408. if (digits != null)
  409. while (s.length < digits)
  410. s = "0" + s;
  411. #end
  412. return s;
  413. }
  414. /**
  415. Returns the character code at position `index` of String `s`, or an
  416. end-of-file indicator at if `position` equals `s.length`.
  417. This method is faster than `String.charCodeAt()` on some platforms, but
  418. the result is unspecified if `index` is negative or greater than
  419. `s.length`.
  420. End of file status can be checked by calling `StringTools.isEof()` with
  421. the returned value as argument.
  422. This operation is not guaranteed to work if `s` contains the `\0`
  423. character.
  424. **/
  425. public static #if !eval inline #end function fastCodeAt(s:String, index:Int):Int {
  426. #if neko
  427. return untyped __dollar__sget(s.__s, index);
  428. #elseif cpp
  429. return untyped s.cca(index);
  430. #elseif flash
  431. return untyped s.cca(index);
  432. #elseif java
  433. return (index < s.length) ? cast(_charAt(s, index), Int) : -1;
  434. #elseif cs
  435. return (cast(index, UInt) < s.length) ? cast(s[index], Int) : -1;
  436. #elseif js
  437. return (cast s).charCodeAt(index);
  438. #elseif python
  439. return if (index >= s.length) -1 else python.internal.UBuiltins.ord(python.Syntax.arrayAccess(s, index));
  440. #elseif hl
  441. return @:privateAccess s.bytes.getUI16(index << 1);
  442. #elseif lua
  443. #if lua_vanilla
  444. return lua.NativeStringTools.byte(s, index + 1);
  445. #else
  446. return lua.lib.luautf8.Utf8.byte(s, index + 1);
  447. #end
  448. #else
  449. return untyped s.cca(index);
  450. #end
  451. }
  452. /**
  453. Returns the character code at position `index` of String `s`, or an
  454. end-of-file indicator at if `position` equals `s.length`.
  455. This method is faster than `String.charCodeAt()` on some platforms, but
  456. the result is unspecified if `index` is negative or greater than
  457. `s.length`.
  458. This operation is not guaranteed to work if `s` contains the `\0`
  459. character.
  460. **/
  461. public static #if !eval inline #end function unsafeCodeAt(s:String, index:Int):Int {
  462. #if neko
  463. return untyped __dollar__sget(s.__s, index);
  464. #elseif cpp
  465. return untyped s.cca(index);
  466. #elseif flash
  467. return untyped s.cca(index);
  468. #elseif java
  469. return cast(_charAt(s, index), Int);
  470. #elseif cs
  471. return cast(s[index], Int);
  472. #elseif js
  473. return (cast s).charCodeAt(index);
  474. #elseif python
  475. return python.internal.UBuiltins.ord(python.Syntax.arrayAccess(s, index));
  476. #elseif hl
  477. return @:privateAccess s.bytes.getUI16(index << 1);
  478. #elseif lua
  479. #if lua_vanilla
  480. return lua.NativeStringTools.byte(s, index + 1);
  481. #else
  482. return lua.lib.luautf8.Utf8.byte(s, index + 1);
  483. #end
  484. #else
  485. return untyped s.cca(index);
  486. #end
  487. }
  488. /**
  489. Returns an iterator of the char codes.
  490. Note that char codes may differ across platforms because of different
  491. internal encoding of strings in different runtimes.
  492. For the consistent cross-platform UTF8 char codes see `haxe.iterators.StringIteratorUnicode`.
  493. **/
  494. public static inline function iterator(s:String):StringIterator {
  495. return new StringIterator(s);
  496. }
  497. /**
  498. Returns an iterator of the char indexes and codes.
  499. Note that char codes may differ across platforms because of different
  500. internal encoding of strings in different of runtimes.
  501. For the consistent cross-platform UTF8 char codes see `haxe.iterators.StringKeyValueIteratorUnicode`.
  502. **/
  503. public static inline function keyValueIterator(s:String):StringKeyValueIterator {
  504. return new StringKeyValueIterator(s);
  505. }
  506. /**
  507. Tells if `c` represents the end-of-file (EOF) character.
  508. **/
  509. @:noUsing public static inline function isEof(c:Int):Bool {
  510. #if (flash || cpp || hl)
  511. return c == 0;
  512. #elseif js
  513. return c != c; // fast NaN
  514. #elseif (neko || lua || eval)
  515. return c == null;
  516. #elseif (cs || java || python)
  517. return c == -1;
  518. #else
  519. return false;
  520. #end
  521. }
  522. /**
  523. Returns a String that can be used as a single command line argument
  524. on Unix.
  525. The input will be quoted, or escaped if necessary.
  526. **/
  527. @:noCompletion
  528. @:deprecated('StringTools.quoteUnixArg() is deprecated. Use haxe.SysTools.quoteUnixArg() instead.')
  529. public static function quoteUnixArg(argument:String):String {
  530. return inline haxe.SysTools.quoteUnixArg(argument);
  531. }
  532. /**
  533. Character codes of the characters that will be escaped by `quoteWinArg(_, true)`.
  534. **/
  535. @:noCompletion
  536. @:deprecated('StringTools.winMetaCharacters is deprecated. Use haxe.SysTools.winMetaCharacters instead.')
  537. public static var winMetaCharacters:Array<Int> = cast haxe.SysTools.winMetaCharacters;
  538. /**
  539. Returns a String that can be used as a single command line argument
  540. on Windows.
  541. The input will be quoted, or escaped if necessary, such that the output
  542. will be parsed as a single argument using the rule specified in
  543. http://msdn.microsoft.com/en-us/library/ms880421
  544. Examples:
  545. ```haxe
  546. quoteWinArg("abc") == "abc";
  547. quoteWinArg("ab c") == '"ab c"';
  548. ```
  549. **/
  550. @:noCompletion
  551. @:deprecated('StringTools.quoteWinArg() is deprecated. Use haxe.SysTools.quoteWinArg() instead.')
  552. public static function quoteWinArg(argument:String, escapeMetaCharacters:Bool):String {
  553. return inline haxe.SysTools.quoteWinArg(argument, escapeMetaCharacters);
  554. }
  555. #if java
  556. private static inline function _charAt(str:String, idx:Int):java.StdTypes.Char16
  557. return (cast str : java.NativeString).charAt(idx);
  558. #end
  559. #if neko
  560. private static var _urlEncode = neko.Lib.load("std", "url_encode", 1);
  561. private static var _urlDecode = neko.Lib.load("std", "url_decode", 1);
  562. #end
  563. #if utf16
  564. static inline var MIN_SURROGATE_CODE_POINT = 65536;
  565. static inline function utf16CodePointAt(s:String, index:Int):Int {
  566. var c = StringTools.fastCodeAt(s, index);
  567. if (c >= 0xD800 && c <= 0xDBFF) {
  568. c = ((c - 0xD7C0) << 10) | (StringTools.fastCodeAt(s, index + 1) & 0x3FF);
  569. }
  570. return c;
  571. }
  572. #end
  573. }