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
29 redef type OTHER: Text
31 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
34 # Gets a view on the chars of the Text object
36 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
37 fun chars
: SequenceRead[Char] is abstract
39 # Gets a view on the bytes of the Text object
41 # assert "hello".bytes.to_a == [104u8, 101u8, 108u8, 108u8, 111u8]
42 fun bytes
: SequenceRead[Byte] is abstract
44 # Number of characters contained in self.
46 # assert "12345".length == 5
47 # assert "".length == 0
48 # assert "あいうえお".length == 5
49 fun length
: Int is abstract
51 # Number of bytes in `self`
53 # assert "12345".bytelen == 5
54 # assert "あいうえお".bytelen == 15
55 fun bytelen
: Int is abstract
59 # assert "abcd".substring(1, 2) == "bc"
60 # assert "abcd".substring(-1, 2) == "a"
61 # assert "abcd".substring(1, 0) == ""
62 # assert "abcd".substring(2, 5) == "cd"
63 # assert "あいうえお".substring(1,3) == "いうえ"
65 # A `from` index < 0 will be replaced by 0.
66 # Unless a `count` value is > 0 at the same time.
67 # In this case, `from += count` and `count -= from`.
68 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
70 # Iterates on the substrings of self if any
71 fun substrings
: Iterator[FlatText] is abstract
73 # Is the current Text empty (== "")
76 # assert not "foo".is_empty
77 fun is_empty
: Bool do return self.length
== 0
79 # Returns an empty Text of the right type
81 # This method is used internally to get the right
82 # implementation of an empty string.
83 protected fun empty
: SELFTYPE is abstract
85 # Gets the first char of the Text
87 # DEPRECATED : Use self.chars.first instead
88 fun first
: Char do return self.chars
[0]
90 # Access a character at `index` in the string.
92 # assert "abcd"[2] == 'c'
94 # DEPRECATED : Use self.chars.[] instead
95 fun [](index
: Int): Char do return self.chars
[index
]
97 # Gets the index of the first occurence of 'c'
99 # Returns -1 if not found
101 # DEPRECATED : Use self.chars.index_of instead
102 fun index_of
(c
: Char): Int
104 return index_of_from
(c
, 0)
107 # Gets the last char of self
109 # DEPRECATED : Use self.chars.last instead
110 fun last
: Char do return self.chars
[length-1
]
112 # Gets the index of the first occurence of ´c´ starting from ´pos´
114 # Returns -1 if not found
116 # DEPRECATED : Use self.chars.index_of_from instead
117 fun index_of_from
(c
: Char, pos
: Int): Int
119 var iter
= self.chars
.iterator_from
(pos
)
121 if iter
.item
== c
then return iter
.index
127 # Gets the last index of char ´c´
129 # Returns -1 if not found
131 # DEPRECATED : Use self.chars.last_index_of instead
132 fun last_index_of
(c
: Char): Int
134 return last_index_of_from
(c
, length
- 1)
137 # Return a null terminated char *
138 fun to_cstring
: NativeString is abstract
140 # The index of the last occurrence of an element starting from pos (in reverse order).
142 # var s = "/etc/bin/test/test.nit"
143 # assert s.last_index_of_from('/', s.length-1) == 13
144 # assert s.last_index_of_from('/', 12) == 8
146 # Returns -1 if not found
148 # DEPRECATED : Use self.chars.last_index_of_from instead
149 fun last_index_of_from
(item
: Char, pos
: Int): Int
151 var iter
= self.chars
.reverse_iterator_from
(pos
)
153 if iter
.item
== item
then return iter
.index
159 # Gets an iterator on the chars of self
161 # DEPRECATED : Use self.chars.iterator instead
162 fun iterator
: Iterator[Char]
164 return self.chars
.iterator
168 # Gets an Array containing the chars of self
170 # DEPRECATED : Use self.chars.to_a instead
171 fun to_a
: Array[Char] do return chars
.to_a
173 # Create a substring from `self` beginning at the `from` position
175 # assert "abcd".substring_from(1) == "bcd"
176 # assert "abcd".substring_from(-1) == "abcd"
177 # assert "abcd".substring_from(2) == "cd"
179 # As with substring, a `from` index < 0 will be replaced by 0
180 fun substring_from
(from
: Int): SELFTYPE
182 if from
>= self.length
then return empty
183 if from
< 0 then from
= 0
184 return substring
(from
, length
- from
)
187 # Does self have a substring `str` starting from position `pos`?
189 # assert "abcd".has_substring("bc",1) == true
190 # assert "abcd".has_substring("bc",2) == false
192 # Returns true iff all characters of `str` are presents
193 # at the expected index in `self.`
194 # The first character of `str` being at `pos`, the second
195 # character being at `pos+1` and so on...
197 # This means that all characters of `str` need to be inside `self`.
199 # assert "abcd".has_substring("xab", -1) == false
200 # assert "abcd".has_substring("cdx", 2) == false
202 # And that the empty string is always a valid substring.
204 # assert "abcd".has_substring("", 2) == true
205 # assert "abcd".has_substring("", 200) == true
206 fun has_substring
(str
: String, pos
: Int): Bool
208 if str
.is_empty
then return true
209 if pos
< 0 or pos
+ str
.length
> length
then return false
210 var myiter
= self.chars
.iterator_from
(pos
)
211 var itsiter
= str
.chars
.iterator
212 while myiter
.is_ok
and itsiter
.is_ok
do
213 if myiter
.item
!= itsiter
.item
then return false
217 if itsiter
.is_ok
then return false
221 # Is this string prefixed by `prefix`?
223 # assert "abcd".has_prefix("ab") == true
224 # assert "abcbc".has_prefix("bc") == false
225 # assert "ab".has_prefix("abcd") == false
226 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
228 # Is this string suffixed by `suffix`?
230 # assert "abcd".has_suffix("abc") == false
231 # assert "abcd".has_suffix("bcd") == true
232 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
234 # Returns `self` as the corresponding integer
236 # assert "123".to_i == 123
237 # assert "-1".to_i == -1
238 # assert "0x64".to_i == 100
239 # assert "0b1100_0011".to_i== 195
240 # assert "--12".to_i == 12
242 # REQUIRE: `self`.`is_int`
243 fun to_i
: Int is abstract
245 # If `self` contains a float, return the corresponding float
247 # assert "123".to_f == 123.0
248 # assert "-1".to_f == -1.0
249 # assert "-1.2e-3".to_f == -0.0012
253 return to_s
.to_cstring
.atof
256 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
258 # assert "ff".to_hex == 255
259 fun to_hex
: Int do return a_to
(16)
261 # If `self` contains only digits <= '7', return the corresponding integer.
263 # assert "714".to_oct == 460
264 fun to_oct
: Int do return a_to
(8)
266 # If `self` contains only '0' et '1', return the corresponding integer.
268 # assert "101101".to_bin == 45
269 fun to_bin
: Int do return a_to
(2)
271 # If `self` contains only digits '0' .. '9', return the corresponding integer.
273 # assert "108".to_dec == 108
274 fun to_dec
: Int do return a_to
(10)
276 # If `self` contains only digits and letters, return the corresponding integer in a given base
278 # assert "120".a_to(3) == 15
279 fun a_to
(base
: Int) : Int
284 for j
in [0..length
[ do
306 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
308 # assert "123".is_numeric == true
309 # assert "1.2".is_numeric == true
310 # assert "1,2".is_numeric == true
311 # assert "1..2".is_numeric == false
314 var has_point_or_comma
= false
315 for i
in [0..length
[ do
317 if not c
.is_numeric
then
318 if (c
== '.' or c
== ',') and not has_point_or_comma
then
319 has_point_or_comma
= true
328 # Returns `true` if the string contains only Hex chars
330 # assert "048bf".is_hex == true
331 # assert "ABCDEF".is_hex == true
332 # assert "0G".is_hex == false
335 for i
in [0..length
[ do
337 if not (c
>= 'a' and c
<= 'f') and
338 not (c
>= 'A' and c
<= 'F') and
339 not (c
>= '0' and c
<= '9') then return false
344 # Returns `true` if the string contains only Binary digits
346 # assert "1101100".is_bin == true
347 # assert "1101020".is_bin == false
349 for i
in chars
do if i
!= '0' and i
!= '1' then return false
353 # Returns `true` if the string contains only Octal digits
355 # assert "213453".is_oct == true
356 # assert "781".is_oct == false
358 for i
in chars
do if i
< '0' or i
> '7' then return false
362 # Returns `true` if the string contains only Decimal digits
364 # assert "10839".is_dec == true
365 # assert "164F".is_dec == false
367 for i
in chars
do if i
< '0' or i
> '9' then return false
371 # Are all letters in `self` upper-case ?
373 # assert "HELLO WORLD".is_upper == true
374 # assert "%$&%!".is_upper == true
375 # assert "hello world".is_upper == false
376 # assert "Hello World".is_upper == false
379 for i
in [0..length
[ do
381 if char
.is_lower
then return false
386 # Are all letters in `self` lower-case ?
388 # assert "hello world".is_lower == true
389 # assert "%$&%!".is_lower == true
390 # assert "Hello World".is_lower == false
393 for i
in [0..length
[ do
395 if char
.is_upper
then return false
400 # Removes the whitespaces at the beginning of self
402 # assert " \n\thello \n\t".l_trim == "hello \n\t"
404 # `Char::is_whitespace` determines what is a whitespace.
407 var iter
= self.chars
.iterator
409 if not iter
.item
.is_whitespace
then break
412 if iter
.index
== length
then return self.empty
413 return self.substring_from
(iter
.index
)
416 # Removes the whitespaces at the end of self
418 # assert " \n\thello \n\t".r_trim == " \n\thello"
420 # `Char::is_whitespace` determines what is a whitespace.
423 var iter
= self.chars
.reverse_iterator
425 if not iter
.item
.is_whitespace
then break
428 if iter
.index
< 0 then return self.empty
429 return self.substring
(0, iter
.index
+ 1)
432 # Trims trailing and preceding white spaces
434 # assert " Hello World ! ".trim == "Hello World !"
435 # assert "\na\nb\tc\t".trim == "a\nb\tc"
437 # `Char::is_whitespace` determines what is a whitespace.
438 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
440 # Is the string non-empty but only made of whitespaces?
442 # assert " \n\t ".is_whitespace == true
443 # assert " hello ".is_whitespace == false
444 # assert "".is_whitespace == false
446 # `Char::is_whitespace` determines what is a whitespace.
447 fun is_whitespace
: Bool
449 if is_empty
then return false
450 for c
in self.chars
do
451 if not c
.is_whitespace
then return false
456 # Returns `self` removed from its last line terminator (if any).
458 # assert "Hello\n".chomp == "Hello"
459 # assert "Hello".chomp == "Hello"
461 # assert "\n".chomp == ""
462 # assert "".chomp == ""
464 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
465 # A single line terminator, the last one, is removed.
467 # assert "\r\n".chomp == ""
468 # assert "\r\n\n".chomp == "\r\n"
469 # assert "\r\n\r\n".chomp == "\r\n"
470 # assert "\r\n\r".chomp == "\r\n"
472 # Note: unlike with most IO methods like `Reader::read_line`,
473 # a single `\r` is considered here to be a line terminator and will be removed.
477 if len
== 0 then return self
478 var l
= self.chars
.last
480 return substring
(0, len-1
)
481 else if l
!= '\n' then
483 else if len
> 1 and self.chars
[len-2
] == '\r' then
484 return substring
(0, len-2
)
486 return substring
(0, len-1
)
490 # Justify a self in a space of `length`
492 # `left` is the space ratio on the left side.
493 # * 0.0 for left-justified (no space at the left)
494 # * 1.0 for right-justified (all spaces at the left)
495 # * 0.5 for centered (half the spaces at the left)
499 # assert "hello".justify(10, 0.0) == "hello "
500 # assert "hello".justify(10, 1.0) == " hello"
501 # assert "hello".justify(10, 0.5) == " hello "
503 # If `length` is not enough, `self` is returned as is.
505 # assert "hello".justify(2, 0.0) == "hello"
507 # REQUIRE: `left >= 0.0 and left <= 1.0`
508 # ENSURE: `self.length <= length implies result.length == length`
509 # ENSURE: `self.length >= length implies result == self`
510 fun justify
(length
: Int, left
: Float): String
512 var diff
= length
- self.length
513 if diff
<= 0 then return to_s
514 assert left
>= 0.0 and left
<= 1.0
515 var before
= (diff
.to_f
* left
).to_i
516 return " " * before
+ self + " " * (diff-before
)
519 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
521 # This method is injective (two different inputs never produce the same
522 # output) and the returned string always respect the following rules:
524 # * Contains only US-ASCII letters, digits and underscores.
525 # * Never starts with a digit.
526 # * Never ends with an underscore.
527 # * Never contains two contiguous underscores.
529 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
530 # assert "__".to_cmangle == "_95d_95d"
531 # assert "__d".to_cmangle == "_95d_d"
532 # assert "_d_".to_cmangle == "_d_95d"
533 # assert "_42".to_cmangle == "_95d42"
534 # assert "foo".to_cmangle == "foo"
535 # assert "".to_cmangle == ""
536 fun to_cmangle
: String
538 if is_empty
then return ""
540 var underscore
= false
544 if c
>= '0' and c
<= '9' then
546 res
.append
(c
.ascii
.to_s
)
550 for i
in [start
..length
[ do
552 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
558 res
.append
('_'.ascii
.to_s
)
561 if c
>= '0' and c
<= '9' then
564 else if c
== '_' then
569 res
.append
(c
.ascii
.to_s
)
575 res
.append
('_'.ascii
.to_s
)
581 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
583 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
584 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
586 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
587 # Three digits are always used to avoid following digits to be interpreted as an element
588 # of the octal sequence.
590 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
592 # The exceptions are the common `\t` and `\n`.
593 fun escape_to_c
: String
596 for i
in [0..length
[ do
600 else if c
== '\t' then
602 else if c
== '"' then
604 else if c == '\'' then
606 else if c == '\\
' then
608 else if c.ascii < 32 then
610 var oct = c.ascii.to_base(8, false)
611 # Force 3 octal digits since it is the
612 # maximum allowed in the C specification
613 if oct.length == 1 then
616 else if oct.length == 2 then
627 # Escape additionnal characters
628 # The result might no be legal in C but be used in other languages
630 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
631 fun escape_more_to_c(chars: String): String
634 for c in escape_to_c.chars do
635 if chars.chars.has(c) then
643 # Escape to C plus braces
645 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
646 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
648 # Escape to POSIX Shell (sh).
650 # Abort if the text contains a null byte.
652 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
653 fun escape_to_sh
: String do
656 for i in [0..length[ do
661 assert without_null_byte
: c
!= '\0'
669 # Escape to include in a Makefile
671 # Unfortunately, some characters are not escapable in Makefile.
672 # These characters are `;`, `|`, `\`, and the non-printable ones.
673 # They will be rendered as `"?{hex}"`.
674 fun escape_to_mk: String do
676 for i in [0..length[ do
680 else if c == ':' or c == ' ' or c == '#' then
683 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
684 b
.append
("?{c.ascii.to_base(16, false)}")
692 # Return a string where Nit escape sequences are transformed.
695 # assert s.length == 2
696 # var u = s.unescape_nit
697 # assert u.length == 1
698 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
699 fun unescape_nit
: String
701 var res
= new Buffer.with_cap
(self.length
)
702 var was_slash
= false
703 for i
in [0..length
[ do
705 if not was_slash
then
716 else if c
== 'r' then
718 else if c
== 't' then
720 else if c
== '0' then
729 # Encode `self` to percent (or URL) encoding
731 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
732 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
733 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
734 fun to_percent_encoding
: String
738 for i
in [0..length
[ do
740 if (c
>= '0' and c
<= '9') or
741 (c
>= 'a' and c
<= 'z') or
742 (c
>= 'A' and c
<= 'Z') or
743 c
== '-' or c
== '.' or
747 else buf
.append
"%{c.ascii.to_hex}"
753 # Decode `self` from percent (or URL) encoding to a clear string
755 # Replace invalid use of '%' with '?'.
757 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
758 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
759 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
760 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
761 # assert "incomplete %".from_percent_encoding == "incomplete ?"
762 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
763 fun from_percent_encoding
: String
771 if i
+ 2 >= length
then
772 # What follows % has been cut off
776 var hex_s
= substring
(i
, 2)
778 var hex_i
= hex_s
.to_hex
782 # What follows a % is not Hex
795 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
797 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
799 # 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>
800 fun html_escape
: String
804 for i
in [0..length
[ do
808 else if c
== '<' then
810 else if c
== '>' then
812 else if c
== '"' then
814 else if c
== '\'' then
816 else if c == '/' then
825 # Two pieces of text are equals if thez have the same characters in the same order.
827 # assert "hello" == "hello"
828 # assert "hello" != "HELLO"
829 # assert "hello" == "hel"+"lo"
831 # Things that are not Text are not equal.
834 # assert "9" != ['9']
837 # assert "9".chars.first == '9' # equality of Char
838 # assert "9".chars == ['9'] # equality of Sequence
839 # assert "9".to_i == 9 # equality of Int
842 if o == null then return false
843 if not o isa Text then return false
844 if self.is_same_instance(o) then return true
845 if self.length != o.length then return false
846 return self.chars == o.chars
849 # Lexicographical comparaison
851 # assert "abc" < "xy"
852 # assert "ABC" < "abc"
855 var self_chars = self.chars.iterator
856 var other_chars = other.chars.iterator
858 while self_chars.is_ok and other_chars.is_ok do
859 if self_chars.item < other_chars.item then return true
860 if self_chars.item > other_chars.item then return false
865 if self_chars.is_ok then
872 # Escape string used in labels for graphviz
874 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
875 fun escape_to_dot: String
877 return escape_more_to_c("|\{\}<>")
880 private var hash_cache: nullable Int = null
884 if hash_cache == null then
885 # djb2 hash algorithm
888 for i in [0..length[ do
890 h = (h << 5) + h + char.ascii
895 return hash_cache.as(not null)
898 # Gives the formatted string back as a Nit string with `args` in place
900 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
901 # assert "\\%1 This string".format("String") == "\\%1 This string"
902 fun format(args: Object...): String do
903 var s = new Array[Text]
907 # Skip escaped characters
908 if self[i] == '\\
' then
911 else if self[i] == '%' then
915 while i < length and self[i].is_numeric do
920 var ciph_len = fmt_end - ciph_st + 1
922 var arg_index = substring(ciph_st, ciph_len).to_i - 1
923 if arg_index >= args.length then continue
925 s.push substring(curr_st, fmt_st - curr_st)
926 s.push args[arg_index].to_s
931 s.push substring(curr_st, length - curr_st)
935 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
937 # Basically a high-level synonym of NativeString::copy_to
939 # REQUIRE: `n` must be large enough to contain `len` bytes
941 # var ns = new NativeString(8)
942 # "Text is String".copy_to_native(ns, 8, 2, 0)
943 # assert ns.to_s_with_length(8) == "xt is St"
945 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
946 var mypos = src_offset
947 var itspos = dest_offset
949 dest[itspos] = self.bytes[mypos]
958 # All kinds of array-based text representations.
959 abstract class FlatText
962 # Underlying C-String (`char*`)
964 # Warning : Might be void in some subclasses, be sure to check
965 # if set before using it.
966 private var items: NativeString is noinit
968 # Real items, used as cache for to_cstring is called
969 private var real_items: nullable NativeString = null
971 # Returns a char* starting at position `first_byte`
973 # WARNING: If you choose to use this service, be careful of the following.
975 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
976 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
977 # deallocated at any moment, rendering the pointer returned by this function invalid.
978 # Any access to freed memory may very likely cause undefined behaviour or a crash.
979 # (Failure to do so will most certainly result in long and painful debugging hours)
981 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
982 # then immediately return).
984 # As always, do not modify the content of the String in C code, if this is what you want
985 # copy locally the char* as Nit Strings are immutable.
986 private fun fast_cstring: NativeString is abstract
990 redef var bytelen = 0
1001 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1002 items.copy_to(dest, n, src_offset, dest_offset)
1006 # Abstract class for the SequenceRead compatible
1007 # views on the chars of any Text
1008 private abstract class StringCharView
1009 super SequenceRead[Char]
1013 var target: SELFTYPE
1015 redef fun is_empty do return target.is_empty
1017 redef fun length do return target.length
1019 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1021 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1024 # Abstract class for the SequenceRead compatible
1025 # views on the bytes of any Text
1026 private abstract class StringByteView
1027 super SequenceRead[Byte]
1031 var target: SELFTYPE
1033 redef fun is_empty do return target.is_empty
1035 redef fun length do return target.length
1037 redef fun iterator do return self.iterator_from(0)
1039 redef fun reverse_iterator do return self.reverse_iterator_from(target.bytelen - 1)
1042 # Immutable sequence of characters.
1044 # String objects may be created using literals.
1046 # assert "Hello World!" isa String
1047 abstract class String
1050 redef type SELFTYPE: String is fixed
1052 redef fun to_s do return self
1054 # Concatenates `o` to `self`
1056 # assert "hello" + "world" == "helloworld"
1057 # assert "" + "hello" + "" == "hello"
1058 fun +(o: Text): SELFTYPE is abstract
1060 # Concatenates self `i` times
1062 # assert "abc" * 4 == "abcabcabcabc"
1063 # assert "abc" * 1 == "abc"
1064 # assert "abc" * 0 == ""
1065 fun *(i: Int): SELFTYPE is abstract
1067 # Insert `s` at `pos`.
1069 # assert "helloworld".insert_at(" ", 5) == "hello world"
1070 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1072 redef fun substrings is abstract
1074 # Returns a reversed version of self
1076 # assert "hello".reversed == "olleh"
1077 # assert "bob".reversed == "bob"
1078 # assert "".reversed == ""
1079 fun reversed: SELFTYPE is abstract
1081 # A upper case version of `self`
1083 # assert "Hello World!".to_upper == "HELLO WORLD!"
1084 fun to_upper: SELFTYPE is abstract
1086 # A lower case version of `self`
1088 # assert "Hello World!".to_lower == "hello world!"
1089 fun to_lower : SELFTYPE is abstract
1091 # Takes a camel case `self` and converts it to snake case
1093 # assert "randomMethodId".to_snake_case == "random_method_id"
1095 # The rules are the following:
1097 # An uppercase is always converted to a lowercase
1099 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1101 # An uppercase that follows a lowercase is prefixed with an underscore
1103 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1105 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1107 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1109 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1111 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1112 fun to_snake_case: SELFTYPE
1114 if self.is_lower then return self
1116 var new_str = new Buffer.with_cap(self.length)
1117 var prev_is_lower = false
1118 var prev_is_upper = false
1120 for i in [0..length[ do
1122 if char.is_lower then
1124 prev_is_lower = true
1125 prev_is_upper = false
1126 else if char.is_upper then
1127 if prev_is_lower then
1129 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1132 new_str.add(char.to_lower)
1133 prev_is_lower = false
1134 prev_is_upper = true
1137 prev_is_lower = false
1138 prev_is_upper = false
1145 # Takes a snake case `self` and converts it to camel case
1147 # assert "random_method_id".to_camel_case == "randomMethodId"
1149 # If the identifier is prefixed by an underscore, the underscore is ignored
1151 # assert "_private_field".to_camel_case == "_privateField"
1153 # If `self` is upper, it is returned unchanged
1155 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1157 # If there are several consecutive underscores, they are considered as a single one
1159 # assert "random__method_id".to_camel_case == "randomMethodId"
1160 fun to_camel_case: SELFTYPE
1162 if self.is_upper then return self
1164 var new_str = new Buffer
1165 var is_first_char = true
1166 var follows_us = false
1168 for i in [0..length[ do
1170 if is_first_char then
1172 is_first_char = false
1173 else if char == '_
' then
1175 else if follows_us then
1176 new_str.add(char.to_upper)
1186 # Returns a capitalized `self`
1188 # Letters that follow a letter are lowercased
1189 # Letters that follow a non-letter are upcased.
1191 # SEE : `Char::is_letter` for the definition of letter.
1193 # assert "jAVASCRIPT".capitalized == "Javascript"
1194 # assert "i am root".capitalized == "I Am Root"
1195 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1196 fun capitalized: SELFTYPE do
1197 if length == 0 then return self
1199 var buf = new Buffer.with_cap(length)
1201 var curr = chars[0].to_upper
1205 for i in [1 .. length[ do
1208 if prev.is_letter then
1209 buf[i] = curr.to_lower
1211 buf[i] = curr.to_upper
1219 # A mutable sequence of characters.
1220 abstract class Buffer
1223 # Returns an arbitrary subclass of `Buffer` with default parameters
1226 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1227 new with_cap(i: Int) is abstract
1229 redef type SELFTYPE: Buffer is fixed
1231 # Specific implementations MUST set this to `true` in order to invalidate caches
1232 protected var is_dirty = true
1234 # Copy-On-Write flag
1236 # If the `Buffer` was to_s'd
, the next in-place altering
1237 # operation will cause the current `Buffer` to be re-allocated.
1239 # The flag will then be set at `false`.
1240 protected var written
= false
1242 # Modifies the char contained at pos `index`
1244 # DEPRECATED : Use self.chars.[]= instead
1245 fun []=(index
: Int, item
: Char) is abstract
1247 # Adds a char `c` at the end of self
1249 # DEPRECATED : Use self.chars.add instead
1250 fun add
(c
: Char) is abstract
1254 # var b = new Buffer
1256 # assert not b.is_empty
1259 fun clear
is abstract
1261 # Enlarges the subsequent array containing the chars of self
1262 fun enlarge
(cap
: Int) is abstract
1264 # Adds the content of text `s` at the end of self
1266 # var b = new Buffer
1269 # assert b == "helloworld"
1270 fun append
(s
: Text) is abstract
1272 # `self` is appended in such a way that `self` is repeated `r` times
1274 # var b = new Buffer
1277 # assert b == "hellohellohello"
1278 fun times
(r
: Int) is abstract
1280 # Reverses itself in-place
1282 # var b = new Buffer
1285 # assert b == "olleh"
1286 fun reverse
is abstract
1288 # Changes each lower-case char in `self` by its upper-case variant
1290 # var b = new Buffer
1291 # b.append("Hello World!")
1293 # assert b == "HELLO WORLD!"
1294 fun upper
is abstract
1296 # Changes each upper-case char in `self` by its lower-case variant
1298 # var b = new Buffer
1299 # b.append("Hello World!")
1301 # assert b == "hello world!"
1302 fun lower
is abstract
1304 # Capitalizes each word in `self`
1306 # Letters that follow a letter are lowercased
1307 # Letters that follow a non-letter are upcased.
1309 # SEE: `Char::is_letter` for the definition of a letter.
1311 # var b = new FlatBuffer.from("jAVAsCriPt")
1313 # assert b == "Javascript"
1314 # b = new FlatBuffer.from("i am root")
1316 # assert b == "I Am Root"
1317 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1319 # assert b == "Ab_C -Ab0C Ab\nC"
1321 if length
== 0 then return
1322 var c
= self[0].to_upper
1325 for i
in [1 .. length
[ do
1328 if prev
.is_letter
then
1329 self[i
] = c
.to_lower
1331 self[i
] = c
.to_upper
1338 if is_dirty
then hash_cache
= null
1342 # In Buffers, the internal sequence of character is mutable
1343 # Thus, `chars` can be used to modify the buffer.
1344 redef fun chars
: Sequence[Char] is abstract
1347 # View for chars on Buffer objects, extends Sequence
1348 # for mutation operations
1349 private abstract class BufferCharView
1350 super StringCharView
1351 super Sequence[Char]
1353 redef type SELFTYPE: Buffer
1357 # View for bytes on Buffer objects, extends Sequence
1358 # for mutation operations
1359 private abstract class BufferByteView
1360 super StringByteView
1362 redef type SELFTYPE: Buffer
1366 # User readable representation of `self`.
1367 fun to_s
: String do return inspect
1369 # The class name of the object in NativeString format.
1370 private fun native_class_name
: NativeString is intern
1372 # The class name of the object.
1374 # assert 5.class_name == "Int"
1375 fun class_name
: String do return native_class_name
.to_s
1377 # Developer readable representation of `self`.
1378 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1381 return "<{inspect_head}>"
1384 # Return "CLASSNAME:#OBJECTID".
1385 # This function is mainly used with the redefinition of the inspect method
1386 protected fun inspect_head
: String
1388 return "{class_name}:#{object_id.to_hex}"
1393 # assert true.to_s == "true"
1394 # assert false.to_s == "false"
1406 # C function to calculate the length of the `NativeString` to receive `self`
1407 private fun byte_to_s_len
: Int `{
1408 return snprintf(NULL, 0, "0x%02x", self);
1411 # C function to convert an nit Int to a NativeString (char*)
1412 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) `{
1413 snprintf(nstr, strlen, "0x%02x", self);
1416 # Displayable byte in its hexadecimal form (0x..)
1418 # assert 1.to_b.to_s == "0x01"
1419 # assert (-123).to_b.to_s == "0x85"
1421 var nslen
= byte_to_s_len
1422 var ns
= new NativeString(nslen
+ 1)
1424 native_byte_to_s
(ns
, nslen
+ 1)
1425 return ns
.to_s_with_length
(nslen
)
1431 # Wrapper of strerror C function
1432 private fun strerror_ext
: NativeString `{ return strerror(self); `}
1434 # Returns a string describing error number
1435 fun strerror: String do return strerror_ext.to_s
1437 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if 'signed' and negative).
1438 # assume < to_c max const of char
1439 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1446 else if self == 0 then
1453 var pos = digit_count(base) - 1
1454 while pos >= 0 and n > 0 do
1455 s.chars[pos] = (n % base).to_c
1461 # C function to calculate the length of the `NativeString` to receive `self`
1462 private fun int_to_s_len: Int `{
1463 return snprintf
(NULL, 0, "%ld", self);
1466 # C function to convert an nit Int to a NativeString (char*)
1467 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1468 snprintf
(nstr
, strlen
, "%ld", self);
1471 # return displayable int in base base and signed
1472 fun to_base(base: Int, signed: Bool): String is abstract
1474 # return displayable int in hexadecimal
1476 # assert 1.to_hex == "1"
1477 # assert (-255).to_hex == "-ff"
1478 fun to_hex: String do return to_base(16,false)
1482 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1484 # assert 12.34.to_s == "12.34"
1485 # assert (-0120.030).to_s == "-120.03"
1487 # see `to_precision
` for a custom precision.
1489 var str = to_precision( 3 )
1490 if is_inf != 0 or is_nan then return str
1491 var len = str.length
1492 for i in [0..len-1] do
1494 var c = str.chars[j]
1497 else if c == '.' then
1498 return str.substring( 0, j+2 )
1500 return str.substring( 0, j+1 )
1506 # `String` representation of `self` with the given number of `decimals
`
1508 # assert 12.345.to_precision(0) == "12"
1509 # assert 12.345.to_precision(3) == "12.345"
1510 # assert (-12.345).to_precision(3) == "-12.345"
1511 # assert (-0.123).to_precision(3) == "-0.123"
1512 # assert 0.999.to_precision(2) == "1.00"
1513 # assert 0.999.to_precision(4) == "0.9990"
1514 fun to_precision(decimals: Int): String
1516 if is_nan then return "nan"
1518 var isinf = self.is_inf
1521 else if isinf == -1 then
1525 if decimals == 0 then return self.to_i.to_s
1527 for i in [0..decimals[ do f = f * 10.0
1534 if i == 0 then return "0." + "0"*decimals
1536 # Prepare both parts of the float, before and after the "."
1541 if sl > decimals then
1542 # Has something before the "."
1543 p1 = s.substring(0, sl-decimals)
1544 p2 = s.substring(sl-decimals, decimals)
1547 p2 = "0"*(decimals-sl) + s
1550 if i < 0 then p1 = "-" + p1
1552 return p1 + "." + p2
1558 # Length of `self` in a UTF-8 String
1559 private fun u8char_len: Int do
1561 if c < 0x80 then return 1
1562 if c <= 0x7FF then return 2
1563 if c <= 0xFFFF then return 3
1564 if c <= 0x10FFFF then return 4
1565 # Bad character format
1569 # assert 'x'.to_s == "x"
1572 var ns = new NativeString(ln + 1)
1574 return ns.to_s_with_length(ln)
1577 private fun u8char_tos(r: NativeString, len: Int) `{
1584 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
1585 r
[1] = 0x80 | (self & 0x3F);
1588 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
1589 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
1590 r
[2] = 0x80 | (self & 0x3F);
1593 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
1594 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
1595 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
1596 r
[3] = 0x80 | (self & 0x3F);
1601 # Returns true if the char is a numerical digit
1603 # assert '0'.is_numeric
1604 # assert '9'.is_numeric
1605 # assert not 'a'.is_numeric
1606 # assert not '?'.is_numeric
1608 # FIXME: Works on ASCII-range only
1609 fun is_numeric: Bool
1611 return self >= '0' and self <= '9'
1614 # Returns true if the char is an alpha digit
1616 # assert 'a'.is_alpha
1617 # assert 'Z'.is_alpha
1618 # assert not '0'.is_alpha
1619 # assert not '?'.is_alpha
1621 # FIXME: Works on ASCII-range only
1624 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1627 # Returns true if the char is an alpha or a numeric digit
1629 # assert 'a'.is_alphanumeric
1630 # assert 'Z'.is_alphanumeric
1631 # assert '0'.is_alphanumeric
1632 # assert '9'.is_alphanumeric
1633 # assert not '?'.is_alphanumeric
1635 # FIXME: Works on ASCII-range only
1636 fun is_alphanumeric: Bool
1638 return self.is_numeric or self.is_alpha
1642 redef class Collection[E]
1643 # String representation of the content of the collection.
1645 # The standard representation is the list of elements separated with commas.
1648 # assert [1,2,3].to_s == "[1,2,3]"
1649 # assert [1..3].to_s == "[1,2,3]"
1650 # assert (new Array[Int]).to_s == "[]" # empty collection
1653 # Subclasses may return a more specific string representation.
1656 return "[" + join(",") + "]"
1659 # Concatenate elements without separators
1662 # assert [1,2,3].plain_to_s == "123"
1663 # assert [11..13].plain_to_s == "111213"
1664 # assert (new Array[Int]).plain_to_s == "" # empty collection
1666 fun plain_to_s: String
1669 for e in self do if e != null then s.append(e.to_s)
1673 # Concatenate and separate each elements with `separator
`.
1675 # Only concatenate if `separator
== null`.
1677 # assert [1, 2, 3].join(":") == "1:2:3"
1678 # assert [1..3].join(":") == "1:2:3"
1679 # assert [1..3].join == "123"
1680 fun join(separator: nullable Text): String
1682 if is_empty then return ""
1684 var s = new Buffer # Result
1689 if e != null then s.append(e.to_s)
1691 # Concat other items
1694 if separator != null then s.append(separator)
1696 if e != null then s.append(e.to_s)
1703 redef class Map[K,V]
1704 # Concatenate couples of key value.
1705 # Key and value are separated by `couple_sep
`.
1706 # Couples are separated by `sep
`.
1708 # var m = new HashMap[Int, String]
1711 # assert m.join("; ", "=") == "1=one; 10=ten"
1712 fun join(sep, couple_sep: String): String is abstract
1716 private var args_cache: nullable Sequence[String] = null
1718 # The arguments of the program as given by the OS
1719 fun program_args: Sequence[String]
1721 if _args_cache == null then init_args
1722 return _args_cache.as(not null)
1725 # The name of the program as given by the OS
1726 fun program_name: String
1728 return native_argv(0).to_s
1731 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
1732 private fun init_args
1734 var argc = native_argc
1735 var args = new Array[String].with_capacity(0)
1738 args[i-1] = native_argv(i).to_s
1744 # First argument of the main C function.
1745 private fun native_argc: Int is intern
1747 # Second argument of the main C function.
1748 private fun native_argv(i: Int): NativeString is intern
1751 # Comparator that efficienlty use `to_s
` to compare things
1753 # The comparaison call `to_s
` on object and use the result to order things.
1755 # var a = [1, 2, 3, 10, 20]
1756 # (new CachedAlphaComparator).sort(a)
1757 # assert a == [1, 10, 2, 20, 3]
1759 # Internally the result of `to_s
` is cached in a HashMap to counter
1760 # uneficient implementation of `to_s
`.
1762 # Note: it caching is not usefull, see `alpha_comparator
`
1763 class CachedAlphaComparator
1765 redef type COMPARED: Object
1767 private var cache = new HashMap[Object, String]
1769 private fun do_to_s(a: Object): String do
1770 if cache.has_key(a) then return cache[a]
1776 redef fun compare(a, b) do
1777 return do_to_s(a) <=> do_to_s(b)
1781 # see `alpha_comparator
`
1782 private class AlphaComparator
1784 redef fun compare(a, b) do return a.to_s <=> b.to_s
1787 # Stateless comparator that naively use `to_s
` to compare things.
1789 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
1790 # on a single instace. See `CachedAlphaComparator` as an alternative.
1792 # var a = [1, 2, 3, 10, 20]
1793 # alpha_comparator.sort(a)
1794 # assert a == [1, 10, 2, 20, 3]
1795 fun alpha_comparator: Comparator do return once new AlphaComparator
1797 # The arguments of the program as given by the OS
1798 fun args: Sequence[String]
1800 return sys.program_args
1803 redef class NativeString
1804 # Returns `self` as a new String.
1805 fun to_s_with_copy: String is abstract
1807 # Returns `self` as a String of `length
`.
1808 fun to_s_with_length(length: Int): String is abstract
1810 # Returns `self` as a String with `bytelen
` and `length
` set
1812 # SEE: `abstract_text
::Text` for more infos on the difference
1813 # between `Text::bytelen
` and `Text::length
`
1814 fun to_s_full(bytelen, unilen: Int): String is abstract
1817 redef class NativeArray[E]
1818 # Join all the elements using `to_s
`
1820 # REQUIRE: `self isa NativeArray[String]`
1821 # REQUIRE: all elements are initialized
1822 fun native_to_s: String is abstract