StringTools.hx 17 KB

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