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).to_u32
793 if cp
< 0xD800u
32 then return cp
.code_point
794 if cp
> 0xDFFFu
32 then return cp
.code_point
795 if cp
> 0xDBFFu
32 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).to_u32
800 var cplo
= cp
& 0xFFFFu
32
801 if cplo
< 0xDC00u
32 then return 0xFFFD.code_point
802 if cplo
> 0xDFFFu
32 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 # Invalid '%' are not decoded.
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 # assert "%1 %A %C3%A9A9".from_percent_encoding == "%1 %A éA9"
856 fun from_percent_encoding
: String
858 var len
= byte_length
859 var has_percent
= false
867 # If no transformation is needed, return self as a string
868 if not has_percent
then return to_s
870 var buf
= new CString(len
)
876 if i
+ 2 >= length
then
877 # What follows % has been cut off
881 var hex_s
= substring
(i
, 2)
883 var hex_i
= hex_s
.to_hex
887 # What follows a % is not Hex
892 else buf
[l
] = c
.ascii
898 return buf
.to_s_unsafe
(l
, copy
=false)
901 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
903 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
905 # 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>
906 fun html_escape
: String
910 for i
in [0..length
[ do
914 else if c
== '<' then
916 else if c
== '>' then
918 else if c
== '"' then
920 else if c
== '\'' then
922 else if c == '/' then
931 # Two pieces of text are equals if thez have the same characters in the same order.
933 # assert "hello" == "hello"
934 # assert "hello" != "HELLO"
935 # assert "hello" == "hel"+"lo"
937 # Things that are not Text are not equal.
940 # assert "9" != ['9']
943 # assert "9".chars.first == '9' # equality of Char
944 # assert "9".chars == ['9'] # equality of Sequence
945 # assert "9".to_i == 9 # equality of Int
948 if o == null then return false
949 if not o isa Text then return false
950 if self.is_same_instance(o) then return true
951 if self.length != o.length then return false
952 return self.chars == o.chars
955 # Lexicographical comparaison
957 # assert "abc" < "xy"
958 # assert "ABC" < "abc"
961 var self_chars = self.chars.iterator
962 var other_chars = other.chars.iterator
964 while self_chars.is_ok and other_chars.is_ok do
965 if self_chars.item < other_chars.item then return true
966 if self_chars.item > other_chars.item then return false
971 if self_chars.is_ok then
978 # Escape string used in labels for graphviz
980 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
981 fun escape_to_dot: String
983 return escape_more_to_c("|\{\}<>")
986 private var hash_cache: nullable Int = null
990 if hash_cache == null then
991 # djb2 hash algorithm
994 for i in [0..length[ do
996 h = (h << 5) + h + char.code_point
1001 return hash_cache.as(not null)
1004 # Format `self` by replacing each `%n` with the `n`th item of `args`
1006 # The character `%` followed by something other than a number are left as is.
1007 # To represent a `%` followed by a number, double the `%`, as in `%%7`.
1009 # assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
1010 # assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"
1011 fun format(args: Object...): String do
1012 var s = new Array[Text]
1016 if self[i] == '%' then
1020 while i < length and self[i].is_numeric do
1024 var ciph_len = i - ciph_st
1025 if ciph_len == 0 then
1026 # What follows '%' is not a number.
1027 s.push substring(curr_st, i - curr_st)
1028 if i < length and self[i] == '%' then
1036 var arg_index = substring(ciph_st, ciph_len).to_i
1037 if arg_index >= args.length then continue
1039 s.push substring(curr_st, fmt_st - curr_st)
1040 s.push args[arg_index].to_s
1047 s.push substring(curr_st, length - curr_st)
1051 # Return the Levenshtein distance between two strings
1054 # assert "abcd".levenshtein_distance("abcd") == 0
1055 # assert "".levenshtein_distance("abcd") == 4
1056 # assert "abcd".levenshtein_distance("") == 4
1057 # assert "abcd".levenshtein_distance("xyz") == 4
1058 # assert "abcd".levenshtein_distance("xbdy") == 3
1060 fun levenshtein_distance(other: String): Int
1062 var slen = self.length
1063 var olen = other.length
1066 if slen == 0 then return olen
1067 if olen == 0 then return slen
1068 if self == other then return 0
1070 # previous row of distances
1071 var v0 = new Array[Int].with_capacity(olen+1)
1073 # current row of distances
1074 var v1 = new Array[Int].with_capacity(olen+1)
1076 for j in [0..olen] do
1077 # prefix insert cost
1081 for i in [0..slen[ do
1083 # prefix delete cost
1086 for j in [0..olen[ do
1088 var cost1 = v1[j] + 1
1090 var cost2 = v0[j + 1] + 1
1091 # same char cost (+0)
1094 if self[i] != other[j] then cost3 += 1
1096 v1[j+1] = cost1.min(cost2).min(cost3)
1100 # * v1 become v0 in the next iteration
1101 # * old v0 is reused as the new v1
1110 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1112 # Basically a high-level synonym of CString::copy_to
1114 # REQUIRE: `n` must be large enough to contain `len` bytes
1116 # var ns = new CString(8)
1117 # "Text is String".copy_to_native(ns, 8, 2, 0)
1118 # assert ns.to_s_with_length(8) == "xt is St"
1120 fun copy_to_native(dest: CString, n, src_offset, dest_offset: Int) do
1121 var mypos = src_offset
1122 var itspos = dest_offset
1124 dest[itspos] = self.bytes[mypos]
1131 # Packs the content of a string in packs of `ln` chars.
1132 # This variant ensures that only the last element might be smaller than `ln`
1135 # var s = "abcdefghijklmnopqrstuvwxyz"
1136 # assert s.pack_l(4) == ["abcd","efgh","ijkl","mnop","qrst","uvwx","yz"]
1138 fun pack_l(ln: Int): Array[Text] do
1140 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1141 while st < length do
1142 retarr.add(substring(st, ln))
1148 # Packs the content of a string in packs of `ln` chars.
1149 # This variant ensures that only the first element might be smaller than `ln`
1152 # var s = "abcdefghijklmnopqrstuvwxyz"
1153 # assert s.pack_r(4) == ["ab","cdef","ghij","klmn","opqr","stuv","wxyz"]
1155 fun pack_r(ln: Int): Array[Text] do
1157 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1159 retarr.add(substring(st - ln, ln))
1162 return retarr.reversed
1165 # Concatenates self `i` times
1168 # assert "abc" * 4 == "abcabcabcabc"
1169 # assert "abc" * 1 == "abc"
1170 # assert "abc" * 0 == ""
1171 # var b = new Buffer
1174 # assert b == "天地天地天地天地"
1176 fun *(i: Int): SELFTYPE is abstract
1178 # Insert `s` at `pos`.
1181 # assert "helloworld".insert_at(" ", 5) == "hello world"
1182 # var b = new Buffer
1183 # b.append("Hello世界")
1184 # b = b.insert_at(" beautiful ", 5)
1185 # assert b == "Hello beautiful 世界"
1187 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1189 # Returns a reversed version of self
1191 # assert "hello".reversed == "olleh"
1192 # assert "bob".reversed == "bob"
1193 # assert "".reversed == ""
1194 fun reversed: SELFTYPE is abstract
1196 # A upper case version of `self`
1198 # assert "Hello World!".to_upper == "HELLO WORLD!"
1199 fun to_upper: SELFTYPE is abstract
1201 # A lower case version of `self`
1203 # assert "Hello World!".to_lower == "hello world!"
1204 fun to_lower : SELFTYPE is abstract
1206 # Takes a camel case `self` and converts it to snake case
1208 # assert "randomMethodId".to_snake_case == "random_method_id"
1210 # The rules are the following:
1212 # An uppercase is always converted to a lowercase
1214 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1216 # An uppercase that follows a lowercase is prefixed with an underscore
1218 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1220 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1222 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1224 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1226 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1227 fun to_snake_case: SELFTYPE is abstract
1229 # Takes a snake case `self` and converts it to camel case
1231 # assert "random_method_id".to_camel_case == "randomMethodId"
1233 # If the identifier is prefixed by an underscore, the underscore is ignored
1235 # assert "_private_field".to_camel_case == "_privateField"
1237 # If `self` is upper, it is returned unchanged
1239 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1241 # If there are several consecutive underscores, they are considered as a single one
1243 # assert "random__method_id".to_camel_case == "randomMethodId"
1244 fun to_camel_case: SELFTYPE is abstract
1246 # Returns a capitalized `self`
1248 # Letters that follow a letter are lowercased
1249 # Letters that follow a non-letter are upcased.
1251 # If `keep_upper = true`, already uppercase letters are not lowercased.
1253 # SEE : `Char::is_letter` for the definition of letter.
1255 # assert "jAVASCRIPT".capitalized == "Javascript"
1256 # assert "i am root".capitalized == "I Am Root"
1257 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1258 # assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"
1259 fun capitalized(keep_upper: nullable Bool): SELFTYPE do
1260 if length == 0 then return self
1262 var buf = new Buffer.with_cap(length)
1263 buf.capitalize(keep_upper=keep_upper, src=self)
1268 # All kinds of array-based text representations.
1269 abstract class FlatText
1272 # Underlying CString (`char*`)
1274 # Warning: Might be void in some subclasses, be sure to check
1275 # if set before using it.
1276 var items: CString is noinit
1278 # Returns a char* starting at position `first_byte`
1280 # WARNING: If you choose to use this service, be careful of the following.
1282 # Strings and CString are *ideally* always allocated through a Garbage Collector.
1283 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1284 # deallocated at any moment, rendering the pointer returned by this function invalid.
1285 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1286 # (Failure to do so will most certainly result in long and painful debugging hours)
1288 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1289 # then immediately return).
1291 # As always, do not modify the content of the String in C code, if this is what you want
1292 # copy locally the char* as Nit Strings are immutable.
1293 fun fast_cstring: CString is abstract
1295 redef var length = 0
1297 redef var byte_length = 0
1308 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1309 items.copy_to(dest, n, src_offset, dest_offset)
1313 # Abstract class for the SequenceRead compatible
1314 # views on the chars of any Text
1315 private abstract class StringCharView
1316 super SequenceRead[Char]
1320 var target: SELFTYPE
1322 redef fun is_empty do return target.is_empty
1324 redef fun length do return target.length
1326 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1328 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1331 # Abstract class for the SequenceRead compatible
1332 # views on the bytes of any Text
1333 private abstract class StringByteView
1334 super SequenceRead[Byte]
1338 var target: SELFTYPE
1340 redef fun is_empty do return target.is_empty
1342 redef fun length do return target.byte_length
1344 redef fun iterator do return self.iterator_from(0)
1346 redef fun reverse_iterator do return self.reverse_iterator_from(target.byte_length - 1)
1349 # Immutable sequence of characters.
1351 # String objects may be created using literals.
1353 # assert "Hello World!" isa String
1354 abstract class String
1357 redef type SELFTYPE: String is fixed
1359 redef fun to_s do return self
1361 redef fun clone do return self
1363 redef fun to_buffer do return new Buffer.from_text(self)
1365 redef fun to_camel_case do
1366 if self.is_upper then return self
1368 var new_str = new Buffer.with_cap(length)
1374 redef fun to_snake_case do
1375 if self.is_lower then return self
1377 var new_str = new Buffer.with_cap(self.length)
1384 # A mutable sequence of characters.
1385 abstract class Buffer
1388 # Returns an arbitrary subclass of `Buffer` with default parameters
1391 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1392 new with_cap(i: Int) is abstract
1394 # Returns an instance of a subclass of `Buffer` with `t` as content
1395 new from_text(t: Text) do
1396 var ret = new Buffer.with_cap(t.byte_length)
1401 redef type SELFTYPE: Buffer is fixed
1403 # Copy-On-Write flag
1405 # If the `Buffer` was to_s'd
, the next in-place altering
1406 # operation will cause the current `Buffer` to be re-allocated.
1408 # The flag will then be set at `false`.
1409 protected var written
= false
1411 # Modifies the char contained at pos `index`
1413 # DEPRECATED : Use self.chars.[]= instead
1414 fun []=(index
: Int, item
: Char) is abstract
1416 redef fun to_buffer
do return clone
1419 # var b = new Buffer
1420 # b.append("Buffer!")
1425 var cln
= new Buffer.with_cap
(byte_length
)
1430 # Adds a char `c` at the end of self
1432 # DEPRECATED : Use self.chars.add instead
1433 fun add
(c
: Char) is abstract
1437 # var b = new Buffer
1439 # assert not b.is_empty
1442 fun clear
is abstract
1444 # Enlarges the subsequent array containing the chars of self
1445 fun enlarge
(cap
: Int) is abstract
1447 # Adds the content of text `s` at the end of self
1449 # var b = new Buffer
1452 # assert b == "helloworld"
1453 fun append
(s
: Text) is abstract
1455 # `self` is appended in such a way that `self` is repeated `r` times
1457 # var b = new Buffer
1460 # assert b == "hellohellohello"
1461 fun times
(r
: Int) is abstract
1463 # Reverses itself in-place
1465 # var b = new Buffer
1468 # assert b == "olleh"
1469 fun reverse
is abstract
1471 # Changes each lower-case char in `self` by its upper-case variant
1473 # var b = new Buffer
1474 # b.append("Hello World!")
1476 # assert b == "HELLO WORLD!"
1477 fun upper
is abstract
1479 # Changes each upper-case char in `self` by its lower-case variant
1481 # var b = new Buffer
1482 # b.append("Hello World!")
1484 # assert b == "hello world!"
1485 fun lower
is abstract
1487 # Capitalizes each word in `self`
1489 # Letters that follow a letter are lowercased
1490 # Letters that follow a non-letter are upcased.
1492 # If `keep_upper = true`, uppercase letters are not lowercased.
1494 # When `src` is specified, this method reads from `src` instead of `self`
1495 # but it still writes the result to the beginning of `self`.
1496 # This requires `self` to have the capacity to receive all of the
1497 # capitalized content of `src`.
1499 # SEE: `Char::is_letter` for the definition of a letter.
1501 # var b = new FlatBuffer.from("jAVAsCriPt")
1503 # assert b == "Javascript"
1504 # b = new FlatBuffer.from("i am root")
1506 # assert b == "I Am Root"
1507 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1509 # assert b == "Ab_C -Ab0C Ab\nC"
1511 # b = new FlatBuffer.from("12345")
1512 # b.capitalize(src="foo")
1513 # assert b == "Foo45"
1515 # b = new FlatBuffer.from("preserve my ACRONYMS")
1516 # b.capitalize(keep_upper=true)
1517 # assert b == "Preserve My ACRONYMS"
1518 fun capitalize
(keep_upper
: nullable Bool, src
: nullable Text) do
1519 src
= src
or else self
1520 var length
= src
.length
1521 if length
== 0 then return
1522 keep_upper
= keep_upper
or else false
1524 var c
= src
[0].to_upper
1527 for i
in [1 .. length
[ do
1530 if prev
.is_letter
then
1534 self[i
] = c
.to_lower
1537 self[i
] = c
.to_upper
1542 # In Buffers, the internal sequence of character is mutable
1543 # Thus, `chars` can be used to modify the buffer.
1544 redef fun chars
: Sequence[Char] is abstract
1546 # Appends `length` chars from `s` starting at index `from`
1549 # var b = new Buffer
1550 # b.append_substring("abcde", 1, 2)
1552 # b.append_substring("vwxyz", 2, 3)
1553 # assert b == "bcxyz"
1554 # b.append_substring("ABCDE", 4, 300)
1555 # assert b == "bcxyzE"
1556 # b.append_substring("VWXYZ", 400, 1)
1557 # assert b == "bcxyzE"
1559 fun append_substring
(s
: Text, from
, length
: Int) do
1565 if (length
+ from
) > ln
then length
= ln
- from
1566 if length
<= 0 then return
1567 append_substring_impl
(s
, from
, length
)
1570 # Unsafe version of `append_substring` for performance
1572 # NOTE: Use only if sure about `from` and `length`, no checks
1573 # or bound recalculation is done
1574 fun append_substring_impl
(s
: Text, from
, length
: Int) do
1575 var max
= from
+ length
1576 for i
in [from
.. max
[ do add s
[i
]
1580 var ret
= new Buffer.with_cap
(byte_length
* i
)
1581 for its
in [0 .. i
[ do ret
.append
self
1585 redef fun insert_at
(s
, pos
) do
1586 var obuf
= new Buffer.with_cap
(byte_length
+ s
.byte_length
)
1587 obuf
.append_substring
(self, 0, pos
)
1589 obuf
.append_substring
(self, pos
, length
- pos
)
1593 # Inserts `s` at position `pos`
1596 # var b = new Buffer
1598 # b.insert(" nit ", 3)
1599 # assert b == "美しい nit 世界"
1601 fun insert
(s
: Text, pos
: Int) is abstract
1603 # Inserts `c` at position `pos`
1606 # var b = new Buffer
1608 # b.insert_char(' ', 3)
1609 # assert b == "美しい 世界"
1611 fun insert_char
(c
: Char, pos
: Int) is abstract
1613 # Removes a substring from `self` at position `pos`
1615 # NOTE: `length` defaults to 1, expressed in chars
1618 # var b = new Buffer
1619 # b.append("美しい 世界")
1621 # assert b == "美しい世界"
1625 fun remove_at
(pos
: Int, length
: nullable Int) is abstract
1627 redef fun reversed
do
1633 redef fun to_upper
do
1639 redef fun to_lower
do
1645 redef fun to_snake_case
do
1651 # Takes a camel case `self` and converts it to snake case
1653 # SEE: `to_snake_case`
1655 if self.is_lower
then return
1656 var prev_is_lower
= false
1657 var prev_is_upper
= false
1662 if char
.is_lower
then
1663 prev_is_lower
= true
1664 prev_is_upper
= false
1665 else if char
.is_upper
then
1666 if prev_is_lower
then
1669 else if prev_is_upper
and i
+ 1 < length
and self[i
+ 1].is_lower
then
1673 self[i
] = char
.to_lower
1674 prev_is_lower
= false
1675 prev_is_upper
= true
1677 prev_is_lower
= false
1678 prev_is_upper
= false
1684 redef fun to_camel_case
1691 # Takes a snake case `self` and converts it to camel case
1693 # SEE: `to_camel_case`
1695 if is_upper
then return
1697 var underscore_count
= 0
1700 while pos
< length
do
1701 var char
= self[pos
]
1703 underscore_count
+= 1
1704 else if underscore_count
> 0 then
1705 pos
-= underscore_count
1706 remove_at
(pos
, underscore_count
)
1707 self[pos
] = char
.to_upper
1708 underscore_count
= 0
1712 if underscore_count
> 0 then remove_at
(pos
- underscore_count
- 1, underscore_count
)
1715 redef fun capitalized
(keep_upper
) do
1716 if length
== 0 then return self
1718 var buf
= new Buffer.with_cap
(byte_length
)
1719 buf
.capitalize
(keep_upper
=keep_upper
, src
=self)
1724 # View for chars on Buffer objects, extends Sequence
1725 # for mutation operations
1726 private abstract class BufferCharView
1727 super StringCharView
1728 super Sequence[Char]
1730 redef type SELFTYPE: Buffer
1734 # View for bytes on Buffer objects, extends Sequence
1735 # for mutation operations
1736 private abstract class BufferByteView
1737 super StringByteView
1739 redef type SELFTYPE: Buffer
1743 # User readable representation of `self`.
1744 fun to_s
: String do return inspect
1746 # The class name of the object in CString format.
1747 private fun native_class_name
: CString is intern
1749 # The class name of the object.
1751 # assert 5.class_name == "Int"
1752 fun class_name
: String do return native_class_name
.to_s
1754 # Developer readable representation of `self`.
1755 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1758 return "<{inspect_head}>"
1761 # Return "CLASSNAME:#OBJECTID".
1762 # This function is mainly used with the redefinition of the inspect method
1763 protected fun inspect_head
: String
1765 return "{class_name}:#{object_id.to_hex}"
1770 # assert true.to_s == "true"
1771 # assert false.to_s == "false"
1783 # C function to calculate the length of the `CString` to receive `self`
1784 private fun byte_to_s_len
: Int `{
1785 return snprintf(NULL, 0, "0x%02x", self);
1788 # C function to convert an nit Int to a CString (char*)
1789 private fun native_byte_to_s
(nstr
: CString, strlen
: Int) `{
1790 snprintf(nstr, strlen, "0x%02x", self);
1793 # Displayable byte in its hexadecimal form (0x..)
1795 # assert 1.to_b.to_s == "0x01"
1796 # assert (-123).to_b.to_s == "0x85"
1798 var nslen
= byte_to_s_len
1799 var ns
= new CString(nslen
+ 1)
1801 native_byte_to_s
(ns
, nslen
+ 1)
1802 return ns
.to_s_unsafe
(nslen
, copy
=false, clean
=false)
1808 # Wrapper of strerror C function
1809 private fun strerror_ext
: CString `{ return strerror((int)self); `}
1811 # Returns a string describing error number
1812 fun strerror: String do return strerror_ext.to_s
1814 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if negative).
1815 # assume < to_c max const of char
1816 private fun fill_buffer(s: Buffer, base: Int)
1823 else if self == 0 then
1830 var pos = digit_count(base) - 1
1831 while pos >= 0 and n > 0 do
1832 s.chars[pos] = (n % base).to_c
1838 # C function to calculate the length of the `CString` to receive `self`
1839 private fun int_to_s_len: Int `{
1840 return snprintf
(NULL, 0, "%ld", self);
1843 # C function to convert an nit Int to a CString (char*)
1844 private fun native_int_to_s(nstr: CString, strlen: Int) `{
1845 snprintf
(nstr
, strlen
, "%ld", self);
1848 # String representation of `self` in the given `base
`
1851 # assert 15.to_base(10) == "15"
1852 # assert 15.to_base(16) == "f"
1853 # assert 15.to_base(2) == "1111"
1854 # assert (-10).to_base(3) == "-101"
1856 fun to_base(base: Int): String
1858 var l = digit_count(base)
1861 for x in [0..l[ do s.add(' ')
1862 fill_buffer(s, base)
1867 # return displayable int in hexadecimal
1869 # assert 1.to_hex == "1"
1870 # assert (-255).to_hex == "-ff"
1871 fun to_hex: String do return to_base(16)
1875 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1877 # assert 12.34.to_s == "12.34"
1878 # assert (-0120.030).to_s == "-120.03"
1880 # see `to_precision
` for a custom precision.
1882 var str = to_precision( 3 )
1883 if is_inf != 0 or is_nan then return str
1884 var len = str.length
1885 for i in [0..len-1] do
1887 var c = str.chars[j]
1890 else if c == '.' then
1891 return str.substring( 0, j+2 )
1893 return str.substring( 0, j+1 )
1899 # `String` representation of `self` with the given number of `decimals
`
1901 # assert 12.345.to_precision(0) == "12"
1902 # assert 12.345.to_precision(3) == "12.345"
1903 # assert (-12.345).to_precision(3) == "-12.345"
1904 # assert (-0.123).to_precision(3) == "-0.123"
1905 # assert 0.999.to_precision(2) == "1.00"
1906 # assert 0.999.to_precision(4) == "0.9990"
1907 fun to_precision(decimals: Int): String
1909 if is_nan then return "nan"
1911 var isinf = self.is_inf
1914 else if isinf == -1 then
1918 var size = to_precision_size(decimals)
1919 var cstr = new CString(size+1)
1920 to_precision_fill(decimals, size+1, cstr)
1921 return cstr.to_s_unsafe(byte_length=size, copy=false)
1924 # Required string length to hold `self` with `nb
` decimals
1926 # The length does not include the terminating null byte.
1927 private fun to_precision_size(nb: Int): Int `{
1928 return snprintf
(NULL, 0, "%.*f", (int
)nb
, self);
1931 # Fill `cstr
` with `self` and `nb
` decimals
1932 private fun to_precision_fill(nb, size: Int, cstr: CString) `{
1933 snprintf
(cstr
, size
, "%.*f", (int
)nb
, self);
1939 # Returns a sequence with the UTF-8 bytes of `self`
1941 # assert 'a'.bytes == [0x61u8]
1942 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1943 fun bytes: SequenceRead[Byte] do return to_s.bytes
1945 # Is `self` an UTF-16 surrogate pair ?
1946 fun is_surrogate: Bool do
1948 return cp >= 0xD800 and cp <= 0xDFFF
1951 # Is `self` a UTF-16 high surrogate ?
1952 fun is_hi_surrogate: Bool do
1954 return cp >= 0xD800 and cp <= 0xDBFF
1957 # Is `self` a UTF-16 low surrogate ?
1958 fun is_lo_surrogate: Bool do
1960 return cp >= 0xDC00 and cp <= 0xDFFF
1963 # Length of `self` in a UTF-8 String
1964 fun u8char_len: Int do
1965 var c = self.code_point
1966 if c < 0x80 then return 1
1967 if c <= 0x7FF then return 2
1968 if c <= 0xFFFF then return 3
1969 if c <= 0x10FFFF then return 4
1970 # Bad character format
1974 # assert 'x'.to_s == "x"
1977 var ns = new CString(ln + 1)
1979 return ns.to_s_unsafe(ln, copy=false, clean=false)
1982 # Returns `self` escaped to UTF-16
1984 # i.e. Represents `self`.`code_point
` using UTF-16 codets escaped
1987 # assert 'A'.escape_to_utf16 == "\\u0041"
1988 # assert 'è'.escape_to_utf16 == "\\u00e8"
1989 # assert 'あ'.escape_to_utf16 == "\\u3042"
1990 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
1991 fun escape_to_utf16: String do
1994 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
1995 buf = new Buffer.with_cap(6)
1996 buf.append("\\u0000")
1999 for i in hx.chars.reverse_iterator do
2004 buf = new Buffer.with_cap(12)
2005 buf.append("\\u0000\\u0000")
2006 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
2007 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
2022 private fun u8char_tos(r: CString, len: Int) `{
2029 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
2030 r
[1] = 0x80 | (self & 0x3F);
2033 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
2034 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
2035 r
[2] = 0x80 | (self & 0x3F);
2038 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
2039 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
2040 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
2041 r
[3] = 0x80 | (self & 0x3F);
2046 # Returns true if the char is a numerical digit
2048 # assert '0'.is_numeric
2049 # assert '9'.is_numeric
2050 # assert not 'a'.is_numeric
2051 # assert not '?'.is_numeric
2053 # FIXME: Works on ASCII-range only
2054 fun is_numeric: Bool
2056 return self >= '0' and self <= '9'
2059 # Returns true if the char is an alpha digit
2061 # assert 'a'.is_alpha
2062 # assert 'Z'.is_alpha
2063 # assert not '0'.is_alpha
2064 # assert not '?'.is_alpha
2066 # FIXME: Works on ASCII-range only
2069 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2072 # Is `self` an hexadecimal digit ?
2074 # assert 'A'.is_hexdigit
2075 # assert not 'G'.is_hexdigit
2076 # assert 'a'.is_hexdigit
2077 # assert not 'g'.is_hexdigit
2078 # assert '5'.is_hexdigit
2079 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
2080 (self >= 'a' and self <= 'f')
2082 # Returns true if the char is an alpha or a numeric digit
2084 # assert 'a'.is_alphanumeric
2085 # assert 'Z'.is_alphanumeric
2086 # assert '0'.is_alphanumeric
2087 # assert '9'.is_alphanumeric
2088 # assert not '?'.is_alphanumeric
2090 # FIXME: Works on ASCII-range only
2091 fun is_alphanumeric: Bool
2093 return self.is_numeric or self.is_alpha
2096 # Returns `self` to its int value
2098 # REQUIRE: `is_hexdigit
`
2099 fun from_hex: Int do
2100 if self >= '0' and self <= '9' then return code_point - 0x30
2101 if self >= 'A' and self <= 'F' then return code_point - 0x37
2102 if self >= 'a' and self <= 'f' then return code_point - 0x57
2103 # Happens if self is not a hexdigit
2104 assert self.is_hexdigit
2105 # To make flow analysis happy
2110 redef class Collection[E]
2111 # String representation of the content of the collection.
2113 # The standard representation is the list of elements separated with commas.
2116 # assert [1,2,3].to_s == "[1,2,3]"
2117 # assert [1..3].to_s == "[1,2,3]"
2118 # assert (new Array[Int]).to_s == "[]" # empty collection
2121 # Subclasses may return a more specific string representation.
2124 return "[" + join(",") + "]"
2127 # Concatenate elements without separators
2130 # assert [1,2,3].plain_to_s == "123"
2131 # assert [11..13].plain_to_s == "111213"
2132 # assert (new Array[Int]).plain_to_s == "" # empty collection
2134 fun plain_to_s: String
2137 for e in self do if e != null then s.append(e.to_s)
2141 # Concatenate and separate each elements with `separator
`.
2143 # Only concatenate if `separator
== null`.
2145 # assert [1, 2, 3].join(":") == "1:2:3"
2146 # assert [1..3].join(":") == "1:2:3"
2147 # assert [1..3].join == "123"
2149 # if `last_separator
` is given, then it is used to separate the last element.
2151 # assert [1, 2, 3, 4].join(", ", " and ") == "1, 2, 3 and 4"
2152 fun join(separator: nullable Text, last_separator: nullable Text): String
2154 if is_empty then return ""
2156 var s = new Buffer # Result
2161 if e != null then s.append(e.to_s)
2163 if last_separator == null then last_separator = separator
2165 # Concat other items
2171 if separator != null then s.append(separator)
2173 if last_separator != null then s.append(last_separator)
2175 if e != null then s.append(e.to_s)
2181 redef class Map[K,V]
2182 # Concatenate couples of key value.
2183 # Key and value are separated by `couple_sep
`.
2184 # Couples are separated by `sep
`.
2186 # var m = new HashMap[Int, String]
2189 # assert m.join("; ", "=") == "1=one; 10=ten"
2190 fun join(sep, couple_sep: String): String is abstract
2194 private var args_cache: nullable Sequence[String] = null
2196 # The arguments of the program as given by the OS
2197 fun program_args: Sequence[String]
2199 if _args_cache == null then init_args
2200 return _args_cache.as(not null)
2203 # The name of the program as given by the OS
2204 fun program_name: String
2206 return native_argv(0).to_s
2209 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2210 private fun init_args
2212 var argc = native_argc
2213 var args = new Array[String].with_capacity(0)
2216 args[i-1] = native_argv(i).to_s
2222 # First argument of the main C function.
2223 private fun native_argc: Int is intern
2225 # Second argument of the main C function.
2226 private fun native_argv(i: Int): CString is intern
2229 # Comparator that efficienlty use `to_s
` to compare things
2231 # The comparaison call `to_s
` on object and use the result to order things.
2233 # var a = [1, 2, 3, 10, 20]
2234 # (new CachedAlphaComparator).sort(a)
2235 # assert a == [1, 10, 2, 20, 3]
2237 # Internally the result of `to_s
` is cached in a HashMap to counter
2238 # uneficient implementation of `to_s
`.
2240 # Note: it caching is not usefull, see `alpha_comparator
`
2241 class CachedAlphaComparator
2243 redef type COMPARED: Object
2245 private var cache = new HashMap[Object, String]
2247 private fun do_to_s(a: Object): String do
2248 if cache.has_key(a) then return cache[a]
2254 redef fun compare(a, b) do
2255 return do_to_s(a) <=> do_to_s(b)
2259 # see `alpha_comparator
`
2260 private class AlphaComparator
2262 redef fun compare(a, b) do
2263 if a == b then return 0
2264 if a == null then return -1
2265 if b == null then return 1
2266 return a.to_s <=> b.to_s
2270 # Stateless comparator that naively use `to_s
` to compare things.
2272 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2273 # on a single instace. See `CachedAlphaComparator` as an alternative.
2275 # var a = [1, 2, 3, 10, 20]
2276 # alpha_comparator.sort(a)
2277 # assert a == [1, 10, 2, 20, 3]
2278 fun alpha_comparator: Comparator do return once new AlphaComparator
2280 # The arguments of the program as given by the OS
2281 fun args: Sequence[String]
2283 return sys.program_args
2288 # Get a `String` from the data at `self` (with unsafe options)
2290 # The default behavior is the safest and equivalent to `to_s
`.
2294 # * Set `byte_length
` to the number of bytes to use as data.
2295 # Otherwise, this method searches for a terminating null byte.
2297 # * Set `char_length
` to the number of Unicode character in the string.
2298 # Otherwise, the data is read to count the characters.
2299 # Ignored if `clean
== true`.
2301 # * If `copy
== true`, the default, copies the data at `self` in the
2302 # Nit GC allocated memory. Otherwise, the return may still point to
2303 # the data at `self`.
2305 # * If `clean
== true`, the default, the string is cleaned of invalid UTF-8
2306 # characters. If cleaning is necessary, the data is copied into Nit GC
2307 # managed memory, whether or not `copy
== true`.
2308 # Don't clean only when the data has already been verified as valid UTF-8,
2309 # other library services rely on UTF-8 compliant characters.
2310 fun to_s_unsafe(byte_length, char_length: nullable Int, copy, clean: nullable Bool): String is abstract
2312 # Retro-compatibility service use by execution engines
2314 # TODO remove this method at the next c_src regen.
2315 private fun to_s_full(byte_length, char_length: Int): String do return to_s_unsafe(byte_length, char_length, false, false)
2317 # Copies the content of `src
` to `self`
2319 # NOTE: `self` must be large enough to contain `self.byte_length
` bytes
2320 fun fill_from(src: Text) do src.copy_to_native(self, src.byte_length, 0, 0)
2323 redef class NativeArray[E]
2324 # Join all the elements using `to_s
`
2326 # REQUIRE: `self isa NativeArray[String]`
2327 # REQUIRE: all elements are initialized
2328 fun native_to_s: String is abstract