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
37 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
38 fun chars
: SequenceRead[Char] is abstract
40 # Gets a view on the bytes of the Text object
42 # assert "hello".bytes.to_a == [104u8, 101u8, 108u8, 108u8, 111u8]
43 fun bytes
: SequenceRead[Byte] is abstract
45 # Number of characters contained in self.
47 # assert "12345".length == 5
48 # assert "".length == 0
49 # assert "あいうえお".length == 5
50 fun length
: Int is abstract
52 # Number of bytes in `self`
54 # assert "12345".byte_length == 5
55 # assert "あいうえお".byte_length == 15
56 fun byte_length
: Int is abstract
60 # assert "abcd".substring(1, 2) == "bc"
61 # assert "abcd".substring(-1, 2) == "a"
62 # assert "abcd".substring(1, 0) == ""
63 # assert "abcd".substring(2, 5) == "cd"
64 # assert "あいうえお".substring(1,3) == "いうえ"
66 # A `from` index < 0 will be replaced by 0.
67 # Unless a `count` value is > 0 at the same time.
68 # In this case, `from += count` and `count -= from`.
69 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
71 # Iterates on the substrings of self if any
72 private fun substrings
: Iterator[FlatText] is abstract
74 # Is the current Text empty (== "")
77 # assert not "foo".is_empty
78 fun is_empty
: Bool do return self.length
== 0
80 # Returns an empty Text of the right type
82 # This method is used internally to get the right
83 # implementation of an empty string.
84 protected fun empty
: SELFTYPE is abstract
86 # Returns a copy of `self` as a Buffer
87 fun to_buffer
: Buffer is abstract
89 # Gets the first char of the Text
91 # DEPRECATED : Use self.chars.first instead
92 fun first
: Char do return self.chars
[0]
94 # Access a character at `index` in the string.
96 # assert "abcd"[2] == 'c'
98 # DEPRECATED : Use self.chars.[] instead
99 fun [](index
: Int): Char do return self.chars
[index
]
101 # Gets the index of the first occurence of 'c'
103 # Returns -1 if not found
105 # DEPRECATED : Use self.chars.index_of instead
106 fun index_of
(c
: Char): Int
108 return index_of_from
(c
, 0)
111 # Gets the last char of self
113 # DEPRECATED : Use self.chars.last instead
114 fun last
: Char do return self.chars
[length-1
]
116 # Gets the index of the first occurence of ´c´ starting from ´pos´
118 # Returns -1 if not found
120 # DEPRECATED : Use self.chars.index_of_from instead
121 fun index_of_from
(c
: Char, pos
: Int): Int
123 var iter
= self.chars
.iterator_from
(pos
)
125 if iter
.item
== c
then return iter
.index
131 # Gets the last index of char ´c´
133 # Returns -1 if not found
135 # DEPRECATED : Use self.chars.last_index_of instead
136 fun last_index_of
(c
: Char): Int
138 return last_index_of_from
(c
, length
- 1)
141 # Return a null terminated char *
142 fun to_cstring
: CString is abstract
144 # The index of the last occurrence of an element starting from pos (in reverse order).
146 # var s = "/etc/bin/test/test.nit"
147 # assert s.last_index_of_from('/', s.length-1) == 13
148 # assert s.last_index_of_from('/', 12) == 8
150 # Returns -1 if not found
152 # DEPRECATED : Use self.chars.last_index_of_from instead
153 fun last_index_of_from
(item
: Char, pos
: Int): Int do return chars
.last_index_of_from
(item
, pos
)
155 # Concatenates `o` to `self`
157 # assert "hello" + "world" == "helloworld"
158 # assert "" + "hello" + "" == "hello"
159 fun +(o
: Text): SELFTYPE is abstract
161 # Gets an iterator on the chars of self
163 # DEPRECATED : Use self.chars.iterator instead
164 fun iterator
: Iterator[Char]
166 return self.chars
.iterator
170 # Gets an Array containing the chars of self
172 # DEPRECATED : Use self.chars.to_a instead
173 fun to_a
: Array[Char] do return chars
.to_a
175 # Create a substring from `self` beginning at the `from` position
177 # assert "abcd".substring_from(1) == "bcd"
178 # assert "abcd".substring_from(-1) == "abcd"
179 # assert "abcd".substring_from(2) == "cd"
181 # As with substring, a `from` index < 0 will be replaced by 0
182 fun substring_from
(from
: Int): SELFTYPE
184 if from
>= self.length
then return empty
185 if from
< 0 then from
= 0
186 return substring
(from
, length
- from
)
189 # Does self have a substring `str` starting from position `pos`?
191 # assert "abcd".has_substring("bc",1) == true
192 # assert "abcd".has_substring("bc",2) == false
194 # Returns true iff all characters of `str` are presents
195 # at the expected index in `self.`
196 # The first character of `str` being at `pos`, the second
197 # character being at `pos+1` and so on...
199 # This means that all characters of `str` need to be inside `self`.
201 # assert "abcd".has_substring("xab", -1) == false
202 # assert "abcd".has_substring("cdx", 2) == false
204 # And that the empty string is always a valid substring.
206 # assert "abcd".has_substring("", 2) == true
207 # assert "abcd".has_substring("", 200) == true
208 fun has_substring
(str
: String, pos
: Int): Bool
210 if str
.is_empty
then return true
211 if pos
< 0 or pos
+ str
.length
> length
then return false
212 var myiter
= self.chars
.iterator_from
(pos
)
213 var itsiter
= str
.chars
.iterator
214 while myiter
.is_ok
and itsiter
.is_ok
do
215 if myiter
.item
!= itsiter
.item
then return false
219 if itsiter
.is_ok
then return false
223 # Is this string prefixed by `prefix`?
225 # assert "abcd".has_prefix("ab") == true
226 # assert "abcbc".has_prefix("bc") == false
227 # assert "ab".has_prefix("abcd") == false
228 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
230 # Is this string suffixed by `suffix`?
232 # assert "abcd".has_suffix("abc") == false
233 # assert "abcd".has_suffix("bcd") == true
234 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
236 # Returns `self` as the corresponding integer
238 # assert "123".to_i == 123
239 # assert "-1".to_i == -1
240 # assert "0x64".to_i == 100
241 # assert "0b1100_0011".to_i== 195
242 # assert "--12".to_i == 12
244 # REQUIRE: `self`.`is_int`
245 fun to_i
: Int is abstract
247 # If `self` contains a float, return the corresponding float
249 # assert "123".to_f == 123.0
250 # assert "-1".to_f == -1.0
251 # assert "-1.2e-3".to_f == -0.0012
255 return to_s
.to_cstring
.atof
258 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
260 # assert "ff".to_hex == 255
261 fun to_hex
(pos
, ln
: nullable Int): Int do
263 if pos
== null then pos
= 0
264 if ln
== null then ln
= length
- pos
266 for i
in [pos
.. max
[ do
268 res
+= self[i
].from_hex
273 # If `self` contains only digits <= '7', return the corresponding integer.
275 # assert "714".to_oct == 460
276 fun to_oct
: Int do return a_to
(8)
278 # If `self` contains only '0' et '1', return the corresponding integer.
280 # assert "101101".to_bin == 45
281 fun to_bin
: Int do return a_to
(2)
283 # If `self` contains only digits '0' .. '9', return the corresponding integer.
285 # assert "108".to_dec == 108
286 fun to_dec
: Int do return a_to
(10)
288 # If `self` contains only digits and letters, return the corresponding integer in a given base
290 # assert "120".a_to(3) == 15
291 fun a_to
(base
: Int) : Int
296 for j
in [0..length
[ do
318 # Is this string in a valid numeric format compatible with `to_f`?
320 # assert "123".is_numeric == true
321 # assert "1.2".is_numeric == true
322 # assert "-1.2".is_numeric == true
323 # assert "-1.23e-2".is_numeric == true
324 # assert "1..2".is_numeric == false
325 # assert "".is_numeric == false
328 var has_point
= false
330 for i
in [0..length
[ do
332 if not c
.is_numeric
then
333 if c
== '.' and not has_point
then
335 else if c
== 'e' and e_index
== -1 and i
> 0 and i
< length
- 1 and chars
[i-1
] != '-' then
337 else if c
== '-' and i
== e_index
+ 1 and i
< length
- 1 then
346 # Returns `true` if the string contains only Hex chars
348 # assert "048bf".is_hex == true
349 # assert "ABCDEF".is_hex == true
350 # assert "0G".is_hex == false
353 for i
in [0..length
[ do
355 if not (c
>= 'a' and c
<= 'f') and
356 not (c
>= 'A' and c
<= 'F') and
357 not (c
>= '0' and c
<= '9') then return false
362 # Returns `true` if the string contains only Binary digits
364 # assert "1101100".is_bin == true
365 # assert "1101020".is_bin == false
367 for i
in chars
do if i
!= '0' and i
!= '1' then return false
371 # Returns `true` if the string contains only Octal digits
373 # assert "213453".is_oct == true
374 # assert "781".is_oct == false
376 for i
in chars
do if i
< '0' or i
> '7' then return false
380 # Returns `true` if the string contains only Decimal digits
382 # assert "10839".is_dec == true
383 # assert "164F".is_dec == false
385 for i
in chars
do if i
< '0' or i
> '9' then return false
389 # Are all letters in `self` upper-case ?
391 # assert "HELLO WORLD".is_upper == true
392 # assert "%$&%!".is_upper == true
393 # assert "hello world".is_upper == false
394 # assert "Hello World".is_upper == false
397 for i
in [0..length
[ do
399 if char
.is_lower
then return false
404 # Are all letters in `self` lower-case ?
406 # assert "hello world".is_lower == true
407 # assert "%$&%!".is_lower == true
408 # assert "Hello World".is_lower == false
411 for i
in [0..length
[ do
413 if char
.is_upper
then return false
418 # Removes the whitespaces at the beginning of self
420 # assert " \n\thello \n\t".l_trim == "hello \n\t"
422 # `Char::is_whitespace` determines what is a whitespace.
425 var iter
= self.chars
.iterator
427 if not iter
.item
.is_whitespace
then break
430 if iter
.index
== length
then return self.empty
431 return self.substring_from
(iter
.index
)
434 # Removes the whitespaces at the end of self
436 # assert " \n\thello \n\t".r_trim == " \n\thello"
438 # `Char::is_whitespace` determines what is a whitespace.
441 var iter
= self.chars
.reverse_iterator
443 if not iter
.item
.is_whitespace
then break
446 if iter
.index
< 0 then return self.empty
447 return self.substring
(0, iter
.index
+ 1)
450 # Trims trailing and preceding white spaces
452 # assert " Hello World ! ".trim == "Hello World !"
453 # assert "\na\nb\tc\t".trim == "a\nb\tc"
455 # `Char::is_whitespace` determines what is a whitespace.
456 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
458 # Is the string non-empty but only made of whitespaces?
460 # assert " \n\t ".is_whitespace == true
461 # assert " hello ".is_whitespace == false
462 # assert "".is_whitespace == false
464 # `Char::is_whitespace` determines what is a whitespace.
465 fun is_whitespace
: Bool
467 if is_empty
then return false
468 for c
in self.chars
do
469 if not c
.is_whitespace
then return false
474 # Returns `self` removed from its last line terminator (if any).
476 # assert "Hello\n".chomp == "Hello"
477 # assert "Hello".chomp == "Hello"
479 # assert "\n".chomp == ""
480 # assert "".chomp == ""
482 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
483 # A single line terminator, the last one, is removed.
485 # assert "\r\n".chomp == ""
486 # assert "\r\n\n".chomp == "\r\n"
487 # assert "\r\n\r\n".chomp == "\r\n"
488 # assert "\r\n\r".chomp == "\r\n"
490 # Note: unlike with most IO methods like `Reader::read_line`,
491 # a single `\r` is considered here to be a line terminator and will be removed.
495 if len
== 0 then return self
496 var l
= self.chars
.last
498 return substring
(0, len-1
)
499 else if l
!= '\n' then
501 else if len
> 1 and self.chars
[len-2
] == '\r' then
502 return substring
(0, len-2
)
504 return substring
(0, len-1
)
508 # Justify `self` in a space of `length`
510 # `left` is the space ratio on the left side.
511 # * 0.0 for left-justified (no space at the left)
512 # * 1.0 for right-justified (all spaces at the left)
513 # * 0.5 for centered (half the spaces at the left)
515 # `char`, or `' '` by default, is repeated to pad the empty space.
519 # assert "hello".justify(10, 0.0) == "hello "
520 # assert "hello".justify(10, 1.0) == " hello"
521 # assert "hello".justify(10, 0.5) == " hello "
522 # assert "hello".justify(10, 0.5, '.') == "..hello..."
524 # If `length` is not enough, `self` is returned as is.
526 # assert "hello".justify(2, 0.0) == "hello"
528 # REQUIRE: `left >= 0.0 and left <= 1.0`
529 # ENSURE: `self.length <= length implies result.length == length`
530 # ENSURE: `self.length >= length implies result == self`
531 fun justify
(length
: Int, left
: Float, char
: nullable Char): String
533 var pad
= (char
or else ' ').to_s
534 var diff
= length
- self.length
535 if diff
<= 0 then return to_s
536 assert left
>= 0.0 and left
<= 1.0
537 var before
= (diff
.to_f
* left
).to_i
538 return pad
* before
+ self + pad
* (diff-before
)
541 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
543 # This method is injective (two different inputs never produce the same
544 # output) and the returned string always respect the following rules:
546 # * Contains only US-ASCII letters, digits and underscores.
547 # * Never starts with a digit.
548 # * Never ends with an underscore.
549 # * Never contains two contiguous underscores.
551 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
552 # assert "__".to_cmangle == "_95d_95d"
553 # assert "__d".to_cmangle == "_95d_d"
554 # assert "_d_".to_cmangle == "_d_95d"
555 # assert "_42".to_cmangle == "_95d42"
556 # assert "foo".to_cmangle == "foo"
557 # assert "".to_cmangle == ""
558 fun to_cmangle
: String
560 if is_empty
then return ""
562 var underscore
= false
566 if c
>= '0' and c
<= '9' then
568 res
.append
(c
.code_point
.to_s
)
572 for i
in [start
..length
[ do
574 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
580 res
.append
('_'.code_point
.to_s
)
583 if c
>= '0' and c
<= '9' then
586 else if c
== '_' then
591 res
.append
(c
.code_point
.to_s
)
597 res
.append
('_'.code_point
.to_s
)
603 # Escape `"` `\` `'`, trigraphs and non printable characters using the rules of literal C strings and characters
605 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
606 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
607 # assert "allo???!".escape_to_c == "allo??\\?!"
608 # assert "??=??/??'??(??)".escape_to_c == "?\\?=?\\?/??\\'?\\?(?\\?)"
609 # assert "??!??<??>??-".escape_to_c == "?\\?!?\\?<?\\?>?\\?-"
611 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
612 # Three digits are always used to avoid following digits to be interpreted as an element
613 # of the octal sequence.
615 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
617 # The exceptions are the common `\t` and `\n`.
618 fun escape_to_c
: String
621 for i
in [0..length
[ do
625 else if c
== '\t' then
627 else if c
== '"' then
629 else if c == '\'' then
631 else if c == '\\
' then
633 else if c == '?' then
634 # Escape if it is the last question mark of a ANSI C trigraph.
638 # We ignore `??'` because it will be escaped as `??\
'`.
651 else if c.code_point < 32 then
653 var oct = c.code_point.to_base(8)
654 # Force 3 octal digits since it is the
655 # maximum allowed in the C specification
656 if oct.length == 1 then
659 else if oct.length == 2 then
670 # Escape additionnal characters
671 # The result might no be legal in C but be used in other languages
673 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
674 # assert "allo???!".escape_more_to_c("") == "allo??\\?!"
675 fun escape_more_to_c(chars: String): String
678 for c in escape_to_c.chars do
679 if chars.chars.has(c) then
687 # Escape to C plus braces
689 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
690 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
692 # Escape to POSIX Shell (sh).
694 # Abort if the text contains a null byte.
696 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
697 fun escape_to_sh
: String do
700 for i in [0..length[ do
705 assert without_null_byte
: c
!= '\0'
713 # Escape to include in a Makefile
715 # Unfortunately, some characters are not escapable in Makefile.
716 # These characters are `;`, `|`, `\`, and the non-printable ones.
717 # They will be rendered as `"?{hex}"`.
718 fun escape_to_mk: String do
720 for i in [0..length[ do
724 else if c == ':' or c == ' ' or c == '#' then
727 else if c
.code_point
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
728 b
.append
("?{c.code_point.to_base(16)}")
736 # Return a string where Nit escape sequences are transformed.
739 # assert s.length == 2
740 # var u = s.unescape_nit
741 # assert u.length == 1
742 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
743 fun unescape_nit
: String
745 var res
= new Buffer.with_cap
(self.length
)
746 var was_slash
= false
747 for i
in [0..length
[ do
749 if not was_slash
then
760 else if c
== 'r' then
762 else if c
== 't' then
764 else if c
== '0' then
773 # Returns `self` with all characters escaped with their UTF-16 representation
775 # assert "Aèあ𐏓".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
776 fun escape_to_utf16
: String do
778 for i
in chars
do buf
.append i
.escape_to_utf16
782 # Returns the Unicode char escaped by `self`
784 # assert "\\u0041".from_utf16_escape == 'A'
785 # assert "\\ud800\\udfd3".from_utf16_escape == '𐏓'
786 # assert "\\u00e8".from_utf16_escape == 'è'
787 # assert "\\u3042".from_utf16_escape == 'あ'
788 fun from_utf16_escape
(pos
, ln
: nullable Int): Char do
789 if pos
== null then pos
= 0
790 if ln
== null then ln
= length
- pos
791 if ln
< 6 then return 0xFFFD.code_point
792 var cp
= from_utf16_digit
(pos
+ 2)
793 if cp
< 0xD800 then return cp
.code_point
794 if cp
> 0xDFFF then return cp
.code_point
795 if cp
> 0xDBFF then return 0xFFFD.code_point
796 if ln
== 6 then return 0xFFFD.code_point
797 if ln
< 12 then return 0xFFFD.code_point
799 cp
+= from_utf16_digit
(pos
+ 8)
800 var cplo
= cp
& 0xFFFF
801 if cplo
< 0xDC00 then return 0xFFFD.code_point
802 if cplo
> 0xDFFF then return 0xFFFD.code_point
803 return cp
.from_utf16_surr
.code_point
806 # Returns a UTF-16 escape value
808 # var s = "\\ud800\\udfd3"
809 # assert s.from_utf16_digit(2) == 0xD800
810 # assert s.from_utf16_digit(8) == 0xDFD3
811 fun from_utf16_digit
(pos
: nullable Int): Int do
812 if pos
== null then pos
= 0
813 return to_hex
(pos
, 4)
816 # Encode `self` to percent (or URL) encoding
818 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
819 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
820 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
821 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
822 fun to_percent_encoding
: String
826 for i
in [0..length
[ do
828 if (c
>= '0' and c
<= '9') or
829 (c
>= 'a' and c
<= 'z') or
830 (c
>= 'A' and c
<= 'Z') or
831 c
== '-' or c
== '.' or
836 var bytes
= c
.to_s
.bytes
837 for b
in bytes
do buf
.append
"%{b.to_i.to_hex}"
844 # Decode `self` from percent (or URL) encoding to a clear string
846 # Replace invalid use of '%' with '?'.
848 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
849 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
850 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
851 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
852 # assert "incomplete %".from_percent_encoding == "incomplete ?"
853 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
854 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
855 fun from_percent_encoding
: String
857 var len
= byte_length
858 var has_percent
= false
866 # If no transformation is needed, return self as a string
867 if not has_percent
then return to_s
869 var buf
= new CString(len
)
875 if i
+ 2 >= length
then
876 # What follows % has been cut off
880 var hex_s
= substring
(i
, 2)
882 var hex_i
= hex_s
.to_hex
886 # What follows a % is not Hex
891 else buf
[l
] = c
.ascii
897 return buf
.to_s_unsafe
(l
)
900 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
902 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
904 # 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>
905 fun html_escape
: String
909 for i
in [0..length
[ do
913 else if c
== '<' then
915 else if c
== '>' then
917 else if c
== '"' then
919 else if c
== '\'' then
921 else if c == '/' then
930 # Two pieces of text are equals if thez have the same characters in the same order.
932 # assert "hello" == "hello"
933 # assert "hello" != "HELLO"
934 # assert "hello" == "hel"+"lo"
936 # Things that are not Text are not equal.
939 # assert "9" != ['9']
942 # assert "9".chars.first == '9' # equality of Char
943 # assert "9".chars == ['9'] # equality of Sequence
944 # assert "9".to_i == 9 # equality of Int
947 if o == null then return false
948 if not o isa Text then return false
949 if self.is_same_instance(o) then return true
950 if self.length != o.length then return false
951 return self.chars == o.chars
954 # Lexicographical comparaison
956 # assert "abc" < "xy"
957 # assert "ABC" < "abc"
960 var self_chars = self.chars.iterator
961 var other_chars = other.chars.iterator
963 while self_chars.is_ok and other_chars.is_ok do
964 if self_chars.item < other_chars.item then return true
965 if self_chars.item > other_chars.item then return false
970 if self_chars.is_ok then
977 # Escape string used in labels for graphviz
979 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
980 fun escape_to_dot: String
982 return escape_more_to_c("|\{\}<>")
985 private var hash_cache: nullable Int = null
989 if hash_cache == null then
990 # djb2 hash algorithm
993 for i in [0..length[ do
995 h = (h << 5) + h + char.code_point
1000 return hash_cache.as(not null)
1003 # Format `self` by replacing each `%n` with the `n`th item of `args`
1005 # The character `%` followed by something other than a number are left as is.
1006 # To represent a `%` followed by a number, double the `%`, as in `%%7`.
1008 # assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
1009 # assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"
1010 fun format(args: Object...): String do
1011 var s = new Array[Text]
1015 if self[i] == '%' then
1019 while i < length and self[i].is_numeric do
1023 var ciph_len = i - ciph_st
1024 if ciph_len == 0 then
1025 # What follows '%' is not a number.
1026 s.push substring(curr_st, i - curr_st)
1027 if i < length and self[i] == '%' then
1035 var arg_index = substring(ciph_st, ciph_len).to_i
1036 if arg_index >= args.length then continue
1038 s.push substring(curr_st, fmt_st - curr_st)
1039 s.push args[arg_index].to_s
1046 s.push substring(curr_st, length - curr_st)
1050 # Return the Levenshtein distance between two strings
1053 # assert "abcd".levenshtein_distance("abcd") == 0
1054 # assert "".levenshtein_distance("abcd") == 4
1055 # assert "abcd".levenshtein_distance("") == 4
1056 # assert "abcd".levenshtein_distance("xyz") == 4
1057 # assert "abcd".levenshtein_distance("xbdy") == 3
1059 fun levenshtein_distance(other: String): Int
1061 var slen = self.length
1062 var olen = other.length
1065 if slen == 0 then return olen
1066 if olen == 0 then return slen
1067 if self == other then return 0
1069 # previous row of distances
1070 var v0 = new Array[Int].with_capacity(olen+1)
1072 # current row of distances
1073 var v1 = new Array[Int].with_capacity(olen+1)
1075 for j in [0..olen] do
1076 # prefix insert cost
1080 for i in [0..slen[ do
1082 # prefix delete cost
1085 for j in [0..olen[ do
1087 var cost1 = v1[j] + 1
1089 var cost2 = v0[j + 1] + 1
1090 # same char cost (+0)
1093 if self[i] != other[j] then cost3 += 1
1095 v1[j+1] = cost1.min(cost2).min(cost3)
1099 # * v1 become v0 in the next iteration
1100 # * old v0 is reused as the new v1
1109 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1111 # Basically a high-level synonym of CString::copy_to
1113 # REQUIRE: `n` must be large enough to contain `len` bytes
1115 # var ns = new CString(8)
1116 # "Text is String".copy_to_native(ns, 8, 2, 0)
1117 # assert ns.to_s_unsafe(8) == "xt is St"
1119 fun copy_to_native(dest: CString, n, src_offset, dest_offset: Int) do
1120 var mypos = src_offset
1121 var itspos = dest_offset
1123 dest[itspos] = self.bytes[mypos]
1130 # Packs the content of a string in packs of `ln` chars.
1131 # This variant ensures that only the last element might be smaller than `ln`
1134 # var s = "abcdefghijklmnopqrstuvwxyz"
1135 # assert s.pack_l(4) == ["abcd","efgh","ijkl","mnop","qrst","uvwx","yz"]
1137 fun pack_l(ln: Int): Array[Text] do
1139 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1140 while st < length do
1141 retarr.add(substring(st, ln))
1147 # Packs the content of a string in packs of `ln` chars.
1148 # This variant ensures that only the first element might be smaller than `ln`
1151 # var s = "abcdefghijklmnopqrstuvwxyz"
1152 # assert s.pack_r(4) == ["ab","cdef","ghij","klmn","opqr","stuv","wxyz"]
1154 fun pack_r(ln: Int): Array[Text] do
1156 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1158 retarr.add(substring(st - ln, ln))
1161 return retarr.reversed
1164 # Concatenates self `i` times
1167 # assert "abc" * 4 == "abcabcabcabc"
1168 # assert "abc" * 1 == "abc"
1169 # assert "abc" * 0 == ""
1170 # var b = new Buffer
1173 # assert b == "天地天地天地天地"
1175 fun *(i: Int): SELFTYPE is abstract
1177 # Insert `s` at `pos`.
1180 # assert "helloworld".insert_at(" ", 5) == "hello world"
1181 # var b = new Buffer
1182 # b.append("Hello世界")
1183 # b = b.insert_at(" beautiful ", 5)
1184 # assert b == "Hello beautiful 世界"
1186 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1188 # Returns a reversed version of self
1190 # assert "hello".reversed == "olleh"
1191 # assert "bob".reversed == "bob"
1192 # assert "".reversed == ""
1193 fun reversed: SELFTYPE is abstract
1195 # A upper case version of `self`
1197 # assert "Hello World!".to_upper == "HELLO WORLD!"
1198 fun to_upper: SELFTYPE is abstract
1200 # A lower case version of `self`
1202 # assert "Hello World!".to_lower == "hello world!"
1203 fun to_lower : SELFTYPE is abstract
1205 # Takes a camel case `self` and converts it to snake case
1207 # assert "randomMethodId".to_snake_case == "random_method_id"
1209 # The rules are the following:
1211 # An uppercase is always converted to a lowercase
1213 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1215 # An uppercase that follows a lowercase is prefixed with an underscore
1217 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1219 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1221 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1223 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1225 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1226 fun to_snake_case: SELFTYPE is abstract
1228 # Takes a snake case `self` and converts it to camel case
1230 # assert "random_method_id".to_camel_case == "randomMethodId"
1232 # If the identifier is prefixed by an underscore, the underscore is ignored
1234 # assert "_private_field".to_camel_case == "_privateField"
1236 # If `self` is upper, it is returned unchanged
1238 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1240 # If there are several consecutive underscores, they are considered as a single one
1242 # assert "random__method_id".to_camel_case == "randomMethodId"
1243 fun to_camel_case: SELFTYPE is abstract
1245 # Returns a capitalized `self`
1247 # Letters that follow a letter are lowercased
1248 # Letters that follow a non-letter are upcased.
1250 # If `keep_upper = true`, already uppercase letters are not lowercased.
1252 # SEE : `Char::is_letter` for the definition of letter.
1254 # assert "jAVASCRIPT".capitalized == "Javascript"
1255 # assert "i am root".capitalized == "I Am Root"
1256 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1257 # assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"
1258 fun capitalized(keep_upper: nullable Bool): SELFTYPE do
1259 if length == 0 then return self
1261 var buf = new Buffer.with_cap(length)
1262 buf.capitalize(keep_upper=keep_upper, src=self)
1267 # All kinds of array-based text representations.
1268 abstract class FlatText
1271 # Underlying CString (`char*`)
1273 # Warning: Might be void in some subclasses, be sure to check
1274 # if set before using it.
1275 var items: CString is noinit
1277 # Returns a char* starting at position `first_byte`
1279 # WARNING: If you choose to use this service, be careful of the following.
1281 # Strings and CString are *ideally* always allocated through a Garbage Collector.
1282 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1283 # deallocated at any moment, rendering the pointer returned by this function invalid.
1284 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1285 # (Failure to do so will most certainly result in long and painful debugging hours)
1287 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1288 # then immediately return).
1290 # As always, do not modify the content of the String in C code, if this is what you want
1291 # copy locally the char* as Nit Strings are immutable.
1292 fun fast_cstring: CString is abstract
1294 redef var length = 0
1296 redef var byte_length = 0
1307 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1308 items.copy_to(dest, n, src_offset, dest_offset)
1312 # Abstract class for the SequenceRead compatible
1313 # views on the chars of any Text
1314 private abstract class StringCharView
1315 super SequenceRead[Char]
1319 var target: SELFTYPE
1321 redef fun is_empty do return target.is_empty
1323 redef fun length do return target.length
1325 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1327 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1330 # Abstract class for the SequenceRead compatible
1331 # views on the bytes of any Text
1332 private abstract class StringByteView
1333 super SequenceRead[Byte]
1337 var target: SELFTYPE
1339 redef fun is_empty do return target.is_empty
1341 redef fun length do return target.byte_length
1343 redef fun iterator do return self.iterator_from(0)
1345 redef fun reverse_iterator do return self.reverse_iterator_from(target.byte_length - 1)
1348 # Immutable sequence of characters.
1350 # String objects may be created using literals.
1352 # assert "Hello World!" isa String
1353 abstract class String
1356 redef type SELFTYPE: String is fixed
1358 redef fun to_s do return self
1360 redef fun clone do return self
1362 redef fun to_buffer do return new Buffer.from_text(self)
1364 redef fun to_camel_case do
1365 if self.is_upper then return self
1367 var new_str = new Buffer.with_cap(length)
1373 redef fun to_snake_case do
1374 if self.is_lower then return self
1376 var new_str = new Buffer.with_cap(self.length)
1383 # A mutable sequence of characters.
1384 abstract class Buffer
1387 # Returns an arbitrary subclass of `Buffer` with default parameters
1390 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1391 new with_cap(i: Int) is abstract
1393 # Returns an instance of a subclass of `Buffer` with `t` as content
1394 new from_text(t: Text) do
1395 var ret = new Buffer.with_cap(t.byte_length)
1400 redef type SELFTYPE: Buffer is fixed
1402 # Copy-On-Write flag
1404 # If the `Buffer` was to_s'd
, the next in-place altering
1405 # operation will cause the current `Buffer` to be re-allocated.
1407 # The flag will then be set at `false`.
1408 protected var written
= false
1410 # Modifies the char contained at pos `index`
1412 # DEPRECATED : Use self.chars.[]= instead
1413 fun []=(index
: Int, item
: Char) is abstract
1415 redef fun to_buffer
do return clone
1418 # var b = new Buffer
1419 # b.append("Buffer!")
1424 var cln
= new Buffer.with_cap
(byte_length
)
1429 # Adds a char `c` at the end of self
1431 # DEPRECATED : Use self.chars.add instead
1432 fun add
(c
: Char) is abstract
1436 # var b = new Buffer
1438 # assert not b.is_empty
1441 fun clear
is abstract
1443 # Enlarges the subsequent array containing the chars of self
1444 fun enlarge
(cap
: Int) is abstract
1446 # Adds the content of text `s` at the end of self
1448 # var b = new Buffer
1451 # assert b == "helloworld"
1452 fun append
(s
: Text) is abstract
1454 # `self` is appended in such a way that `self` is repeated `r` times
1456 # var b = new Buffer
1459 # assert b == "hellohellohello"
1460 fun times
(r
: Int) is abstract
1462 # Reverses itself in-place
1464 # var b = new Buffer
1467 # assert b == "olleh"
1468 fun reverse
is abstract
1470 # Changes each lower-case char in `self` by its upper-case variant
1472 # var b = new Buffer
1473 # b.append("Hello World!")
1475 # assert b == "HELLO WORLD!"
1476 fun upper
is abstract
1478 # Changes each upper-case char in `self` by its lower-case variant
1480 # var b = new Buffer
1481 # b.append("Hello World!")
1483 # assert b == "hello world!"
1484 fun lower
is abstract
1486 # Capitalizes each word in `self`
1488 # Letters that follow a letter are lowercased
1489 # Letters that follow a non-letter are upcased.
1491 # If `keep_upper = true`, uppercase letters are not lowercased.
1493 # When `src` is specified, this method reads from `src` instead of `self`
1494 # but it still writes the result to the beginning of `self`.
1495 # This requires `self` to have the capacity to receive all of the
1496 # capitalized content of `src`.
1498 # SEE: `Char::is_letter` for the definition of a letter.
1500 # var b = new FlatBuffer.from("jAVAsCriPt")
1502 # assert b == "Javascript"
1503 # b = new FlatBuffer.from("i am root")
1505 # assert b == "I Am Root"
1506 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1508 # assert b == "Ab_C -Ab0C Ab\nC"
1510 # b = new FlatBuffer.from("12345")
1511 # b.capitalize(src="foo")
1512 # assert b == "Foo45"
1514 # b = new FlatBuffer.from("preserve my ACRONYMS")
1515 # b.capitalize(keep_upper=true)
1516 # assert b == "Preserve My ACRONYMS"
1517 fun capitalize
(keep_upper
: nullable Bool, src
: nullable Text) do
1518 src
= src
or else self
1519 var length
= src
.length
1520 if length
== 0 then return
1521 keep_upper
= keep_upper
or else false
1523 var c
= src
[0].to_upper
1526 for i
in [1 .. length
[ do
1529 if prev
.is_letter
then
1533 self[i
] = c
.to_lower
1536 self[i
] = c
.to_upper
1541 # In Buffers, the internal sequence of character is mutable
1542 # Thus, `chars` can be used to modify the buffer.
1543 redef fun chars
: Sequence[Char] is abstract
1545 # Appends `length` chars from `s` starting at index `from`
1548 # var b = new Buffer
1549 # b.append_substring("abcde", 1, 2)
1551 # b.append_substring("vwxyz", 2, 3)
1552 # assert b == "bcxyz"
1553 # b.append_substring("ABCDE", 4, 300)
1554 # assert b == "bcxyzE"
1555 # b.append_substring("VWXYZ", 400, 1)
1556 # assert b == "bcxyzE"
1558 fun append_substring
(s
: Text, from
, length
: Int) do
1564 if (length
+ from
) > ln
then length
= ln
- from
1565 if length
<= 0 then return
1566 append_substring_impl
(s
, from
, length
)
1569 # Unsafe version of `append_substring` for performance
1571 # NOTE: Use only if sure about `from` and `length`, no checks
1572 # or bound recalculation is done
1573 fun append_substring_impl
(s
: Text, from
, length
: Int) do
1574 var max
= from
+ length
1575 for i
in [from
.. max
[ do add s
[i
]
1579 var ret
= new Buffer.with_cap
(byte_length
* i
)
1580 for its
in [0 .. i
[ do ret
.append
self
1584 redef fun insert_at
(s
, pos
) do
1585 var obuf
= new Buffer.with_cap
(byte_length
+ s
.byte_length
)
1586 obuf
.append_substring
(self, 0, pos
)
1588 obuf
.append_substring
(self, pos
, length
- pos
)
1592 # Inserts `s` at position `pos`
1595 # var b = new Buffer
1597 # b.insert(" nit ", 3)
1598 # assert b == "美しい nit 世界"
1600 fun insert
(s
: Text, pos
: Int) is abstract
1602 # Inserts `c` at position `pos`
1605 # var b = new Buffer
1607 # b.insert_char(' ', 3)
1608 # assert b == "美しい 世界"
1610 fun insert_char
(c
: Char, pos
: Int) is abstract
1612 # Removes a substring from `self` at position `pos`
1614 # NOTE: `length` defaults to 1, expressed in chars
1617 # var b = new Buffer
1618 # b.append("美しい 世界")
1620 # assert b == "美しい世界"
1624 fun remove_at
(pos
: Int, length
: nullable Int) is abstract
1626 redef fun reversed
do
1632 redef fun to_upper
do
1638 redef fun to_lower
do
1644 redef fun to_snake_case
do
1650 # Takes a camel case `self` and converts it to snake case
1652 # SEE: `to_snake_case`
1654 if self.is_lower
then return
1655 var prev_is_lower
= false
1656 var prev_is_upper
= false
1661 if char
.is_lower
then
1662 prev_is_lower
= true
1663 prev_is_upper
= false
1664 else if char
.is_upper
then
1665 if prev_is_lower
then
1668 else if prev_is_upper
and i
+ 1 < length
and self[i
+ 1].is_lower
then
1672 self[i
] = char
.to_lower
1673 prev_is_lower
= false
1674 prev_is_upper
= true
1676 prev_is_lower
= false
1677 prev_is_upper
= false
1683 redef fun to_camel_case
1690 # Takes a snake case `self` and converts it to camel case
1692 # SEE: `to_camel_case`
1694 if is_upper
then return
1696 var underscore_count
= 0
1699 while pos
< length
do
1700 var char
= self[pos
]
1702 underscore_count
+= 1
1703 else if underscore_count
> 0 then
1704 pos
-= underscore_count
1705 remove_at
(pos
, underscore_count
)
1706 self[pos
] = char
.to_upper
1707 underscore_count
= 0
1711 if underscore_count
> 0 then remove_at
(pos
- underscore_count
- 1, underscore_count
)
1714 redef fun capitalized
(keep_upper
) do
1715 if length
== 0 then return self
1717 var buf
= new Buffer.with_cap
(byte_length
)
1718 buf
.capitalize
(keep_upper
=keep_upper
, src
=self)
1723 # View for chars on Buffer objects, extends Sequence
1724 # for mutation operations
1725 private abstract class BufferCharView
1726 super StringCharView
1727 super Sequence[Char]
1729 redef type SELFTYPE: Buffer
1733 # View for bytes on Buffer objects, extends Sequence
1734 # for mutation operations
1735 private abstract class BufferByteView
1736 super StringByteView
1738 redef type SELFTYPE: Buffer
1742 # User readable representation of `self`.
1743 fun to_s
: String do return inspect
1745 # The class name of the object in CString format.
1746 private fun native_class_name
: CString is intern
1748 # The class name of the object.
1750 # assert 5.class_name == "Int"
1751 fun class_name
: String do return native_class_name
.to_s
1753 # Developer readable representation of `self`.
1754 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1757 return "<{inspect_head}>"
1760 # Return "CLASSNAME:#OBJECTID".
1761 # This function is mainly used with the redefinition of the inspect method
1762 protected fun inspect_head
: String
1764 return "{class_name}:#{object_id.to_hex}"
1769 # assert true.to_s == "true"
1770 # assert false.to_s == "false"
1782 # C function to calculate the length of the `CString` to receive `self`
1783 private fun byte_to_s_len
: Int `{
1784 return snprintf(NULL, 0, "0x%02x", self);
1787 # C function to convert an nit Int to a CString (char*)
1788 private fun native_byte_to_s
(nstr
: CString, strlen
: Int) `{
1789 snprintf(nstr, strlen, "0x%02x", self);
1792 # Displayable byte in its hexadecimal form (0x..)
1794 # assert 1.to_b.to_s == "0x01"
1795 # assert (-123).to_b.to_s == "0x85"
1797 var nslen
= byte_to_s_len
1798 var ns
= new CString(nslen
+ 1)
1800 native_byte_to_s
(ns
, nslen
+ 1)
1801 return ns
.to_s_unsafe
(nslen
)
1807 # Wrapper of strerror C function
1808 private fun strerror_ext
: CString `{ return strerror((int)self); `}
1810 # Returns a string describing error number
1811 fun strerror: String do return strerror_ext.to_s
1813 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if negative).
1814 # assume < to_c max const of char
1815 private fun fill_buffer(s: Buffer, base: Int)
1822 else if self == 0 then
1829 var pos = digit_count(base) - 1
1830 while pos >= 0 and n > 0 do
1831 s.chars[pos] = (n % base).to_c
1837 # C function to calculate the length of the `CString` to receive `self`
1838 private fun int_to_s_len: Int `{
1839 return snprintf
(NULL, 0, "%ld", self);
1842 # C function to convert an nit Int to a CString (char*)
1843 private fun native_int_to_s(nstr: CString, strlen: Int) `{
1844 snprintf
(nstr
, strlen
, "%ld", self);
1847 # String representation of `self` in the given `base
`
1850 # assert 15.to_base(10) == "15"
1851 # assert 15.to_base(16) == "f"
1852 # assert 15.to_base(2) == "1111"
1853 # assert (-10).to_base(3) == "-101"
1855 fun to_base(base: Int): String
1857 var l = digit_count(base)
1860 for x in [0..l[ do s.add(' ')
1861 fill_buffer(s, base)
1866 # return displayable int in hexadecimal
1868 # assert 1.to_hex == "1"
1869 # assert (-255).to_hex == "-ff"
1870 fun to_hex: String do return to_base(16)
1874 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1876 # assert 12.34.to_s == "12.34"
1877 # assert (-0120.030).to_s == "-120.03"
1879 # see `to_precision
` for a custom precision.
1881 var str = to_precision( 3 )
1882 if is_inf != 0 or is_nan then return str
1883 var len = str.length
1884 for i in [0..len-1] do
1886 var c = str.chars[j]
1889 else if c == '.' then
1890 return str.substring( 0, j+2 )
1892 return str.substring( 0, j+1 )
1898 # `String` representation of `self` with the given number of `decimals
`
1900 # assert 12.345.to_precision(0) == "12"
1901 # assert 12.345.to_precision(3) == "12.345"
1902 # assert (-12.345).to_precision(3) == "-12.345"
1903 # assert (-0.123).to_precision(3) == "-0.123"
1904 # assert 0.999.to_precision(2) == "1.00"
1905 # assert 0.999.to_precision(4) == "0.9990"
1906 fun to_precision(decimals: Int): String
1908 if is_nan then return "nan"
1910 var isinf = self.is_inf
1913 else if isinf == -1 then
1917 if decimals == 0 then return self.to_i.to_s
1919 for i in [0..decimals[ do f = f * 10.0
1926 if i == 0 then return "0." + "0"*decimals
1928 # Prepare both parts of the float, before and after the "."
1933 if sl > decimals then
1934 # Has something before the "."
1935 p1 = s.substring(0, sl-decimals)
1936 p2 = s.substring(sl-decimals, decimals)
1939 p2 = "0"*(decimals-sl) + s
1942 if i < 0 then p1 = "-" + p1
1944 return p1 + "." + p2
1950 # Returns a sequence with the UTF-8 bytes of `self`
1952 # assert 'a'.bytes == [0x61u8]
1953 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1954 fun bytes: SequenceRead[Byte] do return to_s.bytes
1956 # Is `self` an UTF-16 surrogate pair ?
1957 fun is_surrogate: Bool do
1959 return cp >= 0xD800 and cp <= 0xDFFF
1962 # Is `self` a UTF-16 high surrogate ?
1963 fun is_hi_surrogate: Bool do
1965 return cp >= 0xD800 and cp <= 0xDBFF
1968 # Is `self` a UTF-16 low surrogate ?
1969 fun is_lo_surrogate: Bool do
1971 return cp >= 0xDC00 and cp <= 0xDFFF
1974 # Length of `self` in a UTF-8 String
1975 fun u8char_len: Int do
1976 var c = self.code_point
1977 if c < 0x80 then return 1
1978 if c <= 0x7FF then return 2
1979 if c <= 0xFFFF then return 3
1980 if c <= 0x10FFFF then return 4
1981 # Bad character format
1985 # assert 'x'.to_s == "x"
1988 var ns = new CString(ln + 1)
1990 return ns.to_s_unsafe(ln)
1993 # Returns `self` escaped to UTF-16
1995 # i.e. Represents `self`.`code_point
` using UTF-16 codets escaped
1998 # assert 'A'.escape_to_utf16 == "\\u0041"
1999 # assert 'è'.escape_to_utf16 == "\\u00e8"
2000 # assert 'あ'.escape_to_utf16 == "\\u3042"
2001 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
2002 fun escape_to_utf16: String do
2005 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
2006 buf = new Buffer.with_cap(6)
2007 buf.append("\\u0000")
2010 for i in hx.chars.reverse_iterator do
2015 buf = new Buffer.with_cap(12)
2016 buf.append("\\u0000\\u0000")
2017 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
2018 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
2033 private fun u8char_tos(r: CString, len: Int) `{
2040 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
2041 r
[1] = 0x80 | (self & 0x3F);
2044 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
2045 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
2046 r
[2] = 0x80 | (self & 0x3F);
2049 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
2050 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
2051 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
2052 r
[3] = 0x80 | (self & 0x3F);
2057 # Returns true if the char is a numerical digit
2059 # assert '0'.is_numeric
2060 # assert '9'.is_numeric
2061 # assert not 'a'.is_numeric
2062 # assert not '?'.is_numeric
2064 # FIXME: Works on ASCII-range only
2065 fun is_numeric: Bool
2067 return self >= '0' and self <= '9'
2070 # Returns true if the char is an alpha digit
2072 # assert 'a'.is_alpha
2073 # assert 'Z'.is_alpha
2074 # assert not '0'.is_alpha
2075 # assert not '?'.is_alpha
2077 # FIXME: Works on ASCII-range only
2080 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2083 # Is `self` an hexadecimal digit ?
2085 # assert 'A'.is_hexdigit
2086 # assert not 'G'.is_hexdigit
2087 # assert 'a'.is_hexdigit
2088 # assert not 'g'.is_hexdigit
2089 # assert '5'.is_hexdigit
2090 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
2091 (self >= 'a' and self <= 'f')
2093 # Returns true if the char is an alpha or a numeric digit
2095 # assert 'a'.is_alphanumeric
2096 # assert 'Z'.is_alphanumeric
2097 # assert '0'.is_alphanumeric
2098 # assert '9'.is_alphanumeric
2099 # assert not '?'.is_alphanumeric
2101 # FIXME: Works on ASCII-range only
2102 fun is_alphanumeric: Bool
2104 return self.is_numeric or self.is_alpha
2107 # Returns `self` to its int value
2109 # REQUIRE: `is_hexdigit
`
2110 fun from_hex: Int do
2111 if self >= '0' and self <= '9' then return code_point - 0x30
2112 if self >= 'A' and self <= 'F' then return code_point - 0x37
2113 if self >= 'a' and self <= 'f' then return code_point - 0x57
2114 # Happens if self is not a hexdigit
2115 assert self.is_hexdigit
2116 # To make flow analysis happy
2121 redef class Collection[E]
2122 # String representation of the content of the collection.
2124 # The standard representation is the list of elements separated with commas.
2127 # assert [1,2,3].to_s == "[1,2,3]"
2128 # assert [1..3].to_s == "[1,2,3]"
2129 # assert (new Array[Int]).to_s == "[]" # empty collection
2132 # Subclasses may return a more specific string representation.
2135 return "[" + join(",") + "]"
2138 # Concatenate elements without separators
2141 # assert [1,2,3].plain_to_s == "123"
2142 # assert [11..13].plain_to_s == "111213"
2143 # assert (new Array[Int]).plain_to_s == "" # empty collection
2145 fun plain_to_s: String
2148 for e in self do if e != null then s.append(e.to_s)
2152 # Concatenate and separate each elements with `separator
`.
2154 # Only concatenate if `separator
== null`.
2156 # assert [1, 2, 3].join(":") == "1:2:3"
2157 # assert [1..3].join(":") == "1:2:3"
2158 # assert [1..3].join == "123"
2160 # if `last_separator
` is given, then it is used to separate the last element.
2162 # assert [1, 2, 3, 4].join(", ", " and ") == "1, 2, 3 and 4"
2163 fun join(separator: nullable Text, last_separator: nullable Text): String
2165 if is_empty then return ""
2167 var s = new Buffer # Result
2172 if e != null then s.append(e.to_s)
2174 if last_separator == null then last_separator = separator
2176 # Concat other items
2182 if separator != null then s.append(separator)
2184 if last_separator != null then s.append(last_separator)
2186 if e != null then s.append(e.to_s)
2192 redef class Map[K,V]
2193 # Concatenate couples of key value.
2194 # Key and value are separated by `couple_sep
`.
2195 # Couples are separated by `sep
`.
2197 # var m = new HashMap[Int, String]
2200 # assert m.join("; ", "=") == "1=one; 10=ten"
2201 fun join(sep, couple_sep: String): String is abstract
2205 private var args_cache: nullable Sequence[String] = null
2207 # The arguments of the program as given by the OS
2208 fun program_args: Sequence[String]
2210 if _args_cache == null then init_args
2211 return _args_cache.as(not null)
2214 # The name of the program as given by the OS
2215 fun program_name: String
2217 return native_argv(0).to_s
2220 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2221 private fun init_args
2223 var argc = native_argc
2224 var args = new Array[String].with_capacity(0)
2227 args[i-1] = native_argv(i).to_s
2233 # First argument of the main C function.
2234 private fun native_argc: Int is intern
2236 # Second argument of the main C function.
2237 private fun native_argv(i: Int): CString is intern
2240 # Comparator that efficienlty use `to_s
` to compare things
2242 # The comparaison call `to_s
` on object and use the result to order things.
2244 # var a = [1, 2, 3, 10, 20]
2245 # (new CachedAlphaComparator).sort(a)
2246 # assert a == [1, 10, 2, 20, 3]
2248 # Internally the result of `to_s
` is cached in a HashMap to counter
2249 # uneficient implementation of `to_s
`.
2251 # Note: it caching is not usefull, see `alpha_comparator
`
2252 class CachedAlphaComparator
2254 redef type COMPARED: Object
2256 private var cache = new HashMap[Object, String]
2258 private fun do_to_s(a: Object): String do
2259 if cache.has_key(a) then return cache[a]
2265 redef fun compare(a, b) do
2266 return do_to_s(a) <=> do_to_s(b)
2270 # see `alpha_comparator
`
2271 private class AlphaComparator
2273 redef fun compare(a, b) do
2274 if a == b then return 0
2275 if a == null then return -1
2276 if b == null then return 1
2277 return a.to_s <=> b.to_s
2281 # Stateless comparator that naively use `to_s
` to compare things.
2283 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2284 # on a single instace. See `CachedAlphaComparator` as an alternative.
2286 # var a = [1, 2, 3, 10, 20]
2287 # alpha_comparator.sort(a)
2288 # assert a == [1, 10, 2, 20, 3]
2289 fun alpha_comparator: Comparator do return once new AlphaComparator
2291 # The arguments of the program as given by the OS
2292 fun args: Sequence[String]
2294 return sys.program_args
2298 # Get a `String` from the data at `self` copied into Nit memory
2300 # Require: `self` is a null-terminated string.
2301 fun to_s_with_copy: String is abstract
2303 # Get a `String` from `length
` bytes at `self`
2305 # The result may point to the data at `self` or
2306 # it may make a copy in Nit controlled memory.
2307 # This method should only be used when `self` was allocated by the Nit GC,
2308 # or when manually controlling the deallocation of `self`.
2309 fun to_s_with_length(length: Int): String is abstract
2311 # Get a `String` from the raw `length
` bytes at `self`
2313 # The default value of `length
` is the number of bytes before
2314 # the first null character.
2316 # The created `String` points to the data at `self`.
2317 # This method should be used when `self` was allocated by the Nit GC,
2318 # or when manually controlling the deallocation of `self`.
2320 # /!\: This service does not clean the items for compliance with UTF-8,
2321 # use only when the data has already been verified as valid UTF-8.
2322 fun to_s_unsafe(length: nullable Int): String is abstract
2324 # Get a `String` from the raw `byte_length
` bytes at `self` with `unilen
` Unicode characters
2326 # The created `String` points to the data at `self`.
2327 # This method should be used when `self` was allocated by the Nit GC,
2328 # or when manually controlling the deallocation of `self`.
2330 # /!\: This service does not clean the items for compliance with UTF-8,
2331 # use only when the data has already been verified as valid UTF-8.
2333 # SEE: `abstract_text
::Text` for more info on the difference
2334 # between `Text::byte_length
` and `Text::length
`.
2335 fun to_s_full(byte_length, unilen: Int): String is abstract
2337 # Copies the content of `src
` to `self`
2339 # NOTE: `self` must be large enough to withold `self.byte_length
` bytes
2340 fun fill_from(src: Text) do src.copy_to_native(self, src.byte_length, 0, 0)
2343 redef class NativeArray[E]
2344 # Join all the elements using `to_s
`
2346 # REQUIRE: `self isa NativeArray[String]`
2347 # REQUIRE: all elements are initialized
2348 fun native_to_s: String is abstract