1 # This file is part of NIT ( http://www.nitlanguage.org ).
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
11 # Abstract class for manipulation of sequences of characters
17 intrude import collection
::array
25 # High-level abstraction for all text representations
30 redef type OTHER: Text
32 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
35 # Gets a view on the chars of the Text object
38 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
40 fun chars
: SequenceRead[Char] is abstract
42 # Gets a view on the bytes of the Text object
45 # assert "hello".bytes.to_a == [104, 101, 108, 108, 111]
47 fun bytes
: SequenceRead[Int] is abstract
49 # Number of characters contained in self.
52 # assert "12345".length == 5
53 # assert "".length == 0
54 # assert "あいうえお".length == 5
56 fun length
: Int is abstract
58 # Number of bytes in `self`
61 # assert "12345".byte_length == 5
62 # assert "あいうえお".byte_length == 15
64 fun byte_length
: Int is abstract
69 # assert "abcd".substring(1, 2) == "bc"
70 # assert "abcd".substring(-1, 2) == "a"
71 # assert "abcd".substring(1, 0) == ""
72 # assert "abcd".substring(2, 5) == "cd"
73 # assert "あいうえお".substring(1,3) == "いうえ"
76 # A `from` index < 0 will be replaced by 0.
77 # Unless a `count` value is > 0 at the same time.
78 # In this case, `from += count` and `count -= from`.
79 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
81 # Iterates on the substrings of self if any
82 private fun substrings
: Iterator[FlatText] is abstract
84 # Is the current Text empty (== "")
88 # assert not "foo".is_empty
90 fun is_empty
: Bool do return self.length
== 0
92 # Returns an empty Text of the right type
94 # This method is used internally to get the right
95 # implementation of an empty string.
96 protected fun empty
: SELFTYPE is abstract
98 # Returns a copy of `self` as a Buffer
99 fun to_buffer
: Buffer is abstract
101 # Gets the first char of the Text
102 fun first
: Char do return self.chars
[0]
104 # Access a character at `index` in the string.
107 # assert "abcd"[2] == 'c'
109 fun [](index
: Int): Char do return self.chars
[index
]
111 # Gets the index of the first occurence of 'c'
113 # Returns -1 if not found
114 fun index_of
(c
: Char): Int
116 return index_of_from
(c
, 0)
119 # Gets the last char of self
120 fun last
: Char do return self.chars
[length-1
]
122 # Gets the index of the first occurence of ´c´ starting from ´pos´
124 # Returns -1 if not found
125 fun index_of_from
(c
: Char, pos
: Int): Int
127 var iter
= self.chars
.iterator_from
(pos
)
129 if iter
.item
== c
then return iter
.index
135 # Gets the last index of char ´c´
137 # Returns -1 if not found
138 fun last_index_of
(c
: Char): Int
140 return last_index_of_from
(c
, length
- 1)
143 # Return a null terminated char *
144 fun to_cstring
: CString is abstract
146 # The index of the last occurrence of an element starting from pos (in reverse order).
149 # var s = "/etc/bin/test/test.nit"
150 # assert s.last_index_of_from('/', s.length-1) == 13
151 # assert s.last_index_of_from('/', 12) == 8
154 # Returns -1 if not found
155 fun last_index_of_from
(item
: Char, pos
: Int): Int do return chars
.last_index_of_from
(item
, pos
)
157 # Concatenates `o` to `self`
160 # assert "hello" + "world" == "helloworld"
161 # assert "" + "hello" + "" == "hello"
163 fun +(o
: Text): SELFTYPE is abstract
165 # Gets an iterator on the chars of self
166 fun iterator
: Iterator[Char]
168 return self.chars
.iterator
172 # Gets an Array containing the chars of self
173 fun to_a
: Array[Char] do return chars
.to_a
175 # Create a substring from `self` beginning at the `from` position
178 # assert "abcd".substring_from(1) == "bcd"
179 # assert "abcd".substring_from(-1) == "abcd"
180 # assert "abcd".substring_from(2) == "cd"
183 # As with substring, a `from` index < 0 will be replaced by 0
184 fun substring_from
(from
: Int): SELFTYPE
186 if from
>= self.length
then return empty
187 if from
< 0 then from
= 0
188 return substring
(from
, length
- from
)
191 # Does self have a substring `str` starting from position `pos`?
194 # assert "abcd".has_substring("bc",1) == true
195 # assert "abcd".has_substring("bc",2) == false
198 # Returns true iff all characters of `str` are presents
199 # at the expected index in `self.`
200 # The first character of `str` being at `pos`, the second
201 # character being at `pos+1` and so on...
203 # This means that all characters of `str` need to be inside `self`.
206 # assert "abcd".has_substring("xab", -1) == false
207 # assert "abcd".has_substring("cdx", 2) == false
210 # And that the empty string is always a valid substring.
213 # assert "abcd".has_substring("", 2) == true
214 # assert "abcd".has_substring("", 200) == true
216 fun has_substring
(str
: String, pos
: Int): Bool
218 if str
.is_empty
then return true
219 if pos
< 0 or pos
+ str
.length
> length
then return false
220 var myiter
= self.chars
.iterator_from
(pos
)
221 var itsiter
= str
.chars
.iterator
222 while myiter
.is_ok
and itsiter
.is_ok
do
223 if myiter
.item
!= itsiter
.item
then return false
227 if itsiter
.is_ok
then return false
231 # Is this string prefixed by `prefix`?
234 # assert "abcd".has_prefix("ab") == true
235 # assert "abcbc".has_prefix("bc") == false
236 # assert "ab".has_prefix("abcd") == false
238 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
240 # Is this string suffixed by `suffix`?
243 # assert "abcd".has_suffix("abc") == false
244 # assert "abcd".has_suffix("bcd") == true
246 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
248 # Returns `self` as the corresponding integer
251 # assert "123".to_i == 123
252 # assert "-1".to_i == -1
253 # assert "0x64".to_i == 100
254 # assert "0b1100_0011".to_i== 195
255 # assert "--12".to_i == 12
258 # REQUIRE: `self`.`is_int`
259 fun to_i
: Int is abstract
261 # If `self` contains a float, return the corresponding float
264 # assert "123".to_f == 123.0
265 # assert "-1".to_f == -1.0
266 # assert "-1.2e-3".to_f == -0.0012
271 return to_s
.to_cstring
.atof
274 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
277 # assert "ff".to_hex == 255
279 fun to_hex
(pos
, ln
: nullable Int): Int do
281 if pos
== null then pos
= 0
282 if ln
== null then ln
= length
- pos
284 for i
in [pos
.. max
[ do
286 res
+= self[i
].from_hex
291 # If `self` contains only digits <= '7', return the corresponding integer.
294 # assert "714".to_oct == 460
296 fun to_oct
: Int do return a_to
(8)
298 # If `self` contains only '0' et '1', return the corresponding integer.
301 # assert "101101".to_bin == 45
303 fun to_bin
: Int do return a_to
(2)
305 # If `self` contains only digits '0' .. '9', return the corresponding integer.
308 # assert "108".to_dec == 108
310 fun to_dec
: Int do return a_to
(10)
312 # If `self` contains only digits and letters, return the corresponding integer in a given base
315 # assert "120".a_to(3) == 15
317 fun a_to
(base
: Int) : Int
322 for j
in [0..length
[ do
344 # Is this string in a valid numeric format compatible with `to_f`?
347 # assert "123".is_numeric == true
348 # assert "1.2".is_numeric == true
349 # assert "-1.2".is_numeric == true
350 # assert "-1.23e-2".is_numeric == true
351 # assert "1..2".is_numeric == false
352 # assert "".is_numeric == false
356 var has_point
= false
358 for i
in [0..length
[ do
360 if not c
.is_numeric
then
361 if c
== '.' and not has_point
then
363 else if c
== 'e' and e_index
== -1 and i
> 0 and i
< length
- 1 and chars
[i-1
] != '-' then
365 else if c
== '-' and i
== e_index
+ 1 and i
< length
- 1 then
374 # Returns `true` if the string contains only Hex chars
377 # assert "048bf".is_hex == true
378 # assert "ABCDEF".is_hex == true
379 # assert "0G".is_hex == false
383 for i
in [0..length
[ do
385 if not (c
>= 'a' and c
<= 'f') and
386 not (c
>= 'A' and c
<= 'F') and
387 not (c
>= '0' and c
<= '9') then return false
392 # Returns `true` if the string contains only Binary digits
395 # assert "1101100".is_bin == true
396 # assert "1101020".is_bin == false
399 for i
in chars
do if i
!= '0' and i
!= '1' then return false
403 # Returns `true` if the string contains only Octal digits
406 # assert "213453".is_oct == true
407 # assert "781".is_oct == false
410 for i
in chars
do if i
< '0' or i
> '7' then return false
414 # Returns `true` if the string contains only Decimal digits
417 # assert "10839".is_dec == true
418 # assert "164F".is_dec == false
421 for i
in chars
do if i
< '0' or i
> '9' then return false
425 # Are all letters in `self` upper-case ?
428 # assert "HELLO WORLD".is_upper == true
429 # assert "%$&%!".is_upper == true
430 # assert "hello world".is_upper == false
431 # assert "Hello World".is_upper == false
435 for i
in [0..length
[ do
437 if char
.is_lower
then return false
442 # Are all letters in `self` lower-case ?
445 # assert "hello world".is_lower == true
446 # assert "%$&%!".is_lower == true
447 # assert "Hello World".is_lower == false
451 for i
in [0..length
[ do
453 if char
.is_upper
then return false
458 # Removes the whitespaces at the beginning of self
461 # assert " \n\thello \n\t".l_trim == "hello \n\t"
464 # `Char::is_whitespace` determines what is a whitespace.
467 var iter
= self.chars
.iterator
469 if not iter
.item
.is_whitespace
then break
472 if iter
.index
== length
then return self.empty
473 return self.substring_from
(iter
.index
)
476 # Removes the whitespaces at the end of self
479 # assert " \n\thello \n\t".r_trim == " \n\thello"
482 # `Char::is_whitespace` determines what is a whitespace.
485 var iter
= self.chars
.reverse_iterator
487 if not iter
.item
.is_whitespace
then break
490 if iter
.index
< 0 then return self.empty
491 return self.substring
(0, iter
.index
+ 1)
494 # Trims trailing and preceding white spaces
497 # assert " Hello World ! ".trim == "Hello World !"
498 # assert "\na\nb\tc\t".trim == "a\nb\tc"
501 # `Char::is_whitespace` determines what is a whitespace.
502 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
504 # Is the string non-empty but only made of whitespaces?
507 # assert " \n\t ".is_whitespace == true
508 # assert " hello ".is_whitespace == false
509 # assert "".is_whitespace == false
512 # `Char::is_whitespace` determines what is a whitespace.
513 fun is_whitespace
: Bool
515 if is_empty
then return false
516 for c
in self.chars
do
517 if not c
.is_whitespace
then return false
522 # Returns `self` removed from its last line terminator (if any).
525 # assert "Hello\n".chomp == "Hello"
526 # assert "Hello".chomp == "Hello"
528 # assert "\n".chomp == ""
529 # assert "".chomp == ""
532 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
533 # A single line terminator, the last one, is removed.
536 # assert "\r\n".chomp == ""
537 # assert "\r\n\n".chomp == "\r\n"
538 # assert "\r\n\r\n".chomp == "\r\n"
539 # assert "\r\n\r".chomp == "\r\n"
542 # Note: unlike with most IO methods like `Reader::read_line`,
543 # a single `\r` is considered here to be a line terminator and will be removed.
547 if len
== 0 then return self
548 var l
= self.chars
.last
550 return substring
(0, len-1
)
551 else if l
!= '\n' then
553 else if len
> 1 and self.chars
[len-2
] == '\r' then
554 return substring
(0, len-2
)
556 return substring
(0, len-1
)
560 # Justify `self` in a space of `length`
562 # `left` is the space ratio on the left side.
563 # * 0.0 for left-justified (no space at the left)
564 # * 1.0 for right-justified (all spaces at the left)
565 # * 0.5 for centered (half the spaces at the left)
567 # `char`, or `' '` by default, is repeated to pad the empty space.
572 # assert "hello".justify(10, 0.0) == "hello "
573 # assert "hello".justify(10, 1.0) == " hello"
574 # assert "hello".justify(10, 0.5) == " hello "
575 # assert "hello".justify(10, 0.5, '.') == "..hello..."
578 # If `length` is not enough, `self` is returned as is.
581 # assert "hello".justify(2, 0.0) == "hello"
584 # REQUIRE: `left >= 0.0 and left <= 1.0`
585 # ENSURE: `self.length <= length implies result.length == length`
586 # ENSURE: `self.length >= length implies result == self`
587 fun justify
(length
: Int, left
: Float, char
: nullable Char): String
589 var pad
= (char
or else ' ').to_s
590 var diff
= length
- self.length
591 if diff
<= 0 then return to_s
592 assert left
>= 0.0 and left
<= 1.0
593 var before
= (diff
.to_f
* left
).to_i
594 return pad
* before
+ self + pad
* (diff-before
)
597 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
599 # This method is injective (two different inputs never produce the same
600 # output) and the returned string always respect the following rules:
602 # * Contains only US-ASCII letters, digits and underscores.
603 # * Never starts with a digit.
604 # * Never ends with an underscore.
605 # * Never contains two contiguous underscores.
610 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
611 # assert "__".to_cmangle == "_95d_95d"
612 # assert "__d".to_cmangle == "_95d_d"
613 # assert "_d_".to_cmangle == "_d_95d"
614 # assert "_42".to_cmangle == "_95d42"
615 # assert "foo".to_cmangle == "foo"
616 # assert "".to_cmangle == ""
618 fun to_cmangle
: String
620 if is_empty
then return ""
622 var underscore
= false
626 if c
>= '0' and c
<= '9' then
628 res
.append
(c
.code_point
.to_s
)
632 for i
in [start
..length
[ do
634 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
640 res
.append
('_'.code_point
.to_s
)
643 if c
>= '0' and c
<= '9' then
646 else if c
== '_' then
651 res
.append
(c
.code_point
.to_s
)
657 res
.append
('_'.code_point
.to_s
)
663 # Escape `"` `\` `'`, trigraphs and non printable characters using the rules of literal C strings and characters
666 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
667 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
668 # assert "allo???!".escape_to_c == "allo??\\?!"
669 # assert "??=??/??'??(??)".escape_to_c == "?\\?=?\\?/??\\'?\\?(?\\?)"
670 # assert "??!??<??>??-".escape_to_c == "?\\?!?\\?<?\\?>?\\?-"
673 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
674 # Three digits are always used to avoid following digits to be interpreted as an element
675 # of the octal sequence.
678 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
681 # The exceptions are the common `\t` and `\n`.
682 fun escape_to_c
: String
685 for i
in [0..length
[ do
689 else if c
== '\t' then
691 else if c
== '"' then
693 else if c == '\'' then
695 else if c == '\\
' then
697 else if c == '?' then
698 # Escape if it is the last question mark of a ANSI C trigraph.
702 # We ignore `??'` because it will be escaped as `??\
'`.
715 else if c.code_point < 32 then
717 var oct = c.code_point.to_base(8)
718 # Force 3 octal digits since it is the
719 # maximum allowed in the C specification
720 if oct.length == 1 then
723 else if oct.length == 2 then
734 # Escape additionnal characters
735 # The result might no be legal in C but be used in other languages
738 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
739 # assert "allo???!".escape_more_to_c("") == "allo??\\?!"
741 fun escape_more_to_c(chars: String): String
744 for c in escape_to_c.chars do
745 if chars.chars.has(c) then
753 # Escape to C plus braces
756 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
758 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
760 # Escape to POSIX Shell (sh).
762 # Abort if the text contains a null byte.
765 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
767 fun escape_to_sh
: String do
770 for i in [0..length[ do
775 assert without_null_byte
: c
!= '\0'
783 # Escape to include in a Makefile
785 # Unfortunately, some characters are not escapable in Makefile.
786 # These characters are `;`, `|`, `\`, and the non-printable ones.
787 # They will be rendered as `"?{hex}"`.
788 fun escape_to_mk: String do
790 for i in [0..length[ do
794 else if c == ':' or c == ' ' or c == '#' then
797 else if c
.code_point
< 32 or c
== ';' or c
== '|' or c
== '\\' then
798 b
.append
("?{c.code_point.to_base(16)}")
806 # Return a string where Nit escape sequences are transformed.
810 # assert s.length == 2
811 # var u = s.unescape_nit
812 # assert u.length == 1
813 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
815 fun unescape_nit
: String
817 var res
= new Buffer.with_cap
(self.length
)
818 var was_slash
= false
819 for i
in [0..length
[ do
821 if not was_slash
then
832 else if c
== 'r' then
834 else if c
== 't' then
836 else if c
== '0' then
845 # Returns `self` with all characters escaped with their UTF-16 representation
848 # assert "Aèあ𐏓".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
850 fun escape_to_utf16
: String do
852 for i
in chars
do buf
.append i
.escape_to_utf16
856 # Returns the Unicode char escaped by `self`
859 # assert "\\u0041".from_utf16_escape == 'A'
860 # assert "\\ud800\\udfd3".from_utf16_escape == '𐏓'
861 # assert "\\u00e8".from_utf16_escape == 'è'
862 # assert "\\u3042".from_utf16_escape == 'あ'
864 fun from_utf16_escape
(pos
, ln
: nullable Int): Char do
865 if pos
== null then pos
= 0
866 if ln
== null then ln
= length
- pos
867 if ln
< 6 then return 0xFFFD.code_point
868 var cp
= from_utf16_digit
(pos
+ 2).to_u32
869 if cp
< 0xD800u
32 then return cp
.code_point
870 if cp
> 0xDFFFu
32 then return cp
.code_point
871 if cp
> 0xDBFFu
32 then return 0xFFFD.code_point
872 if ln
== 6 then return 0xFFFD.code_point
873 if ln
< 12 then return 0xFFFD.code_point
875 cp
+= from_utf16_digit
(pos
+ 8).to_u32
876 var cplo
= cp
& 0xFFFFu
32
877 if cplo
< 0xDC00u
32 then return 0xFFFD.code_point
878 if cplo
> 0xDFFFu
32 then return 0xFFFD.code_point
879 return cp
.from_utf16_surr
.code_point
882 # Returns a UTF-16 escape value
885 # var s = "\\ud800\\udfd3"
886 # assert s.from_utf16_digit(2) == 0xD800
887 # assert s.from_utf16_digit(8) == 0xDFD3
889 fun from_utf16_digit
(pos
: nullable Int): Int do
890 if pos
== null then pos
= 0
891 return to_hex
(pos
, 4)
894 # Encode `self` to percent (or URL) encoding
897 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
898 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
899 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
900 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
902 fun to_percent_encoding
: String
906 for i
in [0..length
[ do
908 if (c
>= '0' and c
<= '9') or
909 (c
>= 'a' and c
<= 'z') or
910 (c
>= 'A' and c
<= 'Z') or
911 c
== '-' or c
== '.' or
916 var bytes
= c
.to_s
.bytes
917 for b
in bytes
do buf
.append
"%{b.to_i.to_hex}"
924 # Decode `self` from percent (or URL) encoding to a clear string
926 # Invalid '%' are not decoded.
929 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
930 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
931 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
932 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
933 # assert "incomplete %".from_percent_encoding == "incomplete %"
934 # assert "invalid % usage".from_percent_encoding == "invalid % usage"
935 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
936 # assert "%1 %A %C3%A9A9".from_percent_encoding == "%1 %A éA9"
938 fun from_percent_encoding
: String
940 var len
= byte_length
941 var has_percent
= false
949 # If no transformation is needed, return self as a string
950 if not has_percent
then return to_s
952 var buf
= new CString(len
)
958 if i
+ 2 >= length
then
959 # What follows % has been cut off
963 var hex_s
= substring
(i
, 2)
965 var hex_i
= hex_s
.to_hex
969 # What follows a % is not Hex
974 else buf
[l
] = c
.code_point
980 return buf
.to_s_unsafe
(l
, copy
=false)
983 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
986 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
989 # 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>
990 fun html_escape
: String
992 var buf
: nullable Buffer = null
994 for i
in [0..length
[ do
999 else if c
== '<' then
1001 else if c
== '>' then
1003 else if c
== '"' then
1005 else if c
== '\'' then
1007 else if c == '/' then
1010 if buf != null then buf.add c
1015 for j in [0..i[ do buf.add chars[j]
1020 if buf == null then return self.to_s
1025 # Two pieces of text are equals if thez have the same characters in the same order.
1028 # assert "hello" == "hello"
1029 # assert "hello" != "HELLO"
1030 # assert "hello" == "hel"+"lo"
1033 # Things that are not Text are not equal.
1037 # assert "9" != ['9']
1040 # assert "9".chars.first == '9' # equality of Char
1041 # assert "9".chars == ['9'] # equality of Sequence
1042 # assert "9".to_i == 9 # equality of Int
1046 if o == null then return false
1047 if not o isa Text then return false
1048 if self.is_same_instance(o) then return true
1049 if self.length != o.length then return false
1050 return self.chars == o.chars
1053 # Lexicographical comparaison
1056 # assert "abc" < "xy"
1057 # assert "ABC" < "abc"
1061 var self_chars = self.chars.iterator
1062 var other_chars = other.chars.iterator
1064 while self_chars.is_ok and other_chars.is_ok do
1065 if self_chars.item < other_chars.item then return true
1066 if self_chars.item > other_chars.item then return false
1071 if self_chars.is_ok then
1078 # Escape string used in labels for graphviz
1081 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
1083 fun escape_to_dot: String
1085 return escape_more_to_c("|\{\}<>")
1088 private var hash_cache: nullable Int = null
1092 if hash_cache == null then
1093 # djb2 hash algorithm
1096 for i in [0..length[ do
1098 h = (h << 5) + h + char.code_point
1103 return hash_cache.as(not null)
1106 # Format `self` by replacing each `%n` with the `n`th item of `args`
1108 # The character `%` followed by something other than a number are left as is.
1109 # To represent a `%` followed by a number, double the `%`, as in `%%7`.
1112 # assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
1113 # assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"
1115 fun format(args: Object...): String do
1116 var s = new Array[Text]
1120 if self[i] == '%' then
1124 while i < length and self[i].is_numeric do
1128 var ciph_len = i - ciph_st
1129 if ciph_len == 0 then
1130 # What follows '%' is not a number.
1131 s.push substring(curr_st, i - curr_st)
1132 if i < length and self[i] == '%' then
1140 var arg_index = substring(ciph_st, ciph_len).to_i
1141 if arg_index >= args.length then continue
1143 s.push substring(curr_st, fmt_st - curr_st)
1144 s.push args[arg_index].to_s
1151 s.push substring(curr_st, length - curr_st)
1155 # Return the Levenshtein distance between two strings
1158 # assert "abcd".levenshtein_distance("abcd") == 0
1159 # assert "".levenshtein_distance("abcd") == 4
1160 # assert "abcd".levenshtein_distance("") == 4
1161 # assert "abcd".levenshtein_distance("xyz") == 4
1162 # assert "abcd".levenshtein_distance("xbdy") == 3
1164 fun levenshtein_distance(other: String): Int
1166 var slen = self.length
1167 var olen = other.length
1170 if slen == 0 then return olen
1171 if olen == 0 then return slen
1172 if self == other then return 0
1174 # previous row of distances
1175 var v0 = new Array[Int].with_capacity(olen+1)
1177 # current row of distances
1178 var v1 = new Array[Int].with_capacity(olen+1)
1180 for j in [0..olen] do
1181 # prefix insert cost
1185 for i in [0..slen[ do
1187 # prefix delete cost
1190 for j in [0..olen[ do
1192 var cost1 = v1[j] + 1
1194 var cost2 = v0[j + 1] + 1
1195 # same char cost (+0)
1198 if self[i] != other[j] then cost3 += 1
1200 v1[j+1] = cost1.min(cost2).min(cost3)
1204 # * v1 become v0 in the next iteration
1205 # * old v0 is reused as the new v1
1214 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1216 # Basically a high-level synonym of CString::copy_to
1218 # REQUIRE: `n` must be large enough to contain `len` bytes
1221 # var ns = new CString(8)
1222 # "Text is String".copy_to_native(ns, 8, 2, 0)
1223 # assert ns.to_s_with_length(8) == "xt is St"
1225 fun copy_to_native(dest: CString, n, src_offset, dest_offset: Int) do
1226 var mypos = src_offset
1227 var itspos = dest_offset
1229 dest[itspos] = self.bytes[mypos]
1236 # Packs the content of a string in packs of `ln` chars.
1237 # This variant ensures that only the last element might be smaller than `ln`
1240 # var s = "abcdefghijklmnopqrstuvwxyz"
1241 # assert s.pack_l(4) == ["abcd","efgh","ijkl","mnop","qrst","uvwx","yz"]
1243 fun pack_l(ln: Int): Array[Text] do
1245 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1246 while st < length do
1247 retarr.add(substring(st, ln))
1253 # Packs the content of a string in packs of `ln` chars.
1254 # This variant ensures that only the first element might be smaller than `ln`
1257 # var s = "abcdefghijklmnopqrstuvwxyz"
1258 # assert s.pack_r(4) == ["ab","cdef","ghij","klmn","opqr","stuv","wxyz"]
1260 fun pack_r(ln: Int): Array[Text] do
1262 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1264 retarr.add(substring(st - ln, ln))
1267 return retarr.reversed
1270 # Concatenates self `i` times
1273 # assert "abc" * 4 == "abcabcabcabc"
1274 # assert "abc" * 1 == "abc"
1275 # assert "abc" * 0 == ""
1276 # var b = new Buffer
1279 # assert b == "天地天地天地天地"
1281 fun *(i: Int): SELFTYPE is abstract
1283 # Insert `s` at `pos`.
1286 # assert "helloworld".insert_at(" ", 5) == "hello world"
1287 # var b = new Buffer
1288 # b.append("Hello世界")
1289 # b = b.insert_at(" beautiful ", 5)
1290 # assert b == "Hello beautiful 世界"
1292 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1294 # Returns a reversed version of self
1297 # assert "hello".reversed == "olleh"
1298 # assert "bob".reversed == "bob"
1299 # assert "".reversed == ""
1301 fun reversed: SELFTYPE is abstract
1303 # A upper case version of `self`
1306 # assert "Hello World!".to_upper == "HELLO WORLD!"
1308 fun to_upper: SELFTYPE is abstract
1310 # A lower case version of `self`
1313 # assert "Hello World!".to_lower == "hello world!"
1315 fun to_lower : SELFTYPE is abstract
1317 # Takes a camel case `self` and converts it to snake case
1320 # assert "randomMethodId".to_snake_case == "random_method_id"
1323 # The rules are the following:
1325 # An uppercase is always converted to a lowercase
1328 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1331 # An uppercase that follows a lowercase is prefixed with an underscore
1334 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1337 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1340 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1343 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1346 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1348 fun to_snake_case: SELFTYPE is abstract
1350 # Takes a snake case `self` and converts it to camel case
1353 # assert "random_method_id".to_camel_case == "randomMethodId"
1356 # If the identifier is prefixed by an underscore, the underscore is ignored
1359 # assert "_private_field".to_camel_case == "_privateField"
1362 # If `self` is upper, it is returned unchanged
1365 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1368 # If there are several consecutive underscores, they are considered as a single one
1371 # assert "random__method_id".to_camel_case == "randomMethodId"
1373 fun to_camel_case: SELFTYPE is abstract
1375 # Returns a capitalized `self`
1377 # Letters that follow a letter are lowercased
1378 # Letters that follow a non-letter are upcased.
1380 # If `keep_upper = true`, already uppercase letters are not lowercased.
1382 # SEE : `Char::is_letter` for the definition of letter.
1385 # assert "jAVASCRIPT".capitalized == "Javascript"
1386 # assert "i am root".capitalized == "I Am Root"
1387 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1388 # assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"
1390 fun capitalized(keep_upper: nullable Bool): SELFTYPE do
1391 if length == 0 then return self
1393 var buf = new Buffer.with_cap(length)
1394 buf.capitalize(keep_upper=keep_upper, src=self)
1399 # All kinds of array-based text representations.
1400 abstract class FlatText
1403 # Underlying CString (`char*`)
1405 # Warning: Might be void in some subclasses, be sure to check
1406 # if set before using it.
1407 var items: CString is noinit
1409 # Returns a char* starting at position `first_byte`
1411 # WARNING: If you choose to use this service, be careful of the following.
1413 # Strings and CString are *ideally* always allocated through a Garbage Collector.
1414 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1415 # deallocated at any moment, rendering the pointer returned by this function invalid.
1416 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1417 # (Failure to do so will most certainly result in long and painful debugging hours)
1419 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1420 # then immediately return).
1422 # As always, do not modify the content of the String in C code, if this is what you want
1423 # copy locally the char* as Nit Strings are immutable.
1424 fun fast_cstring: CString is abstract
1426 redef var length = 0
1428 redef var byte_length = 0
1439 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1440 items.copy_to(dest, n, src_offset, dest_offset)
1444 # Abstract class for the SequenceRead compatible
1445 # views on the chars of any Text
1446 private abstract class StringCharView
1447 super SequenceRead[Char]
1451 var target: SELFTYPE
1453 redef fun is_empty do return target.is_empty
1455 redef fun length do return target.length
1457 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1459 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1462 # Abstract class for the SequenceRead compatible
1463 # views on the bytes of any Text
1464 private abstract class StringByteView
1465 super SequenceRead[Int]
1469 var target: SELFTYPE
1471 redef fun is_empty do return target.is_empty
1473 redef fun length do return target.byte_length
1475 redef fun iterator do return self.iterator_from(0)
1477 redef fun reverse_iterator do return self.reverse_iterator_from(target.byte_length - 1)
1480 # Immutable sequence of characters.
1482 # String objects may be created using literals.
1485 # assert "Hello World!" isa String
1487 abstract class String
1490 redef type SELFTYPE: String is fixed
1492 redef fun to_s do return self
1494 redef fun clone do return self
1496 redef fun to_buffer do return new Buffer.from_text(self)
1498 redef fun to_camel_case do
1499 if self.is_upper then return self
1501 var new_str = new Buffer.with_cap(length)
1507 redef fun to_snake_case do
1508 if self.is_lower then return self
1510 var new_str = new Buffer.with_cap(self.length)
1517 # A mutable sequence of characters.
1518 abstract class Buffer
1521 # Returns an arbitrary subclass of `Buffer` with default parameters
1524 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1525 new with_cap(i: Int) is abstract
1527 # Returns an instance of a subclass of `Buffer` with `t` as content
1528 new from_text(t: Text) do
1529 var ret = new Buffer.with_cap(t.byte_length)
1534 redef type SELFTYPE: Buffer is fixed
1536 # Copy-On-Write flag
1538 # If the `Buffer` was to_s'd
, the next in-place altering
1539 # operation will cause the current `Buffer` to be re-allocated.
1541 # The flag will then be set at `false`.
1542 protected var written
= false
1544 # Modifies the char contained at pos `index`
1545 fun []=(index
: Int, item
: Char) is abstract
1547 redef fun to_buffer
do return clone
1550 # var b = new Buffer
1551 # b.append("Buffer!")
1556 var cln
= new Buffer.with_cap
(byte_length
)
1561 # Adds a char `c` at the end of self
1562 fun add
(c
: Char) is abstract
1567 # var b = new Buffer
1569 # assert not b.is_empty
1573 fun clear
is abstract
1575 # Enlarges the subsequent array containing the chars of self
1576 fun enlarge
(cap
: Int) is abstract
1578 # Adds the content of text `s` at the end of self
1581 # var b = new Buffer
1584 # assert b == "helloworld"
1586 fun append
(s
: Text) is abstract
1588 # `self` is appended in such a way that `self` is repeated `r` times
1591 # var b = new Buffer
1594 # assert b == "hellohellohello"
1596 fun times
(r
: Int) is abstract
1598 # Reverses itself in-place
1601 # var b = new Buffer
1604 # assert b == "olleh"
1606 fun reverse
is abstract
1608 # Changes each lower-case char in `self` by its upper-case variant
1611 # var b = new Buffer
1612 # b.append("Hello World!")
1614 # assert b == "HELLO WORLD!"
1616 fun upper
is abstract
1618 # Changes each upper-case char in `self` by its lower-case variant
1621 # var b = new Buffer
1622 # b.append("Hello World!")
1624 # assert b == "hello world!"
1626 fun lower
is abstract
1628 # Capitalizes each word in `self`
1630 # Letters that follow a letter are lowercased
1631 # Letters that follow a non-letter are upcased.
1633 # If `keep_upper = true`, uppercase letters are not lowercased.
1635 # When `src` is specified, this method reads from `src` instead of `self`
1636 # but it still writes the result to the beginning of `self`.
1637 # This requires `self` to have the capacity to receive all of the
1638 # capitalized content of `src`.
1640 # SEE: `Char::is_letter` for the definition of a letter.
1643 # var b = new FlatBuffer.from("jAVAsCriPt")
1645 # assert b == "Javascript"
1646 # b = new FlatBuffer.from("i am root")
1648 # assert b == "I Am Root"
1649 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1651 # assert b == "Ab_C -Ab0C Ab\nC"
1653 # b = new FlatBuffer.from("12345")
1654 # b.capitalize(src="foo")
1655 # assert b == "Foo45"
1657 # b = new FlatBuffer.from("preserve my ACRONYMS")
1658 # b.capitalize(keep_upper=true)
1659 # assert b == "Preserve My ACRONYMS"
1661 fun capitalize
(keep_upper
: nullable Bool, src
: nullable Text) do
1662 src
= src
or else self
1663 var length
= src
.length
1664 if length
== 0 then return
1665 keep_upper
= keep_upper
or else false
1667 var c
= src
[0].to_upper
1670 for i
in [1 .. length
[ do
1673 if prev
.is_letter
then
1677 self[i
] = c
.to_lower
1680 self[i
] = c
.to_upper
1685 # In Buffers, the internal sequence of character is mutable
1686 # Thus, `chars` can be used to modify the buffer.
1687 redef fun chars
: Sequence[Char] is abstract
1689 # Appends `length` chars from `s` starting at index `from`
1692 # var b = new Buffer
1693 # b.append_substring("abcde", 1, 2)
1695 # b.append_substring("vwxyz", 2, 3)
1696 # assert b == "bcxyz"
1697 # b.append_substring("ABCDE", 4, 300)
1698 # assert b == "bcxyzE"
1699 # b.append_substring("VWXYZ", 400, 1)
1700 # assert b == "bcxyzE"
1702 fun append_substring
(s
: Text, from
, length
: Int) do
1708 if (length
+ from
) > ln
then length
= ln
- from
1709 if length
<= 0 then return
1710 append_substring_impl
(s
, from
, length
)
1713 # Unsafe version of `append_substring` for performance
1715 # NOTE: Use only if sure about `from` and `length`, no checks
1716 # or bound recalculation is done
1717 fun append_substring_impl
(s
: Text, from
, length
: Int) do
1718 var max
= from
+ length
1719 for i
in [from
.. max
[ do add s
[i
]
1723 var ret
= new Buffer.with_cap
(byte_length
* i
)
1724 for its
in [0 .. i
[ do ret
.append
self
1728 redef fun insert_at
(s
, pos
) do
1729 var obuf
= new Buffer.with_cap
(byte_length
+ s
.byte_length
)
1730 obuf
.append_substring
(self, 0, pos
)
1732 obuf
.append_substring
(self, pos
, length
- pos
)
1736 # Inserts `s` at position `pos`
1739 # var b = new Buffer
1741 # b.insert(" nit ", 3)
1742 # assert b == "美しい nit 世界"
1744 fun insert
(s
: Text, pos
: Int) is abstract
1746 # Inserts `c` at position `pos`
1749 # var b = new Buffer
1751 # b.insert_char(' ', 3)
1752 # assert b == "美しい 世界"
1754 fun insert_char
(c
: Char, pos
: Int) is abstract
1756 # Removes a substring from `self` at position `pos`
1758 # NOTE: `length` defaults to 1, expressed in chars
1761 # var b = new Buffer
1762 # b.append("美しい 世界")
1764 # assert b == "美しい世界"
1768 fun remove_at
(pos
: Int, length
: nullable Int) is abstract
1770 redef fun reversed
do
1776 redef fun to_upper
do
1782 redef fun to_lower
do
1788 redef fun to_snake_case
do
1794 # Takes a camel case `self` and converts it to snake case
1796 # SEE: `to_snake_case`
1798 if self.is_lower
then return
1799 var prev_is_lower
= false
1800 var prev_is_upper
= false
1805 if char
.is_lower
then
1806 prev_is_lower
= true
1807 prev_is_upper
= false
1808 else if char
.is_upper
then
1809 if prev_is_lower
then
1812 else if prev_is_upper
and i
+ 1 < length
and self[i
+ 1].is_lower
then
1816 self[i
] = char
.to_lower
1817 prev_is_lower
= false
1818 prev_is_upper
= true
1820 prev_is_lower
= false
1821 prev_is_upper
= false
1827 redef fun to_camel_case
1834 # Takes a snake case `self` and converts it to camel case
1836 # SEE: `to_camel_case`
1838 if is_upper
then return
1840 var underscore_count
= 0
1843 while pos
< length
do
1844 var char
= self[pos
]
1846 underscore_count
+= 1
1847 else if underscore_count
> 0 then
1848 pos
-= underscore_count
1849 remove_at
(pos
, underscore_count
)
1850 self[pos
] = char
.to_upper
1851 underscore_count
= 0
1855 if underscore_count
> 0 then remove_at
(pos
- underscore_count
- 1, underscore_count
)
1858 redef fun capitalized
(keep_upper
) do
1859 if length
== 0 then return self
1861 var buf
= new Buffer.with_cap
(byte_length
)
1862 buf
.capitalize
(keep_upper
=keep_upper
, src
=self)
1867 # View for chars on Buffer objects, extends Sequence
1868 # for mutation operations
1869 private abstract class BufferCharView
1870 super StringCharView
1871 super Sequence[Char]
1873 redef type SELFTYPE: Buffer
1877 # View for bytes on Buffer objects, extends Sequence
1878 # for mutation operations
1879 private abstract class BufferByteView
1880 super StringByteView
1882 redef type SELFTYPE: Buffer
1886 # User readable representation of `self`.
1887 fun to_s
: String do return inspect
1889 # The class name of the object in CString format.
1890 private fun native_class_name
: CString is intern
1892 # The class name of the object.
1895 # assert 5.class_name == "Int"
1897 fun class_name
: String do return native_class_name
.to_s
1899 # Developer readable representation of `self`.
1900 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1903 return "<{inspect_head}>"
1906 # Return "CLASSNAME:#OBJECTID".
1907 # This function is mainly used with the redefinition of the inspect method
1908 protected fun inspect_head
: String
1910 return "{class_name}:#{object_id.to_hex}"
1916 # assert true.to_s == "true"
1917 # assert false.to_s == "false"
1930 # C function to calculate the length of the `CString` to receive `self`
1931 private fun byte_to_s_len
: Int `{
1932 return snprintf(NULL, 0, "0x%02x", self);
1935 # C function to convert an nit Int to a CString (char*)
1936 private fun native_byte_to_s
(nstr
: CString, strlen
: Int) `{
1937 snprintf(nstr, strlen, "0x%02x", self);
1940 # Displayable byte in its hexadecimal form (0x..)
1943 # assert 1.to_b.to_s == "0x01"
1944 # assert (-123).to_b.to_s == "0x85"
1947 var nslen
= byte_to_s_len
1948 var ns
= new CString(nslen
+ 1)
1950 native_byte_to_s
(ns
, nslen
+ 1)
1951 return ns
.to_s_unsafe
(nslen
, copy
=false, clean
=false)
1957 # Wrapper of strerror C function
1958 private fun strerror_ext
: CString `{ return strerror((int)self); `}
1960 # Returns a string describing error number
1961 fun strerror: String do return strerror_ext.to_s
1963 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if negative).
1964 # assume < to_c max const of char
1965 private fun fill_buffer(s: Buffer, base: Int)
1972 else if self == 0 then
1979 var pos = digit_count(base) - 1
1980 while pos >= 0 and n > 0 do
1981 s.chars[pos] = (n % base).to_c
1987 # C function to calculate the length of the `CString` to receive `self`
1988 private fun int_to_s_len: Int `{
1989 return snprintf
(NULL, 0, "%ld", self);
1992 # C function to convert an nit Int to a CString (char*)
1993 private fun native_int_to_s(nstr: CString, strlen: Int) `{
1994 snprintf
(nstr
, strlen
, "%ld", self);
1997 # String representation of `self` in the given `base
`
2000 # assert 15.to_base(10) == "15"
2001 # assert 15.to_base(16) == "f"
2002 # assert 15.to_base(2) == "1111"
2003 # assert (-10).to_base(3) == "-101"
2005 fun to_base(base: Int): String
2007 var l = digit_count(base)
2010 for x in [0..l[ do s.add(' ')
2011 fill_buffer(s, base)
2016 # return displayable int in hexadecimal
2019 # assert 1.to_hex == "1"
2020 # assert (-255).to_hex == "-ff"
2022 fun to_hex: String do return to_base(16)
2026 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
2029 # assert 12.34.to_s == "12.34"
2030 # assert (-0120.030).to_s == "-120.03"
2033 # see `to_precision
` for a custom precision.
2035 var str = to_precision( 3 )
2036 if is_inf != 0 or is_nan then return str
2037 var len = str.length
2038 for i in [0..len-1] do
2040 var c = str.chars[j]
2043 else if c == '.' then
2044 return str.substring( 0, j+2 )
2046 return str.substring( 0, j+1 )
2052 # `String` representation of `self` with the given number of `decimals
`
2055 # assert 12.345.to_precision(0) == "12"
2056 # assert 12.345.to_precision(3) == "12.345"
2057 # assert (-12.345).to_precision(3) == "-12.345"
2058 # assert (-0.123).to_precision(3) == "-0.123"
2059 # assert 0.999.to_precision(2) == "1.00"
2060 # assert 0.999.to_precision(4) == "0.9990"
2062 fun to_precision(decimals: Int): String
2064 if is_nan then return "nan"
2066 var isinf = self.is_inf
2069 else if isinf == -1 then
2073 var size = to_precision_size(decimals)
2074 var cstr = new CString(size+1)
2075 to_precision_fill(decimals, size+1, cstr)
2076 return cstr.to_s_unsafe(byte_length=size, copy=false)
2079 # Required string length to hold `self` with `nb
` decimals
2081 # The length does not include the terminating null byte.
2082 private fun to_precision_size(nb: Int): Int `{
2083 return snprintf
(NULL, 0, "%.*f", (int
)nb
, self);
2086 # Fill `cstr
` with `self` and `nb
` decimals
2087 private fun to_precision_fill(nb, size: Int, cstr: CString) `{
2088 snprintf
(cstr
, size
, "%.*f", (int
)nb
, self);
2094 # Returns a sequence with the UTF-8 bytes of `self`
2097 # assert 'a'.bytes == [0x61]
2098 # assert 'ま'.bytes == [0xE3, 0x81, 0xBE]
2100 fun bytes: SequenceRead[Int] do return to_s.bytes
2102 # Is `self` an UTF-16 surrogate pair ?
2103 fun is_surrogate: Bool do
2105 return cp >= 0xD800 and cp <= 0xDFFF
2108 # Is `self` a UTF-16 high surrogate ?
2109 fun is_hi_surrogate: Bool do
2111 return cp >= 0xD800 and cp <= 0xDBFF
2114 # Is `self` a UTF-16 low surrogate ?
2115 fun is_lo_surrogate: Bool do
2117 return cp >= 0xDC00 and cp <= 0xDFFF
2120 # Length of `self` in a UTF-8 String
2121 fun u8char_len: Int do
2122 var c = self.code_point
2123 if c < 0x80 then return 1
2124 if c <= 0x7FF then return 2
2125 if c <= 0xFFFF then return 3
2126 if c <= 0x10FFFF then return 4
2127 # Bad character format
2132 # assert 'x'.to_s == "x"
2136 var ns = new CString(ln + 1)
2138 return ns.to_s_unsafe(ln, copy=false, clean=false)
2141 # Returns `self` escaped to UTF-16
2143 # i.e. Represents `self`.`code_point
` using UTF-16 codets escaped
2147 # assert 'A'.escape_to_utf16 == "\\u0041"
2148 # assert 'è'.escape_to_utf16 == "\\u00e8"
2149 # assert 'あ'.escape_to_utf16 == "\\u3042"
2150 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
2152 fun escape_to_utf16: String do
2155 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
2156 buf = new Buffer.with_cap(6)
2157 buf.append("\\u0000")
2160 for i in hx.chars.reverse_iterator do
2165 buf = new Buffer.with_cap(12)
2166 buf.append("\\u0000\\u0000")
2167 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
2168 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
2183 private fun u8char_tos(r: CString, len: Int) `{
2190 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
2191 r
[1] = 0x80 | (self & 0x3F);
2194 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
2195 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
2196 r
[2] = 0x80 | (self & 0x3F);
2199 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
2200 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
2201 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
2202 r
[3] = 0x80 | (self & 0x3F);
2207 # Returns true if the char is a numerical digit
2210 # assert '0'.is_numeric
2211 # assert '9'.is_numeric
2212 # assert not 'a'.is_numeric
2213 # assert not '?'.is_numeric
2216 # FIXME: Works on ASCII-range only
2217 fun is_numeric: Bool
2219 return self >= '0' and self <= '9'
2222 # Returns true if the char is an alpha digit
2225 # assert 'a'.is_alpha
2226 # assert 'Z'.is_alpha
2227 # assert not '0'.is_alpha
2228 # assert not '?'.is_alpha
2231 # FIXME: Works on ASCII-range only
2234 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2237 # Is `self` an hexadecimal digit ?
2240 # assert 'A'.is_hexdigit
2241 # assert not 'G'.is_hexdigit
2242 # assert 'a'.is_hexdigit
2243 # assert not 'g'.is_hexdigit
2244 # assert '5'.is_hexdigit
2246 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
2247 (self >= 'a' and self <= 'f')
2249 # Returns true if the char is an alpha or a numeric digit
2252 # assert 'a'.is_alphanumeric
2253 # assert 'Z'.is_alphanumeric
2254 # assert '0'.is_alphanumeric
2255 # assert '9'.is_alphanumeric
2256 # assert not '?'.is_alphanumeric
2259 # FIXME: Works on ASCII-range only
2260 fun is_alphanumeric: Bool
2262 return self.is_numeric or self.is_alpha
2265 # Returns `self` to its int value
2267 # REQUIRE: `is_hexdigit
`
2268 fun from_hex: Int do
2269 if self >= '0' and self <= '9' then return code_point - 0x30
2270 if self >= 'A' and self <= 'F' then return code_point - 0x37
2271 if self >= 'a' and self <= 'f' then return code_point - 0x57
2272 # Happens if self is not a hexdigit
2273 assert self.is_hexdigit
2274 # To make flow analysis happy
2279 redef class Collection[E]
2280 # String representation of the content of the collection.
2282 # The standard representation is the list of elements separated with commas.
2285 # assert [1,2,3].to_s == "[1,2,3]"
2286 # assert [1..3].to_s == "[1,2,3]"
2287 # assert (new Array[Int]).to_s == "[]" # empty collection
2290 # Subclasses may return a more specific string representation.
2293 return "[" + join(",") + "]"
2296 # Concatenate elements without separators
2299 # assert [1,2,3].plain_to_s == "123"
2300 # assert [11..13].plain_to_s == "111213"
2301 # assert (new Array[Int]).plain_to_s == "" # empty collection
2303 fun plain_to_s: String
2306 for e in self do if e != null then s.append(e.to_s)
2310 # Concatenate and separate each elements with `separator
`.
2312 # Only concatenate if `separator
== null`.
2315 # assert [1, 2, 3].join(":") == "1:2:3"
2316 # assert [1..3].join(":") == "1:2:3"
2317 # assert [1..3].join == "123"
2320 # if `last_separator
` is given, then it is used to separate the last element.
2323 # assert [1, 2, 3, 4].join(", ", " and ") == "1, 2, 3 and 4"
2325 fun join(separator: nullable Text, last_separator: nullable Text): String
2327 if is_empty then return ""
2329 var s = new Buffer # Result
2334 if e != null then s.append(e.to_s)
2336 if last_separator == null then last_separator = separator
2338 # Concat other items
2344 if separator != null then s.append(separator)
2346 if last_separator != null then s.append(last_separator)
2348 if e != null then s.append(e.to_s)
2354 redef class Map[K,V]
2355 # Concatenate couples of key value.
2356 # Key and value are separated by `couple_sep
`.
2357 # Couples are separated by `sep
`.
2360 # var m = new HashMap[Int, String]
2363 # assert m.join("; ", "=") == "1=one; 10=ten"
2365 fun join(sep, couple_sep: String): String is abstract
2369 private var args_cache: nullable Sequence[String] = null
2371 # The arguments of the program as given by the OS
2372 fun program_args: Sequence[String]
2374 if _args_cache == null then init_args
2375 return _args_cache.as(not null)
2378 # The name of the program as given by the OS
2379 fun program_name: String
2381 return native_argv(0).to_s
2384 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2385 private fun init_args
2387 var argc = native_argc
2388 var args = new Array[String].with_capacity(0)
2391 args[i-1] = native_argv(i).to_s
2397 # First argument of the main C function.
2398 private fun native_argc: Int is intern
2400 # Second argument of the main C function.
2401 private fun native_argv(i: Int): CString is intern
2404 # Comparator that efficienlty use `to_s
` to compare things
2406 # The comparaison call `to_s
` on object and use the result to order things.
2409 # var a = [1, 2, 3, 10, 20]
2410 # (new CachedAlphaComparator).sort(a)
2411 # assert a == [1, 10, 2, 20, 3]
2414 # Internally the result of `to_s
` is cached in a HashMap to counter
2415 # uneficient implementation of `to_s
`.
2417 # Note: it caching is not usefull, see `alpha_comparator
`
2418 class CachedAlphaComparator
2420 redef type COMPARED: Object
2422 private var cache = new HashMap[Object, String]
2424 private fun do_to_s(a: Object): String do
2425 if cache.has_key(a) then return cache[a]
2431 redef fun compare(a, b) do
2432 return do_to_s(a) <=> do_to_s(b)
2436 # see `alpha_comparator
`
2437 private class AlphaComparator
2439 redef fun compare(a, b) do
2440 if a == b then return 0
2441 if a == null then return -1
2442 if b == null then return 1
2443 return a.to_s <=> b.to_s
2447 # Stateless comparator that naively use `to_s
` to compare things.
2449 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2450 # on a single instace. See `CachedAlphaComparator` as an alternative.
2453 # var a = [1, 2, 3, 10, 20]
2454 # alpha_comparator.sort(a)
2455 # assert a == [1, 10, 2, 20, 3]
2457 fun alpha_comparator: Comparator do return once new AlphaComparator
2459 # The arguments of the program as given by the OS
2460 fun args: Sequence[String]
2462 return sys.program_args
2467 # Get a `String` from the data at `self` (with unsafe options)
2469 # The default behavior is the safest and equivalent to `to_s
`.
2473 # * Set `byte_length
` to the number of bytes to use as data.
2474 # Otherwise, this method searches for a terminating null byte.
2476 # * Set `char_length
` to the number of Unicode character in the string.
2477 # Otherwise, the data is read to count the characters.
2478 # Ignored if `clean
== true`.
2480 # * If `copy
== true`, the default, copies the data at `self` in the
2481 # Nit GC allocated memory. Otherwise, the return may still point to
2482 # the data at `self`.
2484 # * If `clean
== true`, the default, the string is cleaned of invalid UTF-8
2485 # characters. If cleaning is necessary, the data is copied into Nit GC
2486 # managed memory, whether or not `copy
== true`.
2487 # Don't clean only when the data has already been verified as valid UTF-8,
2488 # other library services rely on UTF-8 compliant characters.
2489 fun to_s_unsafe(byte_length, char_length: nullable Int, copy, clean: nullable Bool): String is abstract
2491 # Retro-compatibility service use by execution engines
2493 # TODO remove this method at the next c_src regen.
2494 private fun to_s_full(byte_length, char_length: Int): String do return to_s_unsafe(byte_length, char_length, false, false)
2496 # Copies the content of `src
` to `self`
2498 # NOTE: `self` must be large enough to contain `self.byte_length
` bytes
2499 fun fill_from(src: Text) do src.copy_to_native(self, src.byte_length, 0, 0)
2502 redef class NativeArray[E]
2503 # Join all the elements using `to_s
`
2505 # REQUIRE: `self isa NativeArray[String]`
2506 # REQUIRE: all elements are initialized
2507 fun native_to_s: String is abstract