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 # Gets the first char of the Text
88 # DEPRECATED : Use self.chars.first instead
89 fun first
: Char do return self.chars
[0]
91 # Access a character at `index` in the string.
93 # assert "abcd"[2] == 'c'
95 # DEPRECATED : Use self.chars.[] instead
96 fun [](index
: Int): Char do return self.chars
[index
]
98 # Gets the index of the first occurence of 'c'
100 # Returns -1 if not found
102 # DEPRECATED : Use self.chars.index_of instead
103 fun index_of
(c
: Char): Int
105 return index_of_from
(c
, 0)
108 # Gets the last char of self
110 # DEPRECATED : Use self.chars.last instead
111 fun last
: Char do return self.chars
[length-1
]
113 # Gets the index of the first occurence of ´c´ starting from ´pos´
115 # Returns -1 if not found
117 # DEPRECATED : Use self.chars.index_of_from instead
118 fun index_of_from
(c
: Char, pos
: Int): Int
120 var iter
= self.chars
.iterator_from
(pos
)
122 if iter
.item
== c
then return iter
.index
128 # Gets the last index of char ´c´
130 # Returns -1 if not found
132 # DEPRECATED : Use self.chars.last_index_of instead
133 fun last_index_of
(c
: Char): Int
135 return last_index_of_from
(c
, length
- 1)
138 # Return a null terminated char *
139 fun to_cstring
: NativeString is abstract
141 # The index of the last occurrence of an element starting from pos (in reverse order).
143 # var s = "/etc/bin/test/test.nit"
144 # assert s.last_index_of_from('/', s.length-1) == 13
145 # assert s.last_index_of_from('/', 12) == 8
147 # Returns -1 if not found
149 # DEPRECATED : Use self.chars.last_index_of_from instead
150 fun last_index_of_from
(item
: Char, pos
: Int): Int do return chars
.last_index_of_from
(item
, pos
)
152 # Concatenates `o` to `self`
154 # assert "hello" + "world" == "helloworld"
155 # assert "" + "hello" + "" == "hello"
156 fun +(o
: Text): SELFTYPE is abstract
158 # Gets an iterator on the chars of self
160 # DEPRECATED : Use self.chars.iterator instead
161 fun iterator
: Iterator[Char]
163 return self.chars
.iterator
167 # Gets an Array containing the chars of self
169 # DEPRECATED : Use self.chars.to_a instead
170 fun to_a
: Array[Char] do return chars
.to_a
172 # Create a substring from `self` beginning at the `from` position
174 # assert "abcd".substring_from(1) == "bcd"
175 # assert "abcd".substring_from(-1) == "abcd"
176 # assert "abcd".substring_from(2) == "cd"
178 # As with substring, a `from` index < 0 will be replaced by 0
179 fun substring_from
(from
: Int): SELFTYPE
181 if from
>= self.length
then return empty
182 if from
< 0 then from
= 0
183 return substring
(from
, length
- from
)
186 # Does self have a substring `str` starting from position `pos`?
188 # assert "abcd".has_substring("bc",1) == true
189 # assert "abcd".has_substring("bc",2) == false
191 # Returns true iff all characters of `str` are presents
192 # at the expected index in `self.`
193 # The first character of `str` being at `pos`, the second
194 # character being at `pos+1` and so on...
196 # This means that all characters of `str` need to be inside `self`.
198 # assert "abcd".has_substring("xab", -1) == false
199 # assert "abcd".has_substring("cdx", 2) == false
201 # And that the empty string is always a valid substring.
203 # assert "abcd".has_substring("", 2) == true
204 # assert "abcd".has_substring("", 200) == true
205 fun has_substring
(str
: String, pos
: Int): Bool
207 if str
.is_empty
then return true
208 if pos
< 0 or pos
+ str
.length
> length
then return false
209 var myiter
= self.chars
.iterator_from
(pos
)
210 var itsiter
= str
.chars
.iterator
211 while myiter
.is_ok
and itsiter
.is_ok
do
212 if myiter
.item
!= itsiter
.item
then return false
216 if itsiter
.is_ok
then return false
220 # Is this string prefixed by `prefix`?
222 # assert "abcd".has_prefix("ab") == true
223 # assert "abcbc".has_prefix("bc") == false
224 # assert "ab".has_prefix("abcd") == false
225 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
227 # Is this string suffixed by `suffix`?
229 # assert "abcd".has_suffix("abc") == false
230 # assert "abcd".has_suffix("bcd") == true
231 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
233 # Returns `self` as the corresponding integer
235 # assert "123".to_i == 123
236 # assert "-1".to_i == -1
237 # assert "0x64".to_i == 100
238 # assert "0b1100_0011".to_i== 195
239 # assert "--12".to_i == 12
241 # REQUIRE: `self`.`is_int`
242 fun to_i
: Int is abstract
244 # If `self` contains a float, return the corresponding float
246 # assert "123".to_f == 123.0
247 # assert "-1".to_f == -1.0
248 # assert "-1.2e-3".to_f == -0.0012
252 return to_s
.to_cstring
.atof
255 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
257 # assert "ff".to_hex == 255
258 fun to_hex
(pos
, ln
: nullable Int): Int do
260 if pos
== null then pos
= 0
261 if ln
== null then ln
= length
- pos
263 for i
in [pos
.. max
[ do
265 res
+= self[i
].from_hex
270 # If `self` contains only digits <= '7', return the corresponding integer.
272 # assert "714".to_oct == 460
273 fun to_oct
: Int do return a_to
(8)
275 # If `self` contains only '0' et '1', return the corresponding integer.
277 # assert "101101".to_bin == 45
278 fun to_bin
: Int do return a_to
(2)
280 # If `self` contains only digits '0' .. '9', return the corresponding integer.
282 # assert "108".to_dec == 108
283 fun to_dec
: Int do return a_to
(10)
285 # If `self` contains only digits and letters, return the corresponding integer in a given base
287 # assert "120".a_to(3) == 15
288 fun a_to
(base
: Int) : Int
293 for j
in [0..length
[ do
315 # Is this string in a valid numeric format compatible with `to_f`?
317 # assert "123".is_numeric == true
318 # assert "1.2".is_numeric == true
319 # assert "-1.2".is_numeric == true
320 # assert "-1.23e-2".is_numeric == true
321 # assert "1..2".is_numeric == false
322 # assert "".is_numeric == false
325 var has_point
= false
327 for i
in [0..length
[ do
329 if not c
.is_numeric
then
330 if c
== '.' and not has_point
then
332 else if c
== 'e' and e_index
== -1 and i
> 0 and i
< length
- 1 and chars
[i-1
] != '-' then
334 else if c
== '-' and i
== e_index
+ 1 and i
< length
- 1 then
343 # Returns `true` if the string contains only Hex chars
345 # assert "048bf".is_hex == true
346 # assert "ABCDEF".is_hex == true
347 # assert "0G".is_hex == false
350 for i
in [0..length
[ do
352 if not (c
>= 'a' and c
<= 'f') and
353 not (c
>= 'A' and c
<= 'F') and
354 not (c
>= '0' and c
<= '9') then return false
359 # Returns `true` if the string contains only Binary digits
361 # assert "1101100".is_bin == true
362 # assert "1101020".is_bin == false
364 for i
in chars
do if i
!= '0' and i
!= '1' then return false
368 # Returns `true` if the string contains only Octal digits
370 # assert "213453".is_oct == true
371 # assert "781".is_oct == false
373 for i
in chars
do if i
< '0' or i
> '7' then return false
377 # Returns `true` if the string contains only Decimal digits
379 # assert "10839".is_dec == true
380 # assert "164F".is_dec == false
382 for i
in chars
do if i
< '0' or i
> '9' then return false
386 # Are all letters in `self` upper-case ?
388 # assert "HELLO WORLD".is_upper == true
389 # assert "%$&%!".is_upper == true
390 # assert "hello world".is_upper == false
391 # assert "Hello World".is_upper == false
394 for i
in [0..length
[ do
396 if char
.is_lower
then return false
401 # Are all letters in `self` lower-case ?
403 # assert "hello world".is_lower == true
404 # assert "%$&%!".is_lower == true
405 # assert "Hello World".is_lower == false
408 for i
in [0..length
[ do
410 if char
.is_upper
then return false
415 # Removes the whitespaces at the beginning of self
417 # assert " \n\thello \n\t".l_trim == "hello \n\t"
419 # `Char::is_whitespace` determines what is a whitespace.
422 var iter
= self.chars
.iterator
424 if not iter
.item
.is_whitespace
then break
427 if iter
.index
== length
then return self.empty
428 return self.substring_from
(iter
.index
)
431 # Removes the whitespaces at the end of self
433 # assert " \n\thello \n\t".r_trim == " \n\thello"
435 # `Char::is_whitespace` determines what is a whitespace.
438 var iter
= self.chars
.reverse_iterator
440 if not iter
.item
.is_whitespace
then break
443 if iter
.index
< 0 then return self.empty
444 return self.substring
(0, iter
.index
+ 1)
447 # Trims trailing and preceding white spaces
449 # assert " Hello World ! ".trim == "Hello World !"
450 # assert "\na\nb\tc\t".trim == "a\nb\tc"
452 # `Char::is_whitespace` determines what is a whitespace.
453 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
455 # Is the string non-empty but only made of whitespaces?
457 # assert " \n\t ".is_whitespace == true
458 # assert " hello ".is_whitespace == false
459 # assert "".is_whitespace == false
461 # `Char::is_whitespace` determines what is a whitespace.
462 fun is_whitespace
: Bool
464 if is_empty
then return false
465 for c
in self.chars
do
466 if not c
.is_whitespace
then return false
471 # Returns `self` removed from its last line terminator (if any).
473 # assert "Hello\n".chomp == "Hello"
474 # assert "Hello".chomp == "Hello"
476 # assert "\n".chomp == ""
477 # assert "".chomp == ""
479 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
480 # A single line terminator, the last one, is removed.
482 # assert "\r\n".chomp == ""
483 # assert "\r\n\n".chomp == "\r\n"
484 # assert "\r\n\r\n".chomp == "\r\n"
485 # assert "\r\n\r".chomp == "\r\n"
487 # Note: unlike with most IO methods like `Reader::read_line`,
488 # a single `\r` is considered here to be a line terminator and will be removed.
492 if len
== 0 then return self
493 var l
= self.chars
.last
495 return substring
(0, len-1
)
496 else if l
!= '\n' then
498 else if len
> 1 and self.chars
[len-2
] == '\r' then
499 return substring
(0, len-2
)
501 return substring
(0, len-1
)
505 # Justify `self` in a space of `length`
507 # `left` is the space ratio on the left side.
508 # * 0.0 for left-justified (no space at the left)
509 # * 1.0 for right-justified (all spaces at the left)
510 # * 0.5 for centered (half the spaces at the left)
512 # `char`, or `' '` by default, is repeated to pad the empty space.
516 # assert "hello".justify(10, 0.0) == "hello "
517 # assert "hello".justify(10, 1.0) == " hello"
518 # assert "hello".justify(10, 0.5) == " hello "
519 # assert "hello".justify(10, 0.5, '.') == "..hello..."
521 # If `length` is not enough, `self` is returned as is.
523 # assert "hello".justify(2, 0.0) == "hello"
525 # REQUIRE: `left >= 0.0 and left <= 1.0`
526 # ENSURE: `self.length <= length implies result.length == length`
527 # ENSURE: `self.length >= length implies result == self`
528 fun justify
(length
: Int, left
: Float, char
: nullable Char): String
530 var pad
= (char
or else ' ').to_s
531 var diff
= length
- self.length
532 if diff
<= 0 then return to_s
533 assert left
>= 0.0 and left
<= 1.0
534 var before
= (diff
.to_f
* left
).to_i
535 return pad
* before
+ self + pad
* (diff-before
)
538 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
540 # This method is injective (two different inputs never produce the same
541 # output) and the returned string always respect the following rules:
543 # * Contains only US-ASCII letters, digits and underscores.
544 # * Never starts with a digit.
545 # * Never ends with an underscore.
546 # * Never contains two contiguous underscores.
548 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
549 # assert "__".to_cmangle == "_95d_95d"
550 # assert "__d".to_cmangle == "_95d_d"
551 # assert "_d_".to_cmangle == "_d_95d"
552 # assert "_42".to_cmangle == "_95d42"
553 # assert "foo".to_cmangle == "foo"
554 # assert "".to_cmangle == ""
555 fun to_cmangle
: String
557 if is_empty
then return ""
559 var underscore
= false
563 if c
>= '0' and c
<= '9' then
565 res
.append
(c
.code_point
.to_s
)
569 for i
in [start
..length
[ do
571 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
577 res
.append
('_'.code_point
.to_s
)
580 if c
>= '0' and c
<= '9' then
583 else if c
== '_' then
588 res
.append
(c
.code_point
.to_s
)
594 res
.append
('_'.code_point
.to_s
)
600 # Escape `"` `\` `'`, trigraphs and non printable characters using the rules of literal C strings and characters
602 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
603 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
604 # assert "allo???!".escape_to_c == "allo??\\?!"
605 # assert "??=??/??'??(??)".escape_to_c == "?\\?=?\\?/??\\'?\\?(?\\?)"
606 # assert "??!??<??>??-".escape_to_c == "?\\?!?\\?<?\\?>?\\?-"
608 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
609 # Three digits are always used to avoid following digits to be interpreted as an element
610 # of the octal sequence.
612 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
614 # The exceptions are the common `\t` and `\n`.
615 fun escape_to_c
: String
618 for i
in [0..length
[ do
622 else if c
== '\t' then
624 else if c
== '"' then
626 else if c == '\'' then
628 else if c == '\\
' then
630 else if c == '?' then
631 # Escape if it is the last question mark of a ANSI C trigraph.
635 # We ignore `??'` because it will be escaped as `??\
'`.
648 else if c.code_point < 32 then
650 var oct = c.code_point.to_base(8)
651 # Force 3 octal digits since it is the
652 # maximum allowed in the C specification
653 if oct.length == 1 then
656 else if oct.length == 2 then
667 # Escape additionnal characters
668 # The result might no be legal in C but be used in other languages
670 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
671 # assert "allo???!".escape_more_to_c("") == "allo??\\?!"
672 fun escape_more_to_c(chars: String): String
675 for c in escape_to_c.chars do
676 if chars.chars.has(c) then
684 # Escape to C plus braces
686 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
687 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
689 # Escape to POSIX Shell (sh).
691 # Abort if the text contains a null byte.
693 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
694 fun escape_to_sh
: String do
697 for i in [0..length[ do
702 assert without_null_byte
: c
!= '\0'
710 # Escape to include in a Makefile
712 # Unfortunately, some characters are not escapable in Makefile.
713 # These characters are `;`, `|`, `\`, and the non-printable ones.
714 # They will be rendered as `"?{hex}"`.
715 fun escape_to_mk: String do
717 for i in [0..length[ do
721 else if c == ':' or c == ' ' or c == '#' then
724 else if c
.code_point
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
725 b
.append
("?{c.code_point.to_base(16)}")
733 # Return a string where Nit escape sequences are transformed.
736 # assert s.length == 2
737 # var u = s.unescape_nit
738 # assert u.length == 1
739 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
740 fun unescape_nit
: String
742 var res
= new Buffer.with_cap
(self.length
)
743 var was_slash
= false
744 for i
in [0..length
[ do
746 if not was_slash
then
757 else if c
== 'r' then
759 else if c
== 't' then
761 else if c
== '0' then
770 # Returns `self` with all characters escaped with their UTF-16 representation
772 # assert "Aèあ𐏓".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
773 fun escape_to_utf16
: String do
775 for i
in chars
do buf
.append i
.escape_to_utf16
779 # Returns the Unicode char escaped by `self`
781 # assert "\\u0041".from_utf16_escape == 'A'
782 # assert "\\ud800\\udfd3".from_utf16_escape == '𐏓'
783 # assert "\\u00e8".from_utf16_escape == 'è'
784 # assert "\\u3042".from_utf16_escape == 'あ'
785 fun from_utf16_escape
(pos
, ln
: nullable Int): Char do
786 if pos
== null then pos
= 0
787 if ln
== null then ln
= length
- pos
788 if ln
< 6 then return 0xFFFD.code_point
789 var cp
= from_utf16_digit
(pos
+ 2)
790 if cp
< 0xD800 then return cp
.code_point
791 if cp
> 0xDFFF then return cp
.code_point
792 if cp
> 0xDBFF then return 0xFFFD.code_point
793 if ln
== 6 then return 0xFFFD.code_point
794 if ln
< 12 then return 0xFFFD.code_point
796 cp
+= from_utf16_digit
(pos
+ 8)
797 var cplo
= cp
& 0xFFFF
798 if cplo
< 0xDC00 then return 0xFFFD.code_point
799 if cplo
> 0xDFFF then return 0xFFFD.code_point
800 return cp
.from_utf16_surr
.code_point
803 # Returns a UTF-16 escape value
805 # var s = "\\ud800\\udfd3"
806 # assert s.from_utf16_digit(2) == 0xD800
807 # assert s.from_utf16_digit(8) == 0xDFD3
808 fun from_utf16_digit
(pos
: nullable Int): Int do
809 if pos
== null then pos
= 0
810 return to_hex
(pos
, 4)
813 # Encode `self` to percent (or URL) encoding
815 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
816 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
817 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
818 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
819 fun to_percent_encoding
: String
823 for i
in [0..length
[ do
825 if (c
>= '0' and c
<= '9') or
826 (c
>= 'a' and c
<= 'z') or
827 (c
>= 'A' and c
<= 'Z') or
828 c
== '-' or c
== '.' or
833 var bytes
= c
.to_s
.bytes
834 for b
in bytes
do buf
.append
"%{b.to_i.to_hex}"
841 # Decode `self` from percent (or URL) encoding to a clear string
843 # Replace invalid use of '%' with '?'.
845 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
846 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
847 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
848 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
849 # assert "incomplete %".from_percent_encoding == "incomplete ?"
850 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
851 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
852 fun from_percent_encoding
: String
854 var len
= byte_length
855 var has_percent
= false
863 # If no transformation is needed, return self as a string
864 if not has_percent
then return to_s
866 var buf
= new NativeString(len
)
872 if i
+ 2 >= length
then
873 # What follows % has been cut off
877 var hex_s
= substring
(i
, 2)
879 var hex_i
= hex_s
.to_hex
883 # What follows a % is not Hex
888 else buf
[l
] = c
.ascii
894 return buf
.to_s_unsafe
(l
)
897 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
899 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
901 # 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>
902 fun html_escape
: String
906 for i
in [0..length
[ do
910 else if c
== '<' then
912 else if c
== '>' then
914 else if c
== '"' then
916 else if c
== '\'' then
918 else if c == '/' then
927 # Two pieces of text are equals if thez have the same characters in the same order.
929 # assert "hello" == "hello"
930 # assert "hello" != "HELLO"
931 # assert "hello" == "hel"+"lo"
933 # Things that are not Text are not equal.
936 # assert "9" != ['9']
939 # assert "9".chars.first == '9' # equality of Char
940 # assert "9".chars == ['9'] # equality of Sequence
941 # assert "9".to_i == 9 # equality of Int
944 if o == null then return false
945 if not o isa Text then return false
946 if self.is_same_instance(o) then return true
947 if self.length != o.length then return false
948 return self.chars == o.chars
951 # Lexicographical comparaison
953 # assert "abc" < "xy"
954 # assert "ABC" < "abc"
957 var self_chars = self.chars.iterator
958 var other_chars = other.chars.iterator
960 while self_chars.is_ok and other_chars.is_ok do
961 if self_chars.item < other_chars.item then return true
962 if self_chars.item > other_chars.item then return false
967 if self_chars.is_ok then
974 # Escape string used in labels for graphviz
976 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
977 fun escape_to_dot: String
979 return escape_more_to_c("|\{\}<>")
982 private var hash_cache: nullable Int = null
986 if hash_cache == null then
987 # djb2 hash algorithm
990 for i in [0..length[ do
992 h = (h << 5) + h + char.code_point
997 return hash_cache.as(not null)
1000 # Format `self` by replacing each `%n` with the `n`th item of `args`
1002 # The character `%` followed by something other than a number are left as is.
1003 # To represent a `%` followed by a number, double the `%`, as in `%%7`.
1005 # assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
1006 # assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"
1007 fun format(args: Object...): String do
1008 var s = new Array[Text]
1012 if self[i] == '%' then
1016 while i < length and self[i].is_numeric do
1020 var ciph_len = i - ciph_st
1021 if ciph_len == 0 then
1022 # What follows '%' is not a number.
1023 s.push substring(curr_st, i - curr_st)
1024 if i < length and self[i] == '%' then
1032 var arg_index = substring(ciph_st, ciph_len).to_i
1033 if arg_index >= args.length then continue
1035 s.push substring(curr_st, fmt_st - curr_st)
1036 s.push args[arg_index].to_s
1043 s.push substring(curr_st, length - curr_st)
1047 # Return the Levenshtein distance between two strings
1050 # assert "abcd".levenshtein_distance("abcd") == 0
1051 # assert "".levenshtein_distance("abcd") == 4
1052 # assert "abcd".levenshtein_distance("") == 4
1053 # assert "abcd".levenshtein_distance("xyz") == 4
1054 # assert "abcd".levenshtein_distance("xbdy") == 3
1056 fun levenshtein_distance(other: String): Int
1058 var slen = self.length
1059 var olen = other.length
1062 if slen == 0 then return olen
1063 if olen == 0 then return slen
1064 if self == other then return 0
1066 # previous row of distances
1067 var v0 = new Array[Int].with_capacity(olen+1)
1069 # current row of distances
1070 var v1 = new Array[Int].with_capacity(olen+1)
1072 for j in [0..olen] do
1073 # prefix insert cost
1077 for i in [0..slen[ do
1079 # prefix delete cost
1082 for j in [0..olen[ do
1084 var cost1 = v1[j] + 1
1086 var cost2 = v0[j + 1] + 1
1087 # same char cost (+0)
1090 if self[i] != other[j] then cost3 += 1
1092 v1[j+1] = cost1.min(cost2).min(cost3)
1096 # * v1 become v0 in the next iteration
1097 # * old v0 is reused as the new v1
1106 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1108 # Basically a high-level synonym of NativeString::copy_to
1110 # REQUIRE: `n` must be large enough to contain `len` bytes
1112 # var ns = new NativeString(8)
1113 # "Text is String".copy_to_native(ns, 8, 2, 0)
1114 # assert ns.to_s_unsafe(8) == "xt is St"
1116 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
1117 var mypos = src_offset
1118 var itspos = dest_offset
1120 dest[itspos] = self.bytes[mypos]
1127 # Packs the content of a string in packs of `ln` chars.
1128 # This variant ensures that only the last element might be smaller than `ln`
1131 # var s = "abcdefghijklmnopqrstuvwxyz"
1132 # assert s.pack_l(4) == ["abcd","efgh","ijkl","mnop","qrst","uvwx","yz"]
1134 fun pack_l(ln: Int): Array[Text] do
1136 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1137 while st < length do
1138 retarr.add(substring(st, ln))
1144 # Packs the content of a string in packs of `ln` chars.
1145 # This variant ensures that only the first element might be smaller than `ln`
1148 # var s = "abcdefghijklmnopqrstuvwxyz"
1149 # assert s.pack_r(4) == ["ab","cdef","ghij","klmn","opqr","stuv","wxyz"]
1151 fun pack_r(ln: Int): Array[Text] do
1153 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1155 retarr.add(substring(st - ln, ln))
1158 return retarr.reversed
1161 # Concatenates self `i` times
1164 # assert "abc" * 4 == "abcabcabcabc"
1165 # assert "abc" * 1 == "abc"
1166 # assert "abc" * 0 == ""
1167 # var b = new Buffer
1170 # assert b == "天地天地天地天地"
1172 fun *(i: Int): SELFTYPE is abstract
1174 # Insert `s` at `pos`.
1177 # assert "helloworld".insert_at(" ", 5) == "hello world"
1178 # var b = new Buffer
1179 # b.append("Hello世界")
1180 # b = b.insert_at(" beautiful ", 5)
1181 # assert b == "Hello beautiful 世界"
1183 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1185 # Returns a reversed version of self
1187 # assert "hello".reversed == "olleh"
1188 # assert "bob".reversed == "bob"
1189 # assert "".reversed == ""
1190 fun reversed: SELFTYPE is abstract
1192 # A upper case version of `self`
1194 # assert "Hello World!".to_upper == "HELLO WORLD!"
1195 fun to_upper: SELFTYPE is abstract
1197 # A lower case version of `self`
1199 # assert "Hello World!".to_lower == "hello world!"
1200 fun to_lower : SELFTYPE is abstract
1202 # Takes a camel case `self` and converts it to snake case
1204 # assert "randomMethodId".to_snake_case == "random_method_id"
1206 # The rules are the following:
1208 # An uppercase is always converted to a lowercase
1210 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1212 # An uppercase that follows a lowercase is prefixed with an underscore
1214 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1216 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1218 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1220 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1222 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1223 fun to_snake_case: SELFTYPE is abstract
1225 # Takes a snake case `self` and converts it to camel case
1227 # assert "random_method_id".to_camel_case == "randomMethodId"
1229 # If the identifier is prefixed by an underscore, the underscore is ignored
1231 # assert "_private_field".to_camel_case == "_privateField"
1233 # If `self` is upper, it is returned unchanged
1235 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1237 # If there are several consecutive underscores, they are considered as a single one
1239 # assert "random__method_id".to_camel_case == "randomMethodId"
1240 fun to_camel_case: SELFTYPE is abstract
1242 # Returns a capitalized `self`
1244 # Letters that follow a letter are lowercased
1245 # Letters that follow a non-letter are upcased.
1247 # If `keep_upper = true`, already uppercase letters are not lowercased.
1249 # SEE : `Char::is_letter` for the definition of letter.
1251 # assert "jAVASCRIPT".capitalized == "Javascript"
1252 # assert "i am root".capitalized == "I Am Root"
1253 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1254 # assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"
1255 fun capitalized(keep_upper: nullable Bool): SELFTYPE do
1256 if length == 0 then return self
1258 var buf = new Buffer.with_cap(length)
1259 buf.capitalize(keep_upper=keep_upper, src=self)
1264 # All kinds of array-based text representations.
1265 abstract class FlatText
1268 # Underlying C-String (`char*`)
1270 # Warning : Might be void in some subclasses, be sure to check
1271 # if set before using it.
1272 var items: NativeString is noinit
1274 # Returns a char* starting at position `first_byte`
1276 # WARNING: If you choose to use this service, be careful of the following.
1278 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
1279 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1280 # deallocated at any moment, rendering the pointer returned by this function invalid.
1281 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1282 # (Failure to do so will most certainly result in long and painful debugging hours)
1284 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1285 # then immediately return).
1287 # As always, do not modify the content of the String in C code, if this is what you want
1288 # copy locally the char* as Nit Strings are immutable.
1289 fun fast_cstring: NativeString is abstract
1291 redef var length = 0
1293 redef var byte_length = 0
1304 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1305 items.copy_to(dest, n, src_offset, dest_offset)
1309 # Abstract class for the SequenceRead compatible
1310 # views on the chars of any Text
1311 private abstract class StringCharView
1312 super SequenceRead[Char]
1316 var target: SELFTYPE
1318 redef fun is_empty do return target.is_empty
1320 redef fun length do return target.length
1322 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1324 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1327 # Abstract class for the SequenceRead compatible
1328 # views on the bytes of any Text
1329 private abstract class StringByteView
1330 super SequenceRead[Byte]
1334 var target: SELFTYPE
1336 redef fun is_empty do return target.is_empty
1338 redef fun length do return target.byte_length
1340 redef fun iterator do return self.iterator_from(0)
1342 redef fun reverse_iterator do return self.reverse_iterator_from(target.byte_length - 1)
1345 # Immutable sequence of characters.
1347 # String objects may be created using literals.
1349 # assert "Hello World!" isa String
1350 abstract class String
1353 redef type SELFTYPE: String is fixed
1355 redef fun to_s do return self
1357 redef fun clone do return self
1360 redef fun to_camel_case do
1361 if self.is_upper then return self
1363 var new_str = new Buffer.with_cap(length)
1369 redef fun to_snake_case do
1370 if self.is_lower then return self
1372 var new_str = new Buffer.with_cap(self.length)
1379 # A mutable sequence of characters.
1380 abstract class Buffer
1383 # Returns an arbitrary subclass of `Buffer` with default parameters
1386 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1387 new with_cap(i: Int) is abstract
1389 redef type SELFTYPE: Buffer is fixed
1391 # Copy-On-Write flag
1393 # If the `Buffer` was to_s'd
, the next in-place altering
1394 # operation will cause the current `Buffer` to be re-allocated.
1396 # The flag will then be set at `false`.
1397 protected var written
= false
1399 # Modifies the char contained at pos `index`
1401 # DEPRECATED : Use self.chars.[]= instead
1402 fun []=(index
: Int, item
: Char) is abstract
1405 # var b = new Buffer
1406 # b.append("Buffer!")
1411 var cln
= new Buffer.with_cap
(byte_length
)
1416 # Adds a char `c` at the end of self
1418 # DEPRECATED : Use self.chars.add instead
1419 fun add
(c
: Char) is abstract
1423 # var b = new Buffer
1425 # assert not b.is_empty
1428 fun clear
is abstract
1430 # Enlarges the subsequent array containing the chars of self
1431 fun enlarge
(cap
: Int) is abstract
1433 # Adds the content of text `s` at the end of self
1435 # var b = new Buffer
1438 # assert b == "helloworld"
1439 fun append
(s
: Text) is abstract
1441 # `self` is appended in such a way that `self` is repeated `r` times
1443 # var b = new Buffer
1446 # assert b == "hellohellohello"
1447 fun times
(r
: Int) is abstract
1449 # Reverses itself in-place
1451 # var b = new Buffer
1454 # assert b == "olleh"
1455 fun reverse
is abstract
1457 # Changes each lower-case char in `self` by its upper-case variant
1459 # var b = new Buffer
1460 # b.append("Hello World!")
1462 # assert b == "HELLO WORLD!"
1463 fun upper
is abstract
1465 # Changes each upper-case char in `self` by its lower-case variant
1467 # var b = new Buffer
1468 # b.append("Hello World!")
1470 # assert b == "hello world!"
1471 fun lower
is abstract
1473 # Capitalizes each word in `self`
1475 # Letters that follow a letter are lowercased
1476 # Letters that follow a non-letter are upcased.
1478 # If `keep_upper = true`, uppercase letters are not lowercased.
1480 # When `src` is specified, this method reads from `src` instead of `self`
1481 # but it still writes the result to the beginning of `self`.
1482 # This requires `self` to have the capacity to receive all of the
1483 # capitalized content of `src`.
1485 # SEE: `Char::is_letter` for the definition of a letter.
1487 # var b = new FlatBuffer.from("jAVAsCriPt")
1489 # assert b == "Javascript"
1490 # b = new FlatBuffer.from("i am root")
1492 # assert b == "I Am Root"
1493 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1495 # assert b == "Ab_C -Ab0C Ab\nC"
1497 # b = new FlatBuffer.from("12345")
1498 # b.capitalize(src="foo")
1499 # assert b == "Foo45"
1501 # b = new FlatBuffer.from("preserve my ACRONYMS")
1502 # b.capitalize(keep_upper=true)
1503 # assert b == "Preserve My ACRONYMS"
1504 fun capitalize
(keep_upper
: nullable Bool, src
: nullable Text) do
1505 src
= src
or else self
1506 var length
= src
.length
1507 if length
== 0 then return
1508 keep_upper
= keep_upper
or else false
1510 var c
= src
[0].to_upper
1513 for i
in [1 .. length
[ do
1516 if prev
.is_letter
then
1520 self[i
] = c
.to_lower
1523 self[i
] = c
.to_upper
1528 # In Buffers, the internal sequence of character is mutable
1529 # Thus, `chars` can be used to modify the buffer.
1530 redef fun chars
: Sequence[Char] is abstract
1532 # Appends `length` chars from `s` starting at index `from`
1535 # var b = new Buffer
1536 # b.append_substring("abcde", 1, 2)
1538 # b.append_substring("vwxyz", 2, 3)
1539 # assert b == "bcxyz"
1540 # b.append_substring("ABCDE", 4, 300)
1541 # assert b == "bcxyzE"
1542 # b.append_substring("VWXYZ", 400, 1)
1543 # assert b == "bcxyzE"
1545 fun append_substring
(s
: Text, from
, length
: Int) do
1551 if (length
+ from
) > ln
then length
= ln
- from
1552 if length
<= 0 then return
1553 append_substring_impl
(s
, from
, length
)
1556 # Unsafe version of `append_substring` for performance
1558 # NOTE: Use only if sure about `from` and `length`, no checks
1559 # or bound recalculation is done
1560 fun append_substring_impl
(s
: Text, from
, length
: Int) do
1561 var max
= from
+ length
1562 for i
in [from
.. max
[ do add s
[i
]
1566 var ret
= new Buffer.with_cap
(byte_length
* i
)
1567 for its
in [0 .. i
[ do ret
.append
self
1571 redef fun insert_at
(s
, pos
) do
1572 var obuf
= new Buffer.with_cap
(byte_length
+ s
.byte_length
)
1573 obuf
.append_substring
(self, 0, pos
)
1575 obuf
.append_substring
(self, pos
, length
- pos
)
1579 # Inserts `s` at position `pos`
1582 # var b = new Buffer
1584 # b.insert(" nit ", 3)
1585 # assert b == "美しい nit 世界"
1587 fun insert
(s
: Text, pos
: Int) is abstract
1589 # Inserts `c` at position `pos`
1592 # var b = new Buffer
1594 # b.insert_char(' ', 3)
1595 # assert b == "美しい 世界"
1597 fun insert_char
(c
: Char, pos
: Int) is abstract
1599 # Removes a substring from `self` at position `pos`
1601 # NOTE: `length` defaults to 1, expressed in chars
1604 # var b = new Buffer
1605 # b.append("美しい 世界")
1607 # assert b == "美しい世界"
1611 fun remove_at
(pos
: Int, length
: nullable Int) is abstract
1613 redef fun reversed
do
1619 redef fun to_upper
do
1625 redef fun to_lower
do
1631 redef fun to_snake_case
do
1637 # Takes a camel case `self` and converts it to snake case
1639 # SEE: `to_snake_case`
1641 if self.is_lower
then return
1642 var prev_is_lower
= false
1643 var prev_is_upper
= false
1648 if char
.is_lower
then
1649 prev_is_lower
= true
1650 prev_is_upper
= false
1651 else if char
.is_upper
then
1652 if prev_is_lower
then
1655 else if prev_is_upper
and i
+ 1 < length
and self[i
+ 1].is_lower
then
1659 self[i
] = char
.to_lower
1660 prev_is_lower
= false
1661 prev_is_upper
= true
1663 prev_is_lower
= false
1664 prev_is_upper
= false
1670 redef fun to_camel_case
1677 # Takes a snake case `self` and converts it to camel case
1679 # SEE: `to_camel_case`
1681 if is_upper
then return
1683 var underscore_count
= 0
1686 while pos
< length
do
1687 var char
= self[pos
]
1689 underscore_count
+= 1
1690 else if underscore_count
> 0 then
1691 pos
-= underscore_count
1692 remove_at
(pos
, underscore_count
)
1693 self[pos
] = char
.to_upper
1694 underscore_count
= 0
1698 if underscore_count
> 0 then remove_at
(pos
- underscore_count
- 1, underscore_count
)
1701 redef fun capitalized
(keep_upper
) do
1702 if length
== 0 then return self
1704 var buf
= new Buffer.with_cap
(byte_length
)
1705 buf
.capitalize
(keep_upper
=keep_upper
, src
=self)
1710 # View for chars on Buffer objects, extends Sequence
1711 # for mutation operations
1712 private abstract class BufferCharView
1713 super StringCharView
1714 super Sequence[Char]
1716 redef type SELFTYPE: Buffer
1720 # View for bytes on Buffer objects, extends Sequence
1721 # for mutation operations
1722 private abstract class BufferByteView
1723 super StringByteView
1725 redef type SELFTYPE: Buffer
1729 # User readable representation of `self`.
1730 fun to_s
: String do return inspect
1732 # The class name of the object in NativeString format.
1733 private fun native_class_name
: NativeString is intern
1735 # The class name of the object.
1737 # assert 5.class_name == "Int"
1738 fun class_name
: String do return native_class_name
.to_s
1740 # Developer readable representation of `self`.
1741 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1744 return "<{inspect_head}>"
1747 # Return "CLASSNAME:#OBJECTID".
1748 # This function is mainly used with the redefinition of the inspect method
1749 protected fun inspect_head
: String
1751 return "{class_name}:#{object_id.to_hex}"
1756 # assert true.to_s == "true"
1757 # assert false.to_s == "false"
1769 # C function to calculate the length of the `NativeString` to receive `self`
1770 private fun byte_to_s_len
: Int `{
1771 return snprintf(NULL, 0, "0x%02x", self);
1774 # C function to convert an nit Int to a NativeString (char*)
1775 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) `{
1776 snprintf(nstr, strlen, "0x%02x", self);
1779 # Displayable byte in its hexadecimal form (0x..)
1781 # assert 1.to_b.to_s == "0x01"
1782 # assert (-123).to_b.to_s == "0x85"
1784 var nslen
= byte_to_s_len
1785 var ns
= new NativeString(nslen
+ 1)
1787 native_byte_to_s
(ns
, nslen
+ 1)
1788 return ns
.to_s_unsafe
(nslen
)
1794 # Wrapper of strerror C function
1795 private fun strerror_ext
: NativeString `{ return strerror((int)self); `}
1797 # Returns a string describing error number
1798 fun strerror: String do return strerror_ext.to_s
1800 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if negative).
1801 # assume < to_c max const of char
1802 private fun fill_buffer(s: Buffer, base: Int)
1809 else if self == 0 then
1816 var pos = digit_count(base) - 1
1817 while pos >= 0 and n > 0 do
1818 s.chars[pos] = (n % base).to_c
1824 # C function to calculate the length of the `NativeString` to receive `self`
1825 private fun int_to_s_len: Int `{
1826 return snprintf
(NULL, 0, "%ld", self);
1829 # C function to convert an nit Int to a NativeString (char*)
1830 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1831 snprintf
(nstr
, strlen
, "%ld", self);
1834 # String representation of `self` in the given `base
`
1837 # assert 15.to_base(10) == "15"
1838 # assert 15.to_base(16) == "f"
1839 # assert 15.to_base(2) == "1111"
1840 # assert (-10).to_base(3) == "-101"
1842 fun to_base(base: Int): String
1844 var l = digit_count(base)
1847 for x in [0..l[ do s.add(' ')
1848 fill_buffer(s, base)
1853 # return displayable int in hexadecimal
1855 # assert 1.to_hex == "1"
1856 # assert (-255).to_hex == "-ff"
1857 fun to_hex: String do return to_base(16)
1861 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1863 # assert 12.34.to_s == "12.34"
1864 # assert (-0120.030).to_s == "-120.03"
1866 # see `to_precision
` for a custom precision.
1868 var str = to_precision( 3 )
1869 if is_inf != 0 or is_nan then return str
1870 var len = str.length
1871 for i in [0..len-1] do
1873 var c = str.chars[j]
1876 else if c == '.' then
1877 return str.substring( 0, j+2 )
1879 return str.substring( 0, j+1 )
1885 # `String` representation of `self` with the given number of `decimals
`
1887 # assert 12.345.to_precision(0) == "12"
1888 # assert 12.345.to_precision(3) == "12.345"
1889 # assert (-12.345).to_precision(3) == "-12.345"
1890 # assert (-0.123).to_precision(3) == "-0.123"
1891 # assert 0.999.to_precision(2) == "1.00"
1892 # assert 0.999.to_precision(4) == "0.9990"
1893 fun to_precision(decimals: Int): String
1895 if is_nan then return "nan"
1897 var isinf = self.is_inf
1900 else if isinf == -1 then
1904 if decimals == 0 then return self.to_i.to_s
1906 for i in [0..decimals[ do f = f * 10.0
1913 if i == 0 then return "0." + "0"*decimals
1915 # Prepare both parts of the float, before and after the "."
1920 if sl > decimals then
1921 # Has something before the "."
1922 p1 = s.substring(0, sl-decimals)
1923 p2 = s.substring(sl-decimals, decimals)
1926 p2 = "0"*(decimals-sl) + s
1929 if i < 0 then p1 = "-" + p1
1931 return p1 + "." + p2
1937 # Returns a sequence with the UTF-8 bytes of `self`
1939 # assert 'a'.bytes == [0x61u8]
1940 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1941 fun bytes: SequenceRead[Byte] do return to_s.bytes
1943 # Is `self` an UTF-16 surrogate pair ?
1944 fun is_surrogate: Bool do
1946 return cp >= 0xD800 and cp <= 0xDFFF
1949 # Is `self` a UTF-16 high surrogate ?
1950 fun is_hi_surrogate: Bool do
1952 return cp >= 0xD800 and cp <= 0xDBFF
1955 # Is `self` a UTF-16 low surrogate ?
1956 fun is_lo_surrogate: Bool do
1958 return cp >= 0xDC00 and cp <= 0xDFFF
1961 # Length of `self` in a UTF-8 String
1962 fun u8char_len: Int do
1963 var c = self.code_point
1964 if c < 0x80 then return 1
1965 if c <= 0x7FF then return 2
1966 if c <= 0xFFFF then return 3
1967 if c <= 0x10FFFF then return 4
1968 # Bad character format
1972 # assert 'x'.to_s == "x"
1975 var ns = new NativeString(ln + 1)
1977 return ns.to_s_unsafe(ln)
1980 # Returns `self` escaped to UTF-16
1982 # i.e. Represents `self`.`code_point
` using UTF-16 codets escaped
1985 # assert 'A'.escape_to_utf16 == "\\u0041"
1986 # assert 'è'.escape_to_utf16 == "\\u00e8"
1987 # assert 'あ'.escape_to_utf16 == "\\u3042"
1988 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
1989 fun escape_to_utf16: String do
1992 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
1993 buf = new Buffer.with_cap(6)
1994 buf.append("\\u0000")
1997 for i in hx.chars.reverse_iterator do
2002 buf = new Buffer.with_cap(12)
2003 buf.append("\\u0000\\u0000")
2004 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
2005 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
2020 private fun u8char_tos(r: NativeString, len: Int) `{
2027 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
2028 r
[1] = 0x80 | (self & 0x3F);
2031 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
2032 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
2033 r
[2] = 0x80 | (self & 0x3F);
2036 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
2037 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
2038 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
2039 r
[3] = 0x80 | (self & 0x3F);
2044 # Returns true if the char is a numerical digit
2046 # assert '0'.is_numeric
2047 # assert '9'.is_numeric
2048 # assert not 'a'.is_numeric
2049 # assert not '?'.is_numeric
2051 # FIXME: Works on ASCII-range only
2052 fun is_numeric: Bool
2054 return self >= '0' and self <= '9'
2057 # Returns true if the char is an alpha digit
2059 # assert 'a'.is_alpha
2060 # assert 'Z'.is_alpha
2061 # assert not '0'.is_alpha
2062 # assert not '?'.is_alpha
2064 # FIXME: Works on ASCII-range only
2067 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2070 # Is `self` an hexadecimal digit ?
2072 # assert 'A'.is_hexdigit
2073 # assert not 'G'.is_hexdigit
2074 # assert 'a'.is_hexdigit
2075 # assert not 'g'.is_hexdigit
2076 # assert '5'.is_hexdigit
2077 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
2078 (self >= 'a' and self <= 'f')
2080 # Returns true if the char is an alpha or a numeric digit
2082 # assert 'a'.is_alphanumeric
2083 # assert 'Z'.is_alphanumeric
2084 # assert '0'.is_alphanumeric
2085 # assert '9'.is_alphanumeric
2086 # assert not '?'.is_alphanumeric
2088 # FIXME: Works on ASCII-range only
2089 fun is_alphanumeric: Bool
2091 return self.is_numeric or self.is_alpha
2094 # Returns `self` to its int value
2096 # REQUIRE: `is_hexdigit
`
2097 fun from_hex: Int do
2098 if self >= '0' and self <= '9' then return code_point - 0x30
2099 if self >= 'A' and self <= 'F' then return code_point - 0x37
2100 if self >= 'a' and self <= 'f' then return code_point - 0x57
2101 # Happens if self is not a hexdigit
2102 assert self.is_hexdigit
2103 # To make flow analysis happy
2108 redef class Collection[E]
2109 # String representation of the content of the collection.
2111 # The standard representation is the list of elements separated with commas.
2114 # assert [1,2,3].to_s == "[1,2,3]"
2115 # assert [1..3].to_s == "[1,2,3]"
2116 # assert (new Array[Int]).to_s == "[]" # empty collection
2119 # Subclasses may return a more specific string representation.
2122 return "[" + join(",") + "]"
2125 # Concatenate elements without separators
2128 # assert [1,2,3].plain_to_s == "123"
2129 # assert [11..13].plain_to_s == "111213"
2130 # assert (new Array[Int]).plain_to_s == "" # empty collection
2132 fun plain_to_s: String
2135 for e in self do if e != null then s.append(e.to_s)
2139 # Concatenate and separate each elements with `separator
`.
2141 # Only concatenate if `separator
== null`.
2143 # assert [1, 2, 3].join(":") == "1:2:3"
2144 # assert [1..3].join(":") == "1:2:3"
2145 # assert [1..3].join == "123"
2147 # if `last_separator
` is given, then it is used to separate the last element.
2149 # assert [1, 2, 3, 4].join(", ", " and ") == "1, 2, 3 and 4"
2150 fun join(separator: nullable Text, last_separator: nullable Text): String
2152 if is_empty then return ""
2154 var s = new Buffer # Result
2159 if e != null then s.append(e.to_s)
2161 if last_separator == null then last_separator = separator
2163 # Concat other items
2169 if separator != null then s.append(separator)
2171 if last_separator != null then s.append(last_separator)
2173 if e != null then s.append(e.to_s)
2179 redef class Map[K,V]
2180 # Concatenate couples of key value.
2181 # Key and value are separated by `couple_sep
`.
2182 # Couples are separated by `sep
`.
2184 # var m = new HashMap[Int, String]
2187 # assert m.join("; ", "=") == "1=one; 10=ten"
2188 fun join(sep, couple_sep: String): String is abstract
2192 private var args_cache: nullable Sequence[String] = null
2194 # The arguments of the program as given by the OS
2195 fun program_args: Sequence[String]
2197 if _args_cache == null then init_args
2198 return _args_cache.as(not null)
2201 # The name of the program as given by the OS
2202 fun program_name: String
2204 return native_argv(0).to_s
2207 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2208 private fun init_args
2210 var argc = native_argc
2211 var args = new Array[String].with_capacity(0)
2214 args[i-1] = native_argv(i).to_s
2220 # First argument of the main C function.
2221 private fun native_argc: Int is intern
2223 # Second argument of the main C function.
2224 private fun native_argv(i: Int): NativeString is intern
2227 # Comparator that efficienlty use `to_s
` to compare things
2229 # The comparaison call `to_s
` on object and use the result to order things.
2231 # var a = [1, 2, 3, 10, 20]
2232 # (new CachedAlphaComparator).sort(a)
2233 # assert a == [1, 10, 2, 20, 3]
2235 # Internally the result of `to_s
` is cached in a HashMap to counter
2236 # uneficient implementation of `to_s
`.
2238 # Note: it caching is not usefull, see `alpha_comparator
`
2239 class CachedAlphaComparator
2241 redef type COMPARED: Object
2243 private var cache = new HashMap[Object, String]
2245 private fun do_to_s(a: Object): String do
2246 if cache.has_key(a) then return cache[a]
2252 redef fun compare(a, b) do
2253 return do_to_s(a) <=> do_to_s(b)
2257 # see `alpha_comparator
`
2258 private class AlphaComparator
2260 redef fun compare(a, b) do
2261 if a == b then return 0
2262 if a == null then return -1
2263 if b == null then return 1
2264 return a.to_s <=> b.to_s
2268 # Stateless comparator that naively use `to_s
` to compare things.
2270 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2271 # on a single instace. See `CachedAlphaComparator` as an alternative.
2273 # var a = [1, 2, 3, 10, 20]
2274 # alpha_comparator.sort(a)
2275 # assert a == [1, 10, 2, 20, 3]
2276 fun alpha_comparator: Comparator do return once new AlphaComparator
2278 # The arguments of the program as given by the OS
2279 fun args: Sequence[String]
2281 return sys.program_args
2284 redef class NativeString
2285 # Get a `String` from the data at `self` copied into Nit memory
2287 # Require: `self` is a null-terminated string.
2288 fun to_s_with_copy: String is abstract
2290 # Get a `String` from `length
` bytes at `self`
2292 # The result may point to the data at `self` or
2293 # it may make a copy in Nit controlled memory.
2294 # This method should only be used when `self` was allocated by the Nit GC,
2295 # or when manually controlling the deallocation of `self`.
2296 fun to_s_with_length(length: Int): String is abstract
2298 # Get a `String` from the raw `length
` bytes at `self`
2300 # The default value of `length
` is the number of bytes before
2301 # the first null character.
2303 # The created `String` points to the data at `self`.
2304 # This method should be used when `self` was allocated by the Nit GC,
2305 # or when manually controlling the deallocation of `self`.
2307 # /!\: This service does not clean the items for compliance with UTF-8,
2308 # use only when the data has already been verified as valid UTF-8.
2309 fun to_s_unsafe(length: nullable Int): String is abstract
2311 # Get a `String` from the raw `byte_length
` bytes at `self` with `unilen
` Unicode characters
2313 # The created `String` points to the data at `self`.
2314 # This method should be used when `self` was allocated by the Nit GC,
2315 # or when manually controlling the deallocation of `self`.
2317 # /!\: This service does not clean the items for compliance with UTF-8,
2318 # use only when the data has already been verified as valid UTF-8.
2320 # SEE: `abstract_text
::Text` for more info on the difference
2321 # between `Text::byte_length
` and `Text::length
`.
2322 fun to_s_full(byte_length, unilen: Int): String is abstract
2324 # Copies the content of `src
` to `self`
2326 # NOTE: `self` must be large enough to withold `self.byte_length
` bytes
2327 fun fill_from(src: Text) do src.copy_to_native(self, src.byte_length, 0, 0)
2330 redef class NativeArray[E]
2331 # Join all the elements using `to_s
`
2333 # REQUIRE: `self isa NativeArray[String]`
2334 # REQUIRE: all elements are initialized
2335 fun native_to_s: String is abstract