StringTools.hx 17 KB

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