lib/core: Added `to_s_unsafe` method to `NativeString` which does not cleans a `Nativ...
[nit.git] / lib / core / text / abstract_text.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Abstract class for manipulation of sequences of characters
12 module abstract_text
13
14 import native
15 import math
16 import collection
17 intrude import collection::array
18
19 in "C" `{
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23 `}
24
25 # High-level abstraction for all text representations
26 abstract class Text
27 super Comparable
28
29 redef type OTHER: Text
30
31 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
32 type SELFTYPE: Text
33
34 # Gets a view on the chars of the Text object
35 #
36 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
37 fun chars: SequenceRead[Char] is abstract
38
39 # Gets a view on the bytes of the Text object
40 #
41 # assert "hello".bytes.to_a == [104u8, 101u8, 108u8, 108u8, 111u8]
42 fun bytes: SequenceRead[Byte] is abstract
43
44 # Number of characters contained in self.
45 #
46 # assert "12345".length == 5
47 # assert "".length == 0
48 # assert "あいうえお".length == 5
49 fun length: Int is abstract
50
51 # Number of bytes in `self`
52 #
53 # assert "12345".bytelen == 5
54 # assert "あいうえお".bytelen == 15
55 fun bytelen: Int is abstract
56
57 # Create a substring.
58 #
59 # assert "abcd".substring(1, 2) == "bc"
60 # assert "abcd".substring(-1, 2) == "a"
61 # assert "abcd".substring(1, 0) == ""
62 # assert "abcd".substring(2, 5) == "cd"
63 # assert "あいうえお".substring(1,3) == "いうえ"
64 #
65 # A `from` index < 0 will be replaced by 0.
66 # Unless a `count` value is > 0 at the same time.
67 # In this case, `from += count` and `count -= from`.
68 fun substring(from: Int, count: Int): SELFTYPE is abstract
69
70 # Iterates on the substrings of self if any
71 private fun substrings: Iterator[FlatText] is abstract
72
73 # Is the current Text empty (== "")
74 #
75 # assert "".is_empty
76 # assert not "foo".is_empty
77 fun is_empty: Bool do return self.length == 0
78
79 # Returns an empty Text of the right type
80 #
81 # This method is used internally to get the right
82 # implementation of an empty string.
83 protected fun empty: SELFTYPE is abstract
84
85 # Gets the first char of the Text
86 #
87 # DEPRECATED : Use self.chars.first instead
88 fun first: Char do return self.chars[0]
89
90 # Access a character at `index` in the string.
91 #
92 # assert "abcd"[2] == 'c'
93 #
94 # DEPRECATED : Use self.chars.[] instead
95 fun [](index: Int): Char do return self.chars[index]
96
97 # Gets the index of the first occurence of 'c'
98 #
99 # Returns -1 if not found
100 #
101 # DEPRECATED : Use self.chars.index_of instead
102 fun index_of(c: Char): Int
103 do
104 return index_of_from(c, 0)
105 end
106
107 # Gets the last char of self
108 #
109 # DEPRECATED : Use self.chars.last instead
110 fun last: Char do return self.chars[length-1]
111
112 # Gets the index of the first occurence of ´c´ starting from ´pos´
113 #
114 # Returns -1 if not found
115 #
116 # DEPRECATED : Use self.chars.index_of_from instead
117 fun index_of_from(c: Char, pos: Int): Int
118 do
119 var iter = self.chars.iterator_from(pos)
120 while iter.is_ok do
121 if iter.item == c then return iter.index
122 iter.next
123 end
124 return -1
125 end
126
127 # Gets the last index of char ´c´
128 #
129 # Returns -1 if not found
130 #
131 # DEPRECATED : Use self.chars.last_index_of instead
132 fun last_index_of(c: Char): Int
133 do
134 return last_index_of_from(c, length - 1)
135 end
136
137 # Return a null terminated char *
138 fun to_cstring: NativeString is abstract
139
140 # The index of the last occurrence of an element starting from pos (in reverse order).
141 #
142 # var s = "/etc/bin/test/test.nit"
143 # assert s.last_index_of_from('/', s.length-1) == 13
144 # assert s.last_index_of_from('/', 12) == 8
145 #
146 # Returns -1 if not found
147 #
148 # DEPRECATED : Use self.chars.last_index_of_from instead
149 fun last_index_of_from(item: Char, pos: Int): Int do return chars.last_index_of_from(item, pos)
150
151 # Gets an iterator on the chars of self
152 #
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator: Iterator[Char]
155 do
156 return self.chars.iterator
157 end
158
159
160 # Gets an Array containing the chars of self
161 #
162 # DEPRECATED : Use self.chars.to_a instead
163 fun to_a: Array[Char] do return chars.to_a
164
165 # Create a substring from `self` beginning at the `from` position
166 #
167 # assert "abcd".substring_from(1) == "bcd"
168 # assert "abcd".substring_from(-1) == "abcd"
169 # assert "abcd".substring_from(2) == "cd"
170 #
171 # As with substring, a `from` index < 0 will be replaced by 0
172 fun substring_from(from: Int): SELFTYPE
173 do
174 if from >= self.length then return empty
175 if from < 0 then from = 0
176 return substring(from, length - from)
177 end
178
179 # Does self have a substring `str` starting from position `pos`?
180 #
181 # assert "abcd".has_substring("bc",1) == true
182 # assert "abcd".has_substring("bc",2) == false
183 #
184 # Returns true iff all characters of `str` are presents
185 # at the expected index in `self.`
186 # The first character of `str` being at `pos`, the second
187 # character being at `pos+1` and so on...
188 #
189 # This means that all characters of `str` need to be inside `self`.
190 #
191 # assert "abcd".has_substring("xab", -1) == false
192 # assert "abcd".has_substring("cdx", 2) == false
193 #
194 # And that the empty string is always a valid substring.
195 #
196 # assert "abcd".has_substring("", 2) == true
197 # assert "abcd".has_substring("", 200) == true
198 fun has_substring(str: String, pos: Int): Bool
199 do
200 if str.is_empty then return true
201 if pos < 0 or pos + str.length > length then return false
202 var myiter = self.chars.iterator_from(pos)
203 var itsiter = str.chars.iterator
204 while myiter.is_ok and itsiter.is_ok do
205 if myiter.item != itsiter.item then return false
206 myiter.next
207 itsiter.next
208 end
209 if itsiter.is_ok then return false
210 return true
211 end
212
213 # Is this string prefixed by `prefix`?
214 #
215 # assert "abcd".has_prefix("ab") == true
216 # assert "abcbc".has_prefix("bc") == false
217 # assert "ab".has_prefix("abcd") == false
218 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
219
220 # Is this string suffixed by `suffix`?
221 #
222 # assert "abcd".has_suffix("abc") == false
223 # assert "abcd".has_suffix("bcd") == true
224 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
225
226 # Returns `self` as the corresponding integer
227 #
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
230 # assert "0x64".to_i == 100
231 # assert "0b1100_0011".to_i== 195
232 # assert "--12".to_i == 12
233 #
234 # REQUIRE: `self`.`is_int`
235 fun to_i: Int is abstract
236
237 # If `self` contains a float, return the corresponding float
238 #
239 # assert "123".to_f == 123.0
240 # assert "-1".to_f == -1.0
241 # assert "-1.2e-3".to_f == -0.0012
242 fun to_f: Float
243 do
244 # Shortcut
245 return to_s.to_cstring.atof
246 end
247
248 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
249 #
250 # assert "ff".to_hex == 255
251 fun to_hex(pos, ln: nullable Int): Int do
252 var res = 0
253 if pos == null then pos = 0
254 if ln == null then ln = length - pos
255 var max = pos + ln
256 for i in [pos .. max[ do
257 res <<= 4
258 res += self[i].from_hex
259 end
260 return res
261 end
262
263 # If `self` contains only digits <= '7', return the corresponding integer.
264 #
265 # assert "714".to_oct == 460
266 fun to_oct: Int do return a_to(8)
267
268 # If `self` contains only '0' et '1', return the corresponding integer.
269 #
270 # assert "101101".to_bin == 45
271 fun to_bin: Int do return a_to(2)
272
273 # If `self` contains only digits '0' .. '9', return the corresponding integer.
274 #
275 # assert "108".to_dec == 108
276 fun to_dec: Int do return a_to(10)
277
278 # If `self` contains only digits and letters, return the corresponding integer in a given base
279 #
280 # assert "120".a_to(3) == 15
281 fun a_to(base: Int) : Int
282 do
283 var i = 0
284 var neg = false
285
286 for j in [0..length[ do
287 var c = chars[j]
288 var v = c.to_i
289 if v > base then
290 if neg then
291 return -i
292 else
293 return i
294 end
295 else if v < 0 then
296 neg = true
297 else
298 i = i * base + v
299 end
300 end
301 if neg then
302 return -i
303 else
304 return i
305 end
306 end
307
308 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
309 #
310 # assert "123".is_numeric == true
311 # assert "1.2".is_numeric == true
312 # assert "1,2".is_numeric == true
313 # assert "1..2".is_numeric == false
314 fun is_numeric: Bool
315 do
316 var has_point_or_comma = false
317 for i in [0..length[ do
318 var c = chars[i]
319 if not c.is_numeric then
320 if (c == '.' or c == ',') and not has_point_or_comma then
321 has_point_or_comma = true
322 else
323 return false
324 end
325 end
326 end
327 return true
328 end
329
330 # Returns `true` if the string contains only Hex chars
331 #
332 # assert "048bf".is_hex == true
333 # assert "ABCDEF".is_hex == true
334 # assert "0G".is_hex == false
335 fun is_hex: Bool
336 do
337 for i in [0..length[ do
338 var c = chars[i]
339 if not (c >= 'a' and c <= 'f') and
340 not (c >= 'A' and c <= 'F') and
341 not (c >= '0' and c <= '9') then return false
342 end
343 return true
344 end
345
346 # Returns `true` if the string contains only Binary digits
347 #
348 # assert "1101100".is_bin == true
349 # assert "1101020".is_bin == false
350 fun is_bin: Bool do
351 for i in chars do if i != '0' and i != '1' then return false
352 return true
353 end
354
355 # Returns `true` if the string contains only Octal digits
356 #
357 # assert "213453".is_oct == true
358 # assert "781".is_oct == false
359 fun is_oct: Bool do
360 for i in chars do if i < '0' or i > '7' then return false
361 return true
362 end
363
364 # Returns `true` if the string contains only Decimal digits
365 #
366 # assert "10839".is_dec == true
367 # assert "164F".is_dec == false
368 fun is_dec: Bool do
369 for i in chars do if i < '0' or i > '9' then return false
370 return true
371 end
372
373 # Are all letters in `self` upper-case ?
374 #
375 # assert "HELLO WORLD".is_upper == true
376 # assert "%$&%!".is_upper == true
377 # assert "hello world".is_upper == false
378 # assert "Hello World".is_upper == false
379 fun is_upper: Bool
380 do
381 for i in [0..length[ do
382 var char = chars[i]
383 if char.is_lower then return false
384 end
385 return true
386 end
387
388 # Are all letters in `self` lower-case ?
389 #
390 # assert "hello world".is_lower == true
391 # assert "%$&%!".is_lower == true
392 # assert "Hello World".is_lower == false
393 fun is_lower: Bool
394 do
395 for i in [0..length[ do
396 var char = chars[i]
397 if char.is_upper then return false
398 end
399 return true
400 end
401
402 # Removes the whitespaces at the beginning of self
403 #
404 # assert " \n\thello \n\t".l_trim == "hello \n\t"
405 #
406 # `Char::is_whitespace` determines what is a whitespace.
407 fun l_trim: SELFTYPE
408 do
409 var iter = self.chars.iterator
410 while iter.is_ok do
411 if not iter.item.is_whitespace then break
412 iter.next
413 end
414 if iter.index == length then return self.empty
415 return self.substring_from(iter.index)
416 end
417
418 # Removes the whitespaces at the end of self
419 #
420 # assert " \n\thello \n\t".r_trim == " \n\thello"
421 #
422 # `Char::is_whitespace` determines what is a whitespace.
423 fun r_trim: SELFTYPE
424 do
425 var iter = self.chars.reverse_iterator
426 while iter.is_ok do
427 if not iter.item.is_whitespace then break
428 iter.next
429 end
430 if iter.index < 0 then return self.empty
431 return self.substring(0, iter.index + 1)
432 end
433
434 # Trims trailing and preceding white spaces
435 #
436 # assert " Hello World ! ".trim == "Hello World !"
437 # assert "\na\nb\tc\t".trim == "a\nb\tc"
438 #
439 # `Char::is_whitespace` determines what is a whitespace.
440 fun trim: SELFTYPE do return (self.l_trim).r_trim
441
442 # Is the string non-empty but only made of whitespaces?
443 #
444 # assert " \n\t ".is_whitespace == true
445 # assert " hello ".is_whitespace == false
446 # assert "".is_whitespace == false
447 #
448 # `Char::is_whitespace` determines what is a whitespace.
449 fun is_whitespace: Bool
450 do
451 if is_empty then return false
452 for c in self.chars do
453 if not c.is_whitespace then return false
454 end
455 return true
456 end
457
458 # Returns `self` removed from its last line terminator (if any).
459 #
460 # assert "Hello\n".chomp == "Hello"
461 # assert "Hello".chomp == "Hello"
462 #
463 # assert "\n".chomp == ""
464 # assert "".chomp == ""
465 #
466 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
467 # A single line terminator, the last one, is removed.
468 #
469 # assert "\r\n".chomp == ""
470 # assert "\r\n\n".chomp == "\r\n"
471 # assert "\r\n\r\n".chomp == "\r\n"
472 # assert "\r\n\r".chomp == "\r\n"
473 #
474 # Note: unlike with most IO methods like `Reader::read_line`,
475 # a single `\r` is considered here to be a line terminator and will be removed.
476 fun chomp: SELFTYPE
477 do
478 var len = length
479 if len == 0 then return self
480 var l = self.chars.last
481 if l == '\r' then
482 return substring(0, len-1)
483 else if l != '\n' then
484 return self
485 else if len > 1 and self.chars[len-2] == '\r' then
486 return substring(0, len-2)
487 else
488 return substring(0, len-1)
489 end
490 end
491
492 # Justify a self in a space of `length`
493 #
494 # `left` is the space ratio on the left side.
495 # * 0.0 for left-justified (no space at the left)
496 # * 1.0 for right-justified (all spaces at the left)
497 # * 0.5 for centered (half the spaces at the left)
498 #
499 # Examples
500 #
501 # assert "hello".justify(10, 0.0) == "hello "
502 # assert "hello".justify(10, 1.0) == " hello"
503 # assert "hello".justify(10, 0.5) == " hello "
504 #
505 # If `length` is not enough, `self` is returned as is.
506 #
507 # assert "hello".justify(2, 0.0) == "hello"
508 #
509 # REQUIRE: `left >= 0.0 and left <= 1.0`
510 # ENSURE: `self.length <= length implies result.length == length`
511 # ENSURE: `self.length >= length implies result == self`
512 fun justify(length: Int, left: Float): String
513 do
514 var diff = length - self.length
515 if diff <= 0 then return to_s
516 assert left >= 0.0 and left <= 1.0
517 var before = (diff.to_f * left).to_i
518 return " " * before + self + " " * (diff-before)
519 end
520
521 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
522 #
523 # This method is injective (two different inputs never produce the same
524 # output) and the returned string always respect the following rules:
525 #
526 # * Contains only US-ASCII letters, digits and underscores.
527 # * Never starts with a digit.
528 # * Never ends with an underscore.
529 # * Never contains two contiguous underscores.
530 #
531 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
532 # assert "__".to_cmangle == "_95d_95d"
533 # assert "__d".to_cmangle == "_95d_d"
534 # assert "_d_".to_cmangle == "_d_95d"
535 # assert "_42".to_cmangle == "_95d42"
536 # assert "foo".to_cmangle == "foo"
537 # assert "".to_cmangle == ""
538 fun to_cmangle: String
539 do
540 if is_empty then return ""
541 var res = new Buffer
542 var underscore = false
543 var start = 0
544 var c = chars[0]
545
546 if c >= '0' and c <= '9' then
547 res.add('_')
548 res.append(c.code_point.to_s)
549 res.add('d')
550 start = 1
551 end
552 for i in [start..length[ do
553 c = chars[i]
554 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
555 res.add(c)
556 underscore = false
557 continue
558 end
559 if underscore then
560 res.append('_'.code_point.to_s)
561 res.add('d')
562 end
563 if c >= '0' and c <= '9' then
564 res.add(c)
565 underscore = false
566 else if c == '_' then
567 res.add(c)
568 underscore = true
569 else
570 res.add('_')
571 res.append(c.code_point.to_s)
572 res.add('d')
573 underscore = false
574 end
575 end
576 if underscore then
577 res.append('_'.code_point.to_s)
578 res.add('d')
579 end
580 return res.to_s
581 end
582
583 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
584 #
585 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
586 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
587 #
588 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
589 # Three digits are always used to avoid following digits to be interpreted as an element
590 # of the octal sequence.
591 #
592 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
593 #
594 # The exceptions are the common `\t` and `\n`.
595 fun escape_to_c: String
596 do
597 var b = new Buffer
598 for i in [0..length[ do
599 var c = chars[i]
600 if c == '\n' then
601 b.append("\\n")
602 else if c == '\t' then
603 b.append("\\t")
604 else if c == '"' then
605 b.append("\\\"")
606 else if c == '\'' then
607 b.append("\\\'")
608 else if c == '\\' then
609 b.append("\\\\")
610 else if c.code_point < 32 then
611 b.add('\\')
612 var oct = c.code_point.to_base(8, false)
613 # Force 3 octal digits since it is the
614 # maximum allowed in the C specification
615 if oct.length == 1 then
616 b.add('0')
617 b.add('0')
618 else if oct.length == 2 then
619 b.add('0')
620 end
621 b.append(oct)
622 else
623 b.add(c)
624 end
625 end
626 return b.to_s
627 end
628
629 # Escape additionnal characters
630 # The result might no be legal in C but be used in other languages
631 #
632 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
633 fun escape_more_to_c(chars: String): String
634 do
635 var b = new Buffer
636 for c in escape_to_c.chars do
637 if chars.chars.has(c) then
638 b.add('\\')
639 end
640 b.add(c)
641 end
642 return b.to_s
643 end
644
645 # Escape to C plus braces
646 #
647 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
648 fun escape_to_nit: String do return escape_more_to_c("\{\}")
649
650 # Escape to POSIX Shell (sh).
651 #
652 # Abort if the text contains a null byte.
653 #
654 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
655 fun escape_to_sh: String do
656 var b = new Buffer
657 b.chars.add '\''
658 for i in [0..length[ do
659 var c = chars[i]
660 if c == '\'' then
661 b.append("'\\''")
662 else
663 assert without_null_byte: c != '\0'
664 b.add(c)
665 end
666 end
667 b.chars.add '\''
668 return b.to_s
669 end
670
671 # Escape to include in a Makefile
672 #
673 # Unfortunately, some characters are not escapable in Makefile.
674 # These characters are `;`, `|`, `\`, and the non-printable ones.
675 # They will be rendered as `"?{hex}"`.
676 fun escape_to_mk: String do
677 var b = new Buffer
678 for i in [0..length[ do
679 var c = chars[i]
680 if c == '$' then
681 b.append("$$")
682 else if c == ':' or c == ' ' or c == '#' then
683 b.add('\\')
684 b.add(c)
685 else if c.code_point < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
686 b.append("?{c.code_point.to_base(16, false)}")
687 else
688 b.add(c)
689 end
690 end
691 return b.to_s
692 end
693
694 # Return a string where Nit escape sequences are transformed.
695 #
696 # var s = "\\n"
697 # assert s.length == 2
698 # var u = s.unescape_nit
699 # assert u.length == 1
700 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
701 fun unescape_nit: String
702 do
703 var res = new Buffer.with_cap(self.length)
704 var was_slash = false
705 for i in [0..length[ do
706 var c = chars[i]
707 if not was_slash then
708 if c == '\\' then
709 was_slash = true
710 else
711 res.add(c)
712 end
713 continue
714 end
715 was_slash = false
716 if c == 'n' then
717 res.add('\n')
718 else if c == 'r' then
719 res.add('\r')
720 else if c == 't' then
721 res.add('\t')
722 else if c == '0' then
723 res.add('\0')
724 else
725 res.add(c)
726 end
727 end
728 return res.to_s
729 end
730
731 # Returns `self` with all characters escaped with their UTF-16 representation
732 #
733 # assert "Aèあ𐏓".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
734 fun escape_to_utf16: String do
735 var buf = new Buffer
736 for i in chars do buf.append i.escape_to_utf16
737 return buf.to_s
738 end
739
740 # Returns the Unicode char escaped by `self`
741 #
742 # assert "\\u0041".from_utf16_escape == 'A'
743 # assert "\\ud800\\udfd3".from_utf16_escape == '𐏓'
744 # assert "\\u00e8".from_utf16_escape == 'è'
745 # assert "\\u3042".from_utf16_escape == 'あ'
746 fun from_utf16_escape(pos, ln: nullable Int): Char do
747 if pos == null then pos = 0
748 if ln == null then ln = length - pos
749 if ln < 6 then return 0xFFFD.code_point
750 var cp = from_utf16_digit(pos + 2)
751 if cp < 0xD800 then return cp.code_point
752 if cp > 0xDFFF then return cp.code_point
753 if cp > 0xDBFF then return 0xFFFD.code_point
754 if ln == 6 then return 0xFFFD.code_point
755 if ln < 12 then return 0xFFFD.code_point
756 cp <<= 16
757 cp += from_utf16_digit(pos + 8)
758 var cplo = cp & 0xFFFF
759 if cplo < 0xDC00 then return 0xFFFD.code_point
760 if cplo > 0xDFFF then return 0xFFFD.code_point
761 return cp.from_utf16_surr.code_point
762 end
763
764 # Returns a UTF-16 escape value
765 #
766 # var s = "\\ud800\\udfd3"
767 # assert s.from_utf16_digit(2) == 0xD800
768 # assert s.from_utf16_digit(8) == 0xDFD3
769 fun from_utf16_digit(pos: nullable Int): Int do
770 if pos == null then pos = 0
771 return to_hex(pos, 4)
772 end
773
774 # Encode `self` to percent (or URL) encoding
775 #
776 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
777 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
778 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
779 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
780 fun to_percent_encoding: String
781 do
782 var buf = new Buffer
783
784 for i in [0..length[ do
785 var c = chars[i]
786 if (c >= '0' and c <= '9') or
787 (c >= 'a' and c <= 'z') or
788 (c >= 'A' and c <= 'Z') or
789 c == '-' or c == '.' or
790 c == '_' or c == '~'
791 then
792 buf.add c
793 else
794 var bytes = c.to_s.bytes
795 for b in bytes do buf.append "%{b.to_i.to_hex}"
796 end
797 end
798
799 return buf.to_s
800 end
801
802 # Decode `self` from percent (or URL) encoding to a clear string
803 #
804 # Replace invalid use of '%' with '?'.
805 #
806 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
807 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
808 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
809 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
810 # assert "incomplete %".from_percent_encoding == "incomplete ?"
811 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
812 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
813 fun from_percent_encoding: String
814 do
815 var len = bytelen
816 var has_percent = false
817 for c in chars do
818 if c == '%' then
819 len -= 2
820 has_percent = true
821 end
822 end
823
824 # If no transformation is needed, return self as a string
825 if not has_percent then return to_s
826
827 var buf = new NativeString(len)
828 var i = 0
829 var l = 0
830 while i < length do
831 var c = chars[i]
832 if c == '%' then
833 if i + 2 >= length then
834 # What follows % has been cut off
835 buf[l] = '?'.ascii
836 else
837 i += 1
838 var hex_s = substring(i, 2)
839 if hex_s.is_hex then
840 var hex_i = hex_s.to_hex
841 buf[l] = hex_i.to_b
842 i += 1
843 else
844 # What follows a % is not Hex
845 buf[l] = '?'.ascii
846 i -= 1
847 end
848 end
849 else buf[l] = c.ascii
850
851 i += 1
852 l += 1
853 end
854
855 return buf.to_s_unsafe(l)
856 end
857
858 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
859 #
860 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
861 #
862 # SEE: <https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content>
863 fun html_escape: String
864 do
865 var buf = new Buffer
866
867 for i in [0..length[ do
868 var c = chars[i]
869 if c == '&' then
870 buf.append "&amp;"
871 else if c == '<' then
872 buf.append "&lt;"
873 else if c == '>' then
874 buf.append "&gt;"
875 else if c == '"' then
876 buf.append "&#34;"
877 else if c == '\'' then
878 buf.append "&#39;"
879 else if c == '/' then
880 buf.append "&#47;"
881 else buf.add c
882 end
883
884 return buf.to_s
885 end
886
887 # Equality of text
888 # Two pieces of text are equals if thez have the same characters in the same order.
889 #
890 # assert "hello" == "hello"
891 # assert "hello" != "HELLO"
892 # assert "hello" == "hel"+"lo"
893 #
894 # Things that are not Text are not equal.
895 #
896 # assert "9" != '9'
897 # assert "9" != ['9']
898 # assert "9" != 9
899 #
900 # assert "9".chars.first == '9' # equality of Char
901 # assert "9".chars == ['9'] # equality of Sequence
902 # assert "9".to_i == 9 # equality of Int
903 redef fun ==(o)
904 do
905 if o == null then return false
906 if not o isa Text then return false
907 if self.is_same_instance(o) then return true
908 if self.length != o.length then return false
909 return self.chars == o.chars
910 end
911
912 # Lexicographical comparaison
913 #
914 # assert "abc" < "xy"
915 # assert "ABC" < "abc"
916 redef fun <(other)
917 do
918 var self_chars = self.chars.iterator
919 var other_chars = other.chars.iterator
920
921 while self_chars.is_ok and other_chars.is_ok do
922 if self_chars.item < other_chars.item then return true
923 if self_chars.item > other_chars.item then return false
924 self_chars.next
925 other_chars.next
926 end
927
928 if self_chars.is_ok then
929 return false
930 else
931 return true
932 end
933 end
934
935 # Escape string used in labels for graphviz
936 #
937 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
938 fun escape_to_dot: String
939 do
940 return escape_more_to_c("|\{\}<>")
941 end
942
943 private var hash_cache: nullable Int = null
944
945 redef fun hash
946 do
947 if hash_cache == null then
948 # djb2 hash algorithm
949 var h = 5381
950
951 for i in [0..length[ do
952 var char = chars[i]
953 h = (h << 5) + h + char.code_point
954 end
955
956 hash_cache = h
957 end
958 return hash_cache.as(not null)
959 end
960
961 # Gives the formatted string back as a Nit string with `args` in place
962 #
963 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
964 # assert "\\%1 This string".format("String") == "\\%1 This string"
965 fun format(args: Object...): String do
966 var s = new Array[Text]
967 var curr_st = 0
968 var i = 0
969 while i < length do
970 # Skip escaped characters
971 if self[i] == '\\' then
972 i += 1
973 # In case of format
974 else if self[i] == '%' then
975 var fmt_st = i
976 i += 1
977 var ciph_st = i
978 while i < length and self[i].is_numeric do
979 i += 1
980 end
981 i -= 1
982 var fmt_end = i
983 var ciph_len = fmt_end - ciph_st + 1
984
985 var arg_index = substring(ciph_st, ciph_len).to_i - 1
986 if arg_index >= args.length then continue
987
988 s.push substring(curr_st, fmt_st - curr_st)
989 s.push args[arg_index].to_s
990 curr_st = i + 1
991 end
992 i += 1
993 end
994 s.push substring(curr_st, length - curr_st)
995 return s.plain_to_s
996 end
997
998 # Return the Levenshtein distance between two strings
999 #
1000 # ~~~
1001 # assert "abcd".levenshtein_distance("abcd") == 0
1002 # assert "".levenshtein_distance("abcd") == 4
1003 # assert "abcd".levenshtein_distance("") == 4
1004 # assert "abcd".levenshtein_distance("xyz") == 4
1005 # assert "abcd".levenshtein_distance("xbdy") == 3
1006 # ~~~
1007 fun levenshtein_distance(other: String): Int
1008 do
1009 var slen = self.length
1010 var olen = other.length
1011
1012 # fast cases
1013 if slen == 0 then return olen
1014 if olen == 0 then return slen
1015 if self == other then return 0
1016
1017 # previous row of distances
1018 var v0 = new Array[Int].with_capacity(olen+1)
1019
1020 # current row of distances
1021 var v1 = new Array[Int].with_capacity(olen+1)
1022
1023 for j in [0..olen] do
1024 # prefix insert cost
1025 v0[j] = j
1026 end
1027
1028 for i in [0..slen[ do
1029
1030 # prefix delete cost
1031 v1[0] = i + 1
1032
1033 for j in [0..olen[ do
1034 # delete cost
1035 var cost1 = v1[j] + 1
1036 # insert cost
1037 var cost2 = v0[j + 1] + 1
1038 # same char cost (+0)
1039 var cost3 = v0[j]
1040 # change cost
1041 if self[i] != other[j] then cost3 += 1
1042 # keep the min
1043 v1[j+1] = cost1.min(cost2).min(cost3)
1044 end
1045
1046 # Switch columns:
1047 # * v1 become v0 in the next iteration
1048 # * old v0 is reused as the new v1
1049 var tmp = v1
1050 v1 = v0
1051 v0 = tmp
1052 end
1053
1054 return v0[olen]
1055 end
1056
1057 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1058 #
1059 # Basically a high-level synonym of NativeString::copy_to
1060 #
1061 # REQUIRE: `n` must be large enough to contain `len` bytes
1062 #
1063 # var ns = new NativeString(8)
1064 # "Text is String".copy_to_native(ns, 8, 2, 0)
1065 # assert ns.to_s_unsafe(8) == "xt is St"
1066 #
1067 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
1068 var mypos = src_offset
1069 var itspos = dest_offset
1070 while n > 0 do
1071 dest[itspos] = self.bytes[mypos]
1072 itspos += 1
1073 mypos += 1
1074 n -= 1
1075 end
1076 end
1077
1078 end
1079
1080 # All kinds of array-based text representations.
1081 abstract class FlatText
1082 super Text
1083
1084 # Underlying C-String (`char*`)
1085 #
1086 # Warning : Might be void in some subclasses, be sure to check
1087 # if set before using it.
1088 var items: NativeString is noinit
1089
1090 # Returns a char* starting at position `first_byte`
1091 #
1092 # WARNING: If you choose to use this service, be careful of the following.
1093 #
1094 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
1095 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1096 # deallocated at any moment, rendering the pointer returned by this function invalid.
1097 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1098 # (Failure to do so will most certainly result in long and painful debugging hours)
1099 #
1100 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1101 # then immediately return).
1102 #
1103 # As always, do not modify the content of the String in C code, if this is what you want
1104 # copy locally the char* as Nit Strings are immutable.
1105 fun fast_cstring: NativeString is abstract
1106
1107 redef var length = 0
1108
1109 redef var bytelen = 0
1110
1111 redef fun output
1112 do
1113 var i = 0
1114 while i < length do
1115 items[i].output
1116 i += 1
1117 end
1118 end
1119
1120 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1121 items.copy_to(dest, n, src_offset, dest_offset)
1122 end
1123 end
1124
1125 # Abstract class for the SequenceRead compatible
1126 # views on the chars of any Text
1127 private abstract class StringCharView
1128 super SequenceRead[Char]
1129
1130 type SELFTYPE: Text
1131
1132 var target: SELFTYPE
1133
1134 redef fun is_empty do return target.is_empty
1135
1136 redef fun length do return target.length
1137
1138 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1139
1140 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1141 end
1142
1143 # Abstract class for the SequenceRead compatible
1144 # views on the bytes of any Text
1145 private abstract class StringByteView
1146 super SequenceRead[Byte]
1147
1148 type SELFTYPE: Text
1149
1150 var target: SELFTYPE
1151
1152 redef fun is_empty do return target.is_empty
1153
1154 redef fun length do return target.bytelen
1155
1156 redef fun iterator do return self.iterator_from(0)
1157
1158 redef fun reverse_iterator do return self.reverse_iterator_from(target.bytelen - 1)
1159 end
1160
1161 # Immutable sequence of characters.
1162 #
1163 # String objects may be created using literals.
1164 #
1165 # assert "Hello World!" isa String
1166 abstract class String
1167 super Text
1168
1169 redef type SELFTYPE: String is fixed
1170
1171 redef fun to_s do return self
1172
1173 # Concatenates `o` to `self`
1174 #
1175 # assert "hello" + "world" == "helloworld"
1176 # assert "" + "hello" + "" == "hello"
1177 fun +(o: Text): SELFTYPE is abstract
1178
1179 # Concatenates self `i` times
1180 #
1181 # assert "abc" * 4 == "abcabcabcabc"
1182 # assert "abc" * 1 == "abc"
1183 # assert "abc" * 0 == ""
1184 fun *(i: Int): SELFTYPE is abstract
1185
1186 # Insert `s` at `pos`.
1187 #
1188 # assert "helloworld".insert_at(" ", 5) == "hello world"
1189 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1190
1191 redef fun substrings is abstract
1192
1193 # Returns a reversed version of self
1194 #
1195 # assert "hello".reversed == "olleh"
1196 # assert "bob".reversed == "bob"
1197 # assert "".reversed == ""
1198 fun reversed: SELFTYPE is abstract
1199
1200 # A upper case version of `self`
1201 #
1202 # assert "Hello World!".to_upper == "HELLO WORLD!"
1203 fun to_upper: SELFTYPE is abstract
1204
1205 # A lower case version of `self`
1206 #
1207 # assert "Hello World!".to_lower == "hello world!"
1208 fun to_lower : SELFTYPE is abstract
1209
1210 # Takes a camel case `self` and converts it to snake case
1211 #
1212 # assert "randomMethodId".to_snake_case == "random_method_id"
1213 #
1214 # The rules are the following:
1215 #
1216 # An uppercase is always converted to a lowercase
1217 #
1218 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1219 #
1220 # An uppercase that follows a lowercase is prefixed with an underscore
1221 #
1222 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1223 #
1224 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1225 #
1226 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1227 #
1228 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1229 #
1230 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1231 fun to_snake_case: SELFTYPE
1232 do
1233 if self.is_lower then return self
1234
1235 var new_str = new Buffer.with_cap(self.length)
1236 var prev_is_lower = false
1237 var prev_is_upper = false
1238
1239 for i in [0..length[ do
1240 var char = chars[i]
1241 if char.is_lower then
1242 new_str.add(char)
1243 prev_is_lower = true
1244 prev_is_upper = false
1245 else if char.is_upper then
1246 if prev_is_lower then
1247 new_str.add('_')
1248 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1249 new_str.add('_')
1250 end
1251 new_str.add(char.to_lower)
1252 prev_is_lower = false
1253 prev_is_upper = true
1254 else
1255 new_str.add(char)
1256 prev_is_lower = false
1257 prev_is_upper = false
1258 end
1259 end
1260
1261 return new_str.to_s
1262 end
1263
1264 # Takes a snake case `self` and converts it to camel case
1265 #
1266 # assert "random_method_id".to_camel_case == "randomMethodId"
1267 #
1268 # If the identifier is prefixed by an underscore, the underscore is ignored
1269 #
1270 # assert "_private_field".to_camel_case == "_privateField"
1271 #
1272 # If `self` is upper, it is returned unchanged
1273 #
1274 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1275 #
1276 # If there are several consecutive underscores, they are considered as a single one
1277 #
1278 # assert "random__method_id".to_camel_case == "randomMethodId"
1279 fun to_camel_case: SELFTYPE
1280 do
1281 if self.is_upper then return self
1282
1283 var new_str = new Buffer
1284 var is_first_char = true
1285 var follows_us = false
1286
1287 for i in [0..length[ do
1288 var char = chars[i]
1289 if is_first_char then
1290 new_str.add(char)
1291 is_first_char = false
1292 else if char == '_' then
1293 follows_us = true
1294 else if follows_us then
1295 new_str.add(char.to_upper)
1296 follows_us = false
1297 else
1298 new_str.add(char)
1299 end
1300 end
1301
1302 return new_str.to_s
1303 end
1304
1305 # Returns a capitalized `self`
1306 #
1307 # Letters that follow a letter are lowercased
1308 # Letters that follow a non-letter are upcased.
1309 #
1310 # SEE : `Char::is_letter` for the definition of letter.
1311 #
1312 # assert "jAVASCRIPT".capitalized == "Javascript"
1313 # assert "i am root".capitalized == "I Am Root"
1314 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1315 fun capitalized: SELFTYPE do
1316 if length == 0 then return self
1317
1318 var buf = new Buffer.with_cap(length)
1319
1320 var curr = chars[0].to_upper
1321 var prev = curr
1322 buf[0] = curr
1323
1324 for i in [1 .. length[ do
1325 prev = curr
1326 curr = self[i]
1327 if prev.is_letter then
1328 buf[i] = curr.to_lower
1329 else
1330 buf[i] = curr.to_upper
1331 end
1332 end
1333
1334 return buf.to_s
1335 end
1336 end
1337
1338 # A mutable sequence of characters.
1339 abstract class Buffer
1340 super Text
1341
1342 # Returns an arbitrary subclass of `Buffer` with default parameters
1343 new is abstract
1344
1345 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1346 new with_cap(i: Int) is abstract
1347
1348 redef type SELFTYPE: Buffer is fixed
1349
1350 # Specific implementations MUST set this to `true` in order to invalidate caches
1351 protected var is_dirty = true
1352
1353 # Copy-On-Write flag
1354 #
1355 # If the `Buffer` was to_s'd, the next in-place altering
1356 # operation will cause the current `Buffer` to be re-allocated.
1357 #
1358 # The flag will then be set at `false`.
1359 protected var written = false
1360
1361 # Modifies the char contained at pos `index`
1362 #
1363 # DEPRECATED : Use self.chars.[]= instead
1364 fun []=(index: Int, item: Char) is abstract
1365
1366 # Adds a char `c` at the end of self
1367 #
1368 # DEPRECATED : Use self.chars.add instead
1369 fun add(c: Char) is abstract
1370
1371 # Clears the buffer
1372 #
1373 # var b = new Buffer
1374 # b.append "hello"
1375 # assert not b.is_empty
1376 # b.clear
1377 # assert b.is_empty
1378 fun clear is abstract
1379
1380 # Enlarges the subsequent array containing the chars of self
1381 fun enlarge(cap: Int) is abstract
1382
1383 # Adds the content of text `s` at the end of self
1384 #
1385 # var b = new Buffer
1386 # b.append "hello"
1387 # b.append "world"
1388 # assert b == "helloworld"
1389 fun append(s: Text) is abstract
1390
1391 # `self` is appended in such a way that `self` is repeated `r` times
1392 #
1393 # var b = new Buffer
1394 # b.append "hello"
1395 # b.times 3
1396 # assert b == "hellohellohello"
1397 fun times(r: Int) is abstract
1398
1399 # Reverses itself in-place
1400 #
1401 # var b = new Buffer
1402 # b.append("hello")
1403 # b.reverse
1404 # assert b == "olleh"
1405 fun reverse is abstract
1406
1407 # Changes each lower-case char in `self` by its upper-case variant
1408 #
1409 # var b = new Buffer
1410 # b.append("Hello World!")
1411 # b.upper
1412 # assert b == "HELLO WORLD!"
1413 fun upper is abstract
1414
1415 # Changes each upper-case char in `self` by its lower-case variant
1416 #
1417 # var b = new Buffer
1418 # b.append("Hello World!")
1419 # b.lower
1420 # assert b == "hello world!"
1421 fun lower is abstract
1422
1423 # Capitalizes each word in `self`
1424 #
1425 # Letters that follow a letter are lowercased
1426 # Letters that follow a non-letter are upcased.
1427 #
1428 # SEE: `Char::is_letter` for the definition of a letter.
1429 #
1430 # var b = new FlatBuffer.from("jAVAsCriPt")
1431 # b.capitalize
1432 # assert b == "Javascript"
1433 # b = new FlatBuffer.from("i am root")
1434 # b.capitalize
1435 # assert b == "I Am Root"
1436 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1437 # b.capitalize
1438 # assert b == "Ab_C -Ab0C Ab\nC"
1439 fun capitalize do
1440 if length == 0 then return
1441 var c = self[0].to_upper
1442 self[0] = c
1443 var prev = c
1444 for i in [1 .. length[ do
1445 prev = c
1446 c = self[i]
1447 if prev.is_letter then
1448 self[i] = c.to_lower
1449 else
1450 self[i] = c.to_upper
1451 end
1452 end
1453 end
1454
1455 redef fun hash
1456 do
1457 if is_dirty then hash_cache = null
1458 return super
1459 end
1460
1461 # In Buffers, the internal sequence of character is mutable
1462 # Thus, `chars` can be used to modify the buffer.
1463 redef fun chars: Sequence[Char] is abstract
1464 end
1465
1466 # View for chars on Buffer objects, extends Sequence
1467 # for mutation operations
1468 private abstract class BufferCharView
1469 super StringCharView
1470 super Sequence[Char]
1471
1472 redef type SELFTYPE: Buffer
1473
1474 end
1475
1476 # View for bytes on Buffer objects, extends Sequence
1477 # for mutation operations
1478 private abstract class BufferByteView
1479 super StringByteView
1480
1481 redef type SELFTYPE: Buffer
1482 end
1483
1484 redef class Object
1485 # User readable representation of `self`.
1486 fun to_s: String do return inspect
1487
1488 # The class name of the object in NativeString format.
1489 private fun native_class_name: NativeString is intern
1490
1491 # The class name of the object.
1492 #
1493 # assert 5.class_name == "Int"
1494 fun class_name: String do return native_class_name.to_s
1495
1496 # Developer readable representation of `self`.
1497 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1498 fun inspect: String
1499 do
1500 return "<{inspect_head}>"
1501 end
1502
1503 # Return "CLASSNAME:#OBJECTID".
1504 # This function is mainly used with the redefinition of the inspect method
1505 protected fun inspect_head: String
1506 do
1507 return "{class_name}:#{object_id.to_hex}"
1508 end
1509 end
1510
1511 redef class Bool
1512 # assert true.to_s == "true"
1513 # assert false.to_s == "false"
1514 redef fun to_s
1515 do
1516 if self then
1517 return once "true"
1518 else
1519 return once "false"
1520 end
1521 end
1522 end
1523
1524 redef class Byte
1525 # C function to calculate the length of the `NativeString` to receive `self`
1526 private fun byte_to_s_len: Int `{
1527 return snprintf(NULL, 0, "0x%02x", self);
1528 `}
1529
1530 # C function to convert an nit Int to a NativeString (char*)
1531 private fun native_byte_to_s(nstr: NativeString, strlen: Int) `{
1532 snprintf(nstr, strlen, "0x%02x", self);
1533 `}
1534
1535 # Displayable byte in its hexadecimal form (0x..)
1536 #
1537 # assert 1.to_b.to_s == "0x01"
1538 # assert (-123).to_b.to_s == "0x85"
1539 redef fun to_s do
1540 var nslen = byte_to_s_len
1541 var ns = new NativeString(nslen + 1)
1542 ns[nslen] = 0u8
1543 native_byte_to_s(ns, nslen + 1)
1544 return ns.to_s_unsafe(nslen)
1545 end
1546 end
1547
1548 redef class Int
1549
1550 # Wrapper of strerror C function
1551 private fun strerror_ext: NativeString `{ return strerror(self); `}
1552
1553 # Returns a string describing error number
1554 fun strerror: String do return strerror_ext.to_s
1555
1556 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1557 # assume < to_c max const of char
1558 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1559 do
1560 var n: Int
1561 # Sign
1562 if self < 0 then
1563 n = - self
1564 s.chars[0] = '-'
1565 else if self == 0 then
1566 s.chars[0] = '0'
1567 return
1568 else
1569 n = self
1570 end
1571 # Fill digits
1572 var pos = digit_count(base) - 1
1573 while pos >= 0 and n > 0 do
1574 s.chars[pos] = (n % base).to_c
1575 n = n / base # /
1576 pos -= 1
1577 end
1578 end
1579
1580 # C function to calculate the length of the `NativeString` to receive `self`
1581 private fun int_to_s_len: Int `{
1582 return snprintf(NULL, 0, "%ld", self);
1583 `}
1584
1585 # C function to convert an nit Int to a NativeString (char*)
1586 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1587 snprintf(nstr, strlen, "%ld", self);
1588 `}
1589
1590 # return displayable int in base base and signed
1591 fun to_base(base: Int, signed: Bool): String is abstract
1592
1593 # return displayable int in hexadecimal
1594 #
1595 # assert 1.to_hex == "1"
1596 # assert (-255).to_hex == "-ff"
1597 fun to_hex: String do return to_base(16,false)
1598 end
1599
1600 redef class Float
1601 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1602 #
1603 # assert 12.34.to_s == "12.34"
1604 # assert (-0120.030).to_s == "-120.03"
1605 #
1606 # see `to_precision` for a custom precision.
1607 redef fun to_s do
1608 var str = to_precision( 3 )
1609 if is_inf != 0 or is_nan then return str
1610 var len = str.length
1611 for i in [0..len-1] do
1612 var j = len-1-i
1613 var c = str.chars[j]
1614 if c == '0' then
1615 continue
1616 else if c == '.' then
1617 return str.substring( 0, j+2 )
1618 else
1619 return str.substring( 0, j+1 )
1620 end
1621 end
1622 return str
1623 end
1624
1625 # `String` representation of `self` with the given number of `decimals`
1626 #
1627 # assert 12.345.to_precision(0) == "12"
1628 # assert 12.345.to_precision(3) == "12.345"
1629 # assert (-12.345).to_precision(3) == "-12.345"
1630 # assert (-0.123).to_precision(3) == "-0.123"
1631 # assert 0.999.to_precision(2) == "1.00"
1632 # assert 0.999.to_precision(4) == "0.9990"
1633 fun to_precision(decimals: Int): String
1634 do
1635 if is_nan then return "nan"
1636
1637 var isinf = self.is_inf
1638 if isinf == 1 then
1639 return "inf"
1640 else if isinf == -1 then
1641 return "-inf"
1642 end
1643
1644 if decimals == 0 then return self.to_i.to_s
1645 var f = self
1646 for i in [0..decimals[ do f = f * 10.0
1647 if self > 0.0 then
1648 f = f + 0.5
1649 else
1650 f = f - 0.5
1651 end
1652 var i = f.to_i
1653 if i == 0 then return "0." + "0"*decimals
1654
1655 # Prepare both parts of the float, before and after the "."
1656 var s = i.abs.to_s
1657 var sl = s.length
1658 var p1
1659 var p2
1660 if sl > decimals then
1661 # Has something before the "."
1662 p1 = s.substring(0, sl-decimals)
1663 p2 = s.substring(sl-decimals, decimals)
1664 else
1665 p1 = "0"
1666 p2 = "0"*(decimals-sl) + s
1667 end
1668
1669 if i < 0 then p1 = "-" + p1
1670
1671 return p1 + "." + p2
1672 end
1673 end
1674
1675 redef class Char
1676
1677 # Returns a sequence with the UTF-8 bytes of `self`
1678 #
1679 # assert 'a'.bytes == [0x61u8]
1680 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1681 fun bytes: SequenceRead[Byte] do return to_s.bytes
1682
1683 # Is `self` an UTF-16 surrogate pair ?
1684 fun is_surrogate: Bool do
1685 var cp = code_point
1686 return cp >= 0xD800 and cp <= 0xDFFF
1687 end
1688
1689 # Length of `self` in a UTF-8 String
1690 private fun u8char_len: Int do
1691 var c = self.code_point
1692 if c < 0x80 then return 1
1693 if c <= 0x7FF then return 2
1694 if c <= 0xFFFF then return 3
1695 if c <= 0x10FFFF then return 4
1696 # Bad character format
1697 return 1
1698 end
1699
1700 # assert 'x'.to_s == "x"
1701 redef fun to_s do
1702 var ln = u8char_len
1703 var ns = new NativeString(ln + 1)
1704 u8char_tos(ns, ln)
1705 return ns.to_s_unsafe(ln)
1706 end
1707
1708 # Returns `self` escaped to UTF-16
1709 #
1710 # i.e. Represents `self`.`code_point` using UTF-16 codets escaped
1711 # with a `\u`
1712 #
1713 # assert 'A'.escape_to_utf16 == "\\u0041"
1714 # assert 'è'.escape_to_utf16 == "\\u00e8"
1715 # assert 'あ'.escape_to_utf16 == "\\u3042"
1716 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
1717 fun escape_to_utf16: String do
1718 var cp = code_point
1719 var buf: Buffer
1720 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
1721 buf = new Buffer.with_cap(6)
1722 buf.append("\\u0000")
1723 var hx = cp.to_hex
1724 var outid = 5
1725 for i in hx.chars.reverse_iterator do
1726 buf[outid] = i
1727 outid -= 1
1728 end
1729 else
1730 buf = new Buffer.with_cap(12)
1731 buf.append("\\u0000\\u0000")
1732 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
1733 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
1734 var out = 2
1735 for i in hi do
1736 buf[out] = i
1737 out += 1
1738 end
1739 out = 8
1740 for i in lo do
1741 buf[out] = i
1742 out += 1
1743 end
1744 end
1745 return buf.to_s
1746 end
1747
1748 private fun u8char_tos(r: NativeString, len: Int) `{
1749 r[len] = '\0';
1750 switch(len){
1751 case 1:
1752 r[0] = self;
1753 break;
1754 case 2:
1755 r[0] = 0xC0 | ((self & 0x7C0) >> 6);
1756 r[1] = 0x80 | (self & 0x3F);
1757 break;
1758 case 3:
1759 r[0] = 0xE0 | ((self & 0xF000) >> 12);
1760 r[1] = 0x80 | ((self & 0xFC0) >> 6);
1761 r[2] = 0x80 | (self & 0x3F);
1762 break;
1763 case 4:
1764 r[0] = 0xF0 | ((self & 0x1C0000) >> 18);
1765 r[1] = 0x80 | ((self & 0x3F000) >> 12);
1766 r[2] = 0x80 | ((self & 0xFC0) >> 6);
1767 r[3] = 0x80 | (self & 0x3F);
1768 break;
1769 }
1770 `}
1771
1772 # Returns true if the char is a numerical digit
1773 #
1774 # assert '0'.is_numeric
1775 # assert '9'.is_numeric
1776 # assert not 'a'.is_numeric
1777 # assert not '?'.is_numeric
1778 #
1779 # FIXME: Works on ASCII-range only
1780 fun is_numeric: Bool
1781 do
1782 return self >= '0' and self <= '9'
1783 end
1784
1785 # Returns true if the char is an alpha digit
1786 #
1787 # assert 'a'.is_alpha
1788 # assert 'Z'.is_alpha
1789 # assert not '0'.is_alpha
1790 # assert not '?'.is_alpha
1791 #
1792 # FIXME: Works on ASCII-range only
1793 fun is_alpha: Bool
1794 do
1795 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1796 end
1797
1798 # Is `self` an hexadecimal digit ?
1799 #
1800 # assert 'A'.is_hexdigit
1801 # assert not 'G'.is_hexdigit
1802 # assert 'a'.is_hexdigit
1803 # assert not 'g'.is_hexdigit
1804 # assert '5'.is_hexdigit
1805 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
1806 (self >= 'a' and self <= 'f')
1807
1808 # Returns true if the char is an alpha or a numeric digit
1809 #
1810 # assert 'a'.is_alphanumeric
1811 # assert 'Z'.is_alphanumeric
1812 # assert '0'.is_alphanumeric
1813 # assert '9'.is_alphanumeric
1814 # assert not '?'.is_alphanumeric
1815 #
1816 # FIXME: Works on ASCII-range only
1817 fun is_alphanumeric: Bool
1818 do
1819 return self.is_numeric or self.is_alpha
1820 end
1821
1822 # Returns `self` to its int value
1823 #
1824 # REQUIRE: `is_hexdigit`
1825 fun from_hex: Int do
1826 if self >= '0' and self <= '9' then return code_point - 0x30
1827 if self >= 'A' and self <= 'F' then return code_point - 0x37
1828 if self >= 'a' and self <= 'f' then return code_point - 0x57
1829 # Happens if self is not a hexdigit
1830 assert self.is_hexdigit
1831 # To make flow analysis happy
1832 abort
1833 end
1834 end
1835
1836 redef class Collection[E]
1837 # String representation of the content of the collection.
1838 #
1839 # The standard representation is the list of elements separated with commas.
1840 #
1841 # ~~~
1842 # assert [1,2,3].to_s == "[1,2,3]"
1843 # assert [1..3].to_s == "[1,2,3]"
1844 # assert (new Array[Int]).to_s == "[]" # empty collection
1845 # ~~~
1846 #
1847 # Subclasses may return a more specific string representation.
1848 redef fun to_s
1849 do
1850 return "[" + join(",") + "]"
1851 end
1852
1853 # Concatenate elements without separators
1854 #
1855 # ~~~
1856 # assert [1,2,3].plain_to_s == "123"
1857 # assert [11..13].plain_to_s == "111213"
1858 # assert (new Array[Int]).plain_to_s == "" # empty collection
1859 # ~~~
1860 fun plain_to_s: String
1861 do
1862 var s = new Buffer
1863 for e in self do if e != null then s.append(e.to_s)
1864 return s.to_s
1865 end
1866
1867 # Concatenate and separate each elements with `separator`.
1868 #
1869 # Only concatenate if `separator == null`.
1870 #
1871 # assert [1, 2, 3].join(":") == "1:2:3"
1872 # assert [1..3].join(":") == "1:2:3"
1873 # assert [1..3].join == "123"
1874 fun join(separator: nullable Text): String
1875 do
1876 if is_empty then return ""
1877
1878 var s = new Buffer # Result
1879
1880 # Concat first item
1881 var i = iterator
1882 var e = i.item
1883 if e != null then s.append(e.to_s)
1884
1885 # Concat other items
1886 i.next
1887 while i.is_ok do
1888 if separator != null then s.append(separator)
1889 e = i.item
1890 if e != null then s.append(e.to_s)
1891 i.next
1892 end
1893 return s.to_s
1894 end
1895 end
1896
1897 redef class Map[K,V]
1898 # Concatenate couples of key value.
1899 # Key and value are separated by `couple_sep`.
1900 # Couples are separated by `sep`.
1901 #
1902 # var m = new HashMap[Int, String]
1903 # m[1] = "one"
1904 # m[10] = "ten"
1905 # assert m.join("; ", "=") == "1=one; 10=ten"
1906 fun join(sep, couple_sep: String): String is abstract
1907 end
1908
1909 redef class Sys
1910 private var args_cache: nullable Sequence[String] = null
1911
1912 # The arguments of the program as given by the OS
1913 fun program_args: Sequence[String]
1914 do
1915 if _args_cache == null then init_args
1916 return _args_cache.as(not null)
1917 end
1918
1919 # The name of the program as given by the OS
1920 fun program_name: String
1921 do
1922 return native_argv(0).to_s
1923 end
1924
1925 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1926 private fun init_args
1927 do
1928 var argc = native_argc
1929 var args = new Array[String].with_capacity(0)
1930 var i = 1
1931 while i < argc do
1932 args[i-1] = native_argv(i).to_s
1933 i += 1
1934 end
1935 _args_cache = args
1936 end
1937
1938 # First argument of the main C function.
1939 private fun native_argc: Int is intern
1940
1941 # Second argument of the main C function.
1942 private fun native_argv(i: Int): NativeString is intern
1943 end
1944
1945 # Comparator that efficienlty use `to_s` to compare things
1946 #
1947 # The comparaison call `to_s` on object and use the result to order things.
1948 #
1949 # var a = [1, 2, 3, 10, 20]
1950 # (new CachedAlphaComparator).sort(a)
1951 # assert a == [1, 10, 2, 20, 3]
1952 #
1953 # Internally the result of `to_s` is cached in a HashMap to counter
1954 # uneficient implementation of `to_s`.
1955 #
1956 # Note: it caching is not usefull, see `alpha_comparator`
1957 class CachedAlphaComparator
1958 super Comparator
1959 redef type COMPARED: Object
1960
1961 private var cache = new HashMap[Object, String]
1962
1963 private fun do_to_s(a: Object): String do
1964 if cache.has_key(a) then return cache[a]
1965 var res = a.to_s
1966 cache[a] = res
1967 return res
1968 end
1969
1970 redef fun compare(a, b) do
1971 return do_to_s(a) <=> do_to_s(b)
1972 end
1973 end
1974
1975 # see `alpha_comparator`
1976 private class AlphaComparator
1977 super Comparator
1978 redef fun compare(a, b) do return a.to_s <=> b.to_s
1979 end
1980
1981 # Stateless comparator that naively use `to_s` to compare things.
1982 #
1983 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1984 # on a single instace. See `CachedAlphaComparator` as an alternative.
1985 #
1986 # var a = [1, 2, 3, 10, 20]
1987 # alpha_comparator.sort(a)
1988 # assert a == [1, 10, 2, 20, 3]
1989 fun alpha_comparator: Comparator do return once new AlphaComparator
1990
1991 # The arguments of the program as given by the OS
1992 fun args: Sequence[String]
1993 do
1994 return sys.program_args
1995 end
1996
1997 redef class NativeString
1998 # Returns `self` as a new String.
1999 fun to_s_with_copy: String is abstract
2000
2001 # Returns `self` as a String of `length`.
2002 fun to_s_with_length(length: Int): String is abstract
2003
2004 # Returns a new instance of `String` with self as `_items`
2005 #
2006 # /!\: Does not clean the items for compliance with UTF-8,
2007 # Use only if you know what you are doing
2008 fun to_s_unsafe(len: nullable Int): String is abstract
2009
2010 # Returns `self` as a String with `bytelen` and `length` set
2011 #
2012 # SEE: `abstract_text::Text` for more infos on the difference
2013 # between `Text::bytelen` and `Text::length`
2014 fun to_s_full(bytelen, unilen: Int): String is abstract
2015 end
2016
2017 redef class NativeArray[E]
2018 # Join all the elements using `to_s`
2019 #
2020 # REQUIRE: `self isa NativeArray[String]`
2021 # REQUIRE: all elements are initialized
2022 fun native_to_s: String is abstract
2023 end