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 do return chars
.last_index_of_from
(item
, pos
)
151 # Gets an iterator on the chars of self
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator
: Iterator[Char]
156 return self.chars
.iterator
160 # Gets an Array containing the chars of self
162 # DEPRECATED : Use self.chars.to_a instead
163 fun to_a
: Array[Char] do return chars
.to_a
165 # Create a substring from `self` beginning at the `from` position
167 # assert "abcd".substring_from(1) == "bcd"
168 # assert "abcd".substring_from(-1) == "abcd"
169 # assert "abcd".substring_from(2) == "cd"
171 # As with substring, a `from` index < 0 will be replaced by 0
172 fun substring_from
(from
: Int): SELFTYPE
174 if from
>= self.length
then return empty
175 if from
< 0 then from
= 0
176 return substring
(from
, length
- from
)
179 # Does self have a substring `str` starting from position `pos`?
181 # assert "abcd".has_substring("bc",1) == true
182 # assert "abcd".has_substring("bc",2) == false
184 # Returns true iff all characters of `str` are presents
185 # at the expected index in `self.`
186 # The first character of `str` being at `pos`, the second
187 # character being at `pos+1` and so on...
189 # This means that all characters of `str` need to be inside `self`.
191 # assert "abcd".has_substring("xab", -1) == false
192 # assert "abcd".has_substring("cdx", 2) == false
194 # And that the empty string is always a valid substring.
196 # assert "abcd".has_substring("", 2) == true
197 # assert "abcd".has_substring("", 200) == true
198 fun has_substring
(str
: String, pos
: Int): Bool
200 if str
.is_empty
then return true
201 if pos
< 0 or pos
+ str
.length
> length
then return false
202 var myiter
= self.chars
.iterator_from
(pos
)
203 var itsiter
= str
.chars
.iterator
204 while myiter
.is_ok
and itsiter
.is_ok
do
205 if myiter
.item
!= itsiter
.item
then return false
209 if itsiter
.is_ok
then return false
213 # Is this string prefixed by `prefix`?
215 # assert "abcd".has_prefix("ab") == true
216 # assert "abcbc".has_prefix("bc") == false
217 # assert "ab".has_prefix("abcd") == false
218 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
220 # Is this string suffixed by `suffix`?
222 # assert "abcd".has_suffix("abc") == false
223 # assert "abcd".has_suffix("bcd") == true
224 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
226 # Returns `self` as the corresponding integer
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
230 # assert "0x64".to_i == 100
231 # assert "0b1100_0011".to_i== 195
232 # assert "--12".to_i == 12
234 # REQUIRE: `self`.`is_int`
235 fun to_i
: Int is abstract
237 # If `self` contains a float, return the corresponding float
239 # assert "123".to_f == 123.0
240 # assert "-1".to_f == -1.0
241 # assert "-1.2e-3".to_f == -0.0012
245 return to_s
.to_cstring
.atof
248 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
250 # assert "ff".to_hex == 255
251 fun to_hex
: Int do return a_to
(16)
253 # If `self` contains only digits <= '7', return the corresponding integer.
255 # assert "714".to_oct == 460
256 fun to_oct
: Int do return a_to
(8)
258 # If `self` contains only '0' et '1', return the corresponding integer.
260 # assert "101101".to_bin == 45
261 fun to_bin
: Int do return a_to
(2)
263 # If `self` contains only digits '0' .. '9', return the corresponding integer.
265 # assert "108".to_dec == 108
266 fun to_dec
: Int do return a_to
(10)
268 # If `self` contains only digits and letters, return the corresponding integer in a given base
270 # assert "120".a_to(3) == 15
271 fun a_to
(base
: Int) : Int
276 for j
in [0..length
[ do
298 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
300 # assert "123".is_numeric == true
301 # assert "1.2".is_numeric == true
302 # assert "1,2".is_numeric == true
303 # assert "1..2".is_numeric == false
306 var has_point_or_comma
= false
307 for i
in [0..length
[ do
309 if not c
.is_numeric
then
310 if (c
== '.' or c
== ',') and not has_point_or_comma
then
311 has_point_or_comma
= true
320 # Returns `true` if the string contains only Hex chars
322 # assert "048bf".is_hex == true
323 # assert "ABCDEF".is_hex == true
324 # assert "0G".is_hex == false
327 for i
in [0..length
[ do
329 if not (c
>= 'a' and c
<= 'f') and
330 not (c
>= 'A' and c
<= 'F') and
331 not (c
>= '0' and c
<= '9') then return false
336 # Returns `true` if the string contains only Binary digits
338 # assert "1101100".is_bin == true
339 # assert "1101020".is_bin == false
341 for i
in chars
do if i
!= '0' and i
!= '1' then return false
345 # Returns `true` if the string contains only Octal digits
347 # assert "213453".is_oct == true
348 # assert "781".is_oct == false
350 for i
in chars
do if i
< '0' or i
> '7' then return false
354 # Returns `true` if the string contains only Decimal digits
356 # assert "10839".is_dec == true
357 # assert "164F".is_dec == false
359 for i
in chars
do if i
< '0' or i
> '9' then return false
363 # Are all letters in `self` upper-case ?
365 # assert "HELLO WORLD".is_upper == true
366 # assert "%$&%!".is_upper == true
367 # assert "hello world".is_upper == false
368 # assert "Hello World".is_upper == false
371 for i
in [0..length
[ do
373 if char
.is_lower
then return false
378 # Are all letters in `self` lower-case ?
380 # assert "hello world".is_lower == true
381 # assert "%$&%!".is_lower == true
382 # assert "Hello World".is_lower == false
385 for i
in [0..length
[ do
387 if char
.is_upper
then return false
392 # Removes the whitespaces at the beginning of self
394 # assert " \n\thello \n\t".l_trim == "hello \n\t"
396 # `Char::is_whitespace` determines what is a whitespace.
399 var iter
= self.chars
.iterator
401 if not iter
.item
.is_whitespace
then break
404 if iter
.index
== length
then return self.empty
405 return self.substring_from
(iter
.index
)
408 # Removes the whitespaces at the end of self
410 # assert " \n\thello \n\t".r_trim == " \n\thello"
412 # `Char::is_whitespace` determines what is a whitespace.
415 var iter
= self.chars
.reverse_iterator
417 if not iter
.item
.is_whitespace
then break
420 if iter
.index
< 0 then return self.empty
421 return self.substring
(0, iter
.index
+ 1)
424 # Trims trailing and preceding white spaces
426 # assert " Hello World ! ".trim == "Hello World !"
427 # assert "\na\nb\tc\t".trim == "a\nb\tc"
429 # `Char::is_whitespace` determines what is a whitespace.
430 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
432 # Is the string non-empty but only made of whitespaces?
434 # assert " \n\t ".is_whitespace == true
435 # assert " hello ".is_whitespace == false
436 # assert "".is_whitespace == false
438 # `Char::is_whitespace` determines what is a whitespace.
439 fun is_whitespace
: Bool
441 if is_empty
then return false
442 for c
in self.chars
do
443 if not c
.is_whitespace
then return false
448 # Returns `self` removed from its last line terminator (if any).
450 # assert "Hello\n".chomp == "Hello"
451 # assert "Hello".chomp == "Hello"
453 # assert "\n".chomp == ""
454 # assert "".chomp == ""
456 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
457 # A single line terminator, the last one, is removed.
459 # assert "\r\n".chomp == ""
460 # assert "\r\n\n".chomp == "\r\n"
461 # assert "\r\n\r\n".chomp == "\r\n"
462 # assert "\r\n\r".chomp == "\r\n"
464 # Note: unlike with most IO methods like `Reader::read_line`,
465 # a single `\r` is considered here to be a line terminator and will be removed.
469 if len
== 0 then return self
470 var l
= self.chars
.last
472 return substring
(0, len-1
)
473 else if l
!= '\n' then
475 else if len
> 1 and self.chars
[len-2
] == '\r' then
476 return substring
(0, len-2
)
478 return substring
(0, len-1
)
482 # Justify a self in a space of `length`
484 # `left` is the space ratio on the left side.
485 # * 0.0 for left-justified (no space at the left)
486 # * 1.0 for right-justified (all spaces at the left)
487 # * 0.5 for centered (half the spaces at the left)
491 # assert "hello".justify(10, 0.0) == "hello "
492 # assert "hello".justify(10, 1.0) == " hello"
493 # assert "hello".justify(10, 0.5) == " hello "
495 # If `length` is not enough, `self` is returned as is.
497 # assert "hello".justify(2, 0.0) == "hello"
499 # REQUIRE: `left >= 0.0 and left <= 1.0`
500 # ENSURE: `self.length <= length implies result.length == length`
501 # ENSURE: `self.length >= length implies result == self`
502 fun justify
(length
: Int, left
: Float): String
504 var diff
= length
- self.length
505 if diff
<= 0 then return to_s
506 assert left
>= 0.0 and left
<= 1.0
507 var before
= (diff
.to_f
* left
).to_i
508 return " " * before
+ self + " " * (diff-before
)
511 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
513 # This method is injective (two different inputs never produce the same
514 # output) and the returned string always respect the following rules:
516 # * Contains only US-ASCII letters, digits and underscores.
517 # * Never starts with a digit.
518 # * Never ends with an underscore.
519 # * Never contains two contiguous underscores.
521 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
522 # assert "__".to_cmangle == "_95d_95d"
523 # assert "__d".to_cmangle == "_95d_d"
524 # assert "_d_".to_cmangle == "_d_95d"
525 # assert "_42".to_cmangle == "_95d42"
526 # assert "foo".to_cmangle == "foo"
527 # assert "".to_cmangle == ""
528 fun to_cmangle
: String
530 if is_empty
then return ""
532 var underscore
= false
536 if c
>= '0' and c
<= '9' then
538 res
.append
(c
.code_point
.to_s
)
542 for i
in [start
..length
[ do
544 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
550 res
.append
('_'.code_point
.to_s
)
553 if c
>= '0' and c
<= '9' then
556 else if c
== '_' then
561 res
.append
(c
.code_point
.to_s
)
567 res
.append
('_'.code_point
.to_s
)
573 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
575 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
576 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
578 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
579 # Three digits are always used to avoid following digits to be interpreted as an element
580 # of the octal sequence.
582 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
584 # The exceptions are the common `\t` and `\n`.
585 fun escape_to_c
: String
588 for i
in [0..length
[ do
592 else if c
== '\t' then
594 else if c
== '"' then
596 else if c == '\'' then
598 else if c == '\\
' then
600 else if c.code_point < 32 then
602 var oct = c.code_point.to_base(8, false)
603 # Force 3 octal digits since it is the
604 # maximum allowed in the C specification
605 if oct.length == 1 then
608 else if oct.length == 2 then
619 # Escape additionnal characters
620 # The result might no be legal in C but be used in other languages
622 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
623 fun escape_more_to_c(chars: String): String
626 for c in escape_to_c.chars do
627 if chars.chars.has(c) then
635 # Escape to C plus braces
637 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
638 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
640 # Escape to POSIX Shell (sh).
642 # Abort if the text contains a null byte.
644 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
645 fun escape_to_sh
: String do
648 for i in [0..length[ do
653 assert without_null_byte
: c
!= '\0'
661 # Escape to include in a Makefile
663 # Unfortunately, some characters are not escapable in Makefile.
664 # These characters are `;`, `|`, `\`, and the non-printable ones.
665 # They will be rendered as `"?{hex}"`.
666 fun escape_to_mk: String do
668 for i in [0..length[ do
672 else if c == ':' or c == ' ' or c == '#' then
675 else if c
.code_point
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
676 b
.append
("?{c.code_point.to_base(16, false)}")
684 # Return a string where Nit escape sequences are transformed.
687 # assert s.length == 2
688 # var u = s.unescape_nit
689 # assert u.length == 1
690 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
691 fun unescape_nit
: String
693 var res
= new Buffer.with_cap
(self.length
)
694 var was_slash
= false
695 for i
in [0..length
[ do
697 if not was_slash
then
708 else if c
== 'r' then
710 else if c
== 't' then
712 else if c
== '0' then
721 # Encode `self` to percent (or URL) encoding
723 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
724 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
725 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
726 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
727 fun to_percent_encoding
: String
731 for i
in [0..length
[ do
733 if (c
>= '0' and c
<= '9') or
734 (c
>= 'a' and c
<= 'z') or
735 (c
>= 'A' and c
<= 'Z') or
736 c
== '-' or c
== '.' or
741 var bytes
= c
.to_s
.bytes
742 for b
in bytes
do buf
.append
"%{b.to_i.to_hex}"
749 # Decode `self` from percent (or URL) encoding to a clear string
751 # Replace invalid use of '%' with '?'.
753 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
754 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
755 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
756 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
757 # assert "incomplete %".from_percent_encoding == "incomplete ?"
758 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
759 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
760 fun from_percent_encoding
: String
763 var has_percent
= false
771 # If no transformation is needed, return self as a string
772 if not has_percent
then return to_s
774 var buf
= new NativeString(len
)
780 if i
+ 2 >= length
then
781 # What follows % has been cut off
785 var hex_s
= substring
(i
, 2)
787 var hex_i
= hex_s
.to_hex
791 # What follows a % is not Hex
796 else buf
[l
] = c
.ascii
802 return buf
.to_s_with_length
(l
)
805 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
807 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
809 # 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>
810 fun html_escape
: String
814 for i
in [0..length
[ do
818 else if c
== '<' then
820 else if c
== '>' then
822 else if c
== '"' then
824 else if c
== '\'' then
826 else if c == '/' then
835 # Two pieces of text are equals if thez have the same characters in the same order.
837 # assert "hello" == "hello"
838 # assert "hello" != "HELLO"
839 # assert "hello" == "hel"+"lo"
841 # Things that are not Text are not equal.
844 # assert "9" != ['9']
847 # assert "9".chars.first == '9' # equality of Char
848 # assert "9".chars == ['9'] # equality of Sequence
849 # assert "9".to_i == 9 # equality of Int
852 if o == null then return false
853 if not o isa Text then return false
854 if self.is_same_instance(o) then return true
855 if self.length != o.length then return false
856 return self.chars == o.chars
859 # Lexicographical comparaison
861 # assert "abc" < "xy"
862 # assert "ABC" < "abc"
865 var self_chars = self.chars.iterator
866 var other_chars = other.chars.iterator
868 while self_chars.is_ok and other_chars.is_ok do
869 if self_chars.item < other_chars.item then return true
870 if self_chars.item > other_chars.item then return false
875 if self_chars.is_ok then
882 # Escape string used in labels for graphviz
884 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
885 fun escape_to_dot: String
887 return escape_more_to_c("|\{\}<>")
890 private var hash_cache: nullable Int = null
894 if hash_cache == null then
895 # djb2 hash algorithm
898 for i in [0..length[ do
900 h = (h << 5) + h + char.code_point
905 return hash_cache.as(not null)
908 # Gives the formatted string back as a Nit string with `args` in place
910 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
911 # assert "\\%1 This string".format("String") == "\\%1 This string"
912 fun format(args: Object...): String do
913 var s = new Array[Text]
917 # Skip escaped characters
918 if self[i] == '\\
' then
921 else if self[i] == '%' then
925 while i < length and self[i].is_numeric do
930 var ciph_len = fmt_end - ciph_st + 1
932 var arg_index = substring(ciph_st, ciph_len).to_i - 1
933 if arg_index >= args.length then continue
935 s.push substring(curr_st, fmt_st - curr_st)
936 s.push args[arg_index].to_s
941 s.push substring(curr_st, length - curr_st)
945 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
947 # Basically a high-level synonym of NativeString::copy_to
949 # REQUIRE: `n` must be large enough to contain `len` bytes
951 # var ns = new NativeString(8)
952 # "Text is String".copy_to_native(ns, 8, 2, 0)
953 # assert ns.to_s_with_length(8) == "xt is St"
955 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
956 var mypos = src_offset
957 var itspos = dest_offset
959 dest[itspos] = self.bytes[mypos]
968 # All kinds of array-based text representations.
969 private abstract class FlatText
972 # Underlying C-String (`char*`)
974 # Warning : Might be void in some subclasses, be sure to check
975 # if set before using it.
976 var items: NativeString is noinit
978 # Returns a char* starting at position `first_byte`
980 # WARNING: If you choose to use this service, be careful of the following.
982 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
983 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
984 # deallocated at any moment, rendering the pointer returned by this function invalid.
985 # Any access to freed memory may very likely cause undefined behaviour or a crash.
986 # (Failure to do so will most certainly result in long and painful debugging hours)
988 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
989 # then immediately return).
991 # As always, do not modify the content of the String in C code, if this is what you want
992 # copy locally the char* as Nit Strings are immutable.
993 fun fast_cstring: NativeString is abstract
997 redef var bytelen = 0
1008 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1009 items.copy_to(dest, n, src_offset, dest_offset)
1013 # Abstract class for the SequenceRead compatible
1014 # views on the chars of any Text
1015 private abstract class StringCharView
1016 super SequenceRead[Char]
1020 var target: SELFTYPE
1022 redef fun is_empty do return target.is_empty
1024 redef fun length do return target.length
1026 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1028 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1031 # Abstract class for the SequenceRead compatible
1032 # views on the bytes of any Text
1033 private abstract class StringByteView
1034 super SequenceRead[Byte]
1038 var target: SELFTYPE
1040 redef fun is_empty do return target.is_empty
1042 redef fun length do return target.bytelen
1044 redef fun iterator do return self.iterator_from(0)
1046 redef fun reverse_iterator do return self.reverse_iterator_from(target.bytelen - 1)
1049 # Immutable sequence of characters.
1051 # String objects may be created using literals.
1053 # assert "Hello World!" isa String
1054 abstract class String
1057 redef type SELFTYPE: String is fixed
1059 redef fun to_s do return self
1061 # Concatenates `o` to `self`
1063 # assert "hello" + "world" == "helloworld"
1064 # assert "" + "hello" + "" == "hello"
1065 fun +(o: Text): SELFTYPE is abstract
1067 # Concatenates self `i` times
1069 # assert "abc" * 4 == "abcabcabcabc"
1070 # assert "abc" * 1 == "abc"
1071 # assert "abc" * 0 == ""
1072 fun *(i: Int): SELFTYPE is abstract
1074 # Insert `s` at `pos`.
1076 # assert "helloworld".insert_at(" ", 5) == "hello world"
1077 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1079 redef fun substrings is abstract
1081 # Returns a reversed version of self
1083 # assert "hello".reversed == "olleh"
1084 # assert "bob".reversed == "bob"
1085 # assert "".reversed == ""
1086 fun reversed: SELFTYPE is abstract
1088 # A upper case version of `self`
1090 # assert "Hello World!".to_upper == "HELLO WORLD!"
1091 fun to_upper: SELFTYPE is abstract
1093 # A lower case version of `self`
1095 # assert "Hello World!".to_lower == "hello world!"
1096 fun to_lower : SELFTYPE is abstract
1098 # Takes a camel case `self` and converts it to snake case
1100 # assert "randomMethodId".to_snake_case == "random_method_id"
1102 # The rules are the following:
1104 # An uppercase is always converted to a lowercase
1106 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1108 # An uppercase that follows a lowercase is prefixed with an underscore
1110 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1112 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1114 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1116 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1118 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1119 fun to_snake_case: SELFTYPE
1121 if self.is_lower then return self
1123 var new_str = new Buffer.with_cap(self.length)
1124 var prev_is_lower = false
1125 var prev_is_upper = false
1127 for i in [0..length[ do
1129 if char.is_lower then
1131 prev_is_lower = true
1132 prev_is_upper = false
1133 else if char.is_upper then
1134 if prev_is_lower then
1136 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1139 new_str.add(char.to_lower)
1140 prev_is_lower = false
1141 prev_is_upper = true
1144 prev_is_lower = false
1145 prev_is_upper = false
1152 # Takes a snake case `self` and converts it to camel case
1154 # assert "random_method_id".to_camel_case == "randomMethodId"
1156 # If the identifier is prefixed by an underscore, the underscore is ignored
1158 # assert "_private_field".to_camel_case == "_privateField"
1160 # If `self` is upper, it is returned unchanged
1162 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1164 # If there are several consecutive underscores, they are considered as a single one
1166 # assert "random__method_id".to_camel_case == "randomMethodId"
1167 fun to_camel_case: SELFTYPE
1169 if self.is_upper then return self
1171 var new_str = new Buffer
1172 var is_first_char = true
1173 var follows_us = false
1175 for i in [0..length[ do
1177 if is_first_char then
1179 is_first_char = false
1180 else if char == '_
' then
1182 else if follows_us then
1183 new_str.add(char.to_upper)
1193 # Returns a capitalized `self`
1195 # Letters that follow a letter are lowercased
1196 # Letters that follow a non-letter are upcased.
1198 # SEE : `Char::is_letter` for the definition of letter.
1200 # assert "jAVASCRIPT".capitalized == "Javascript"
1201 # assert "i am root".capitalized == "I Am Root"
1202 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1203 fun capitalized: SELFTYPE do
1204 if length == 0 then return self
1206 var buf = new Buffer.with_cap(length)
1208 var curr = chars[0].to_upper
1212 for i in [1 .. length[ do
1215 if prev.is_letter then
1216 buf[i] = curr.to_lower
1218 buf[i] = curr.to_upper
1226 # A mutable sequence of characters.
1227 abstract class Buffer
1230 # Returns an arbitrary subclass of `Buffer` with default parameters
1233 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1234 new with_cap(i: Int) is abstract
1236 redef type SELFTYPE: Buffer is fixed
1238 # Specific implementations MUST set this to `true` in order to invalidate caches
1239 protected var is_dirty = true
1241 # Copy-On-Write flag
1243 # If the `Buffer` was to_s'd
, the next in-place altering
1244 # operation will cause the current `Buffer` to be re-allocated.
1246 # The flag will then be set at `false`.
1247 protected var written
= false
1249 # Modifies the char contained at pos `index`
1251 # DEPRECATED : Use self.chars.[]= instead
1252 fun []=(index
: Int, item
: Char) is abstract
1254 # Adds a char `c` at the end of self
1256 # DEPRECATED : Use self.chars.add instead
1257 fun add
(c
: Char) is abstract
1261 # var b = new Buffer
1263 # assert not b.is_empty
1266 fun clear
is abstract
1268 # Enlarges the subsequent array containing the chars of self
1269 fun enlarge
(cap
: Int) is abstract
1271 # Adds the content of text `s` at the end of self
1273 # var b = new Buffer
1276 # assert b == "helloworld"
1277 fun append
(s
: Text) is abstract
1279 # `self` is appended in such a way that `self` is repeated `r` times
1281 # var b = new Buffer
1284 # assert b == "hellohellohello"
1285 fun times
(r
: Int) is abstract
1287 # Reverses itself in-place
1289 # var b = new Buffer
1292 # assert b == "olleh"
1293 fun reverse
is abstract
1295 # Changes each lower-case char in `self` by its upper-case variant
1297 # var b = new Buffer
1298 # b.append("Hello World!")
1300 # assert b == "HELLO WORLD!"
1301 fun upper
is abstract
1303 # Changes each upper-case char in `self` by its lower-case variant
1305 # var b = new Buffer
1306 # b.append("Hello World!")
1308 # assert b == "hello world!"
1309 fun lower
is abstract
1311 # Capitalizes each word in `self`
1313 # Letters that follow a letter are lowercased
1314 # Letters that follow a non-letter are upcased.
1316 # SEE: `Char::is_letter` for the definition of a letter.
1318 # var b = new FlatBuffer.from("jAVAsCriPt")
1320 # assert b == "Javascript"
1321 # b = new FlatBuffer.from("i am root")
1323 # assert b == "I Am Root"
1324 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1326 # assert b == "Ab_C -Ab0C Ab\nC"
1328 if length
== 0 then return
1329 var c
= self[0].to_upper
1332 for i
in [1 .. length
[ do
1335 if prev
.is_letter
then
1336 self[i
] = c
.to_lower
1338 self[i
] = c
.to_upper
1345 if is_dirty
then hash_cache
= null
1349 # In Buffers, the internal sequence of character is mutable
1350 # Thus, `chars` can be used to modify the buffer.
1351 redef fun chars
: Sequence[Char] is abstract
1354 # View for chars on Buffer objects, extends Sequence
1355 # for mutation operations
1356 private abstract class BufferCharView
1357 super StringCharView
1358 super Sequence[Char]
1360 redef type SELFTYPE: Buffer
1364 # View for bytes on Buffer objects, extends Sequence
1365 # for mutation operations
1366 private abstract class BufferByteView
1367 super StringByteView
1369 redef type SELFTYPE: Buffer
1373 # User readable representation of `self`.
1374 fun to_s
: String do return inspect
1376 # The class name of the object in NativeString format.
1377 private fun native_class_name
: NativeString is intern
1379 # The class name of the object.
1381 # assert 5.class_name == "Int"
1382 fun class_name
: String do return native_class_name
.to_s
1384 # Developer readable representation of `self`.
1385 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1388 return "<{inspect_head}>"
1391 # Return "CLASSNAME:#OBJECTID".
1392 # This function is mainly used with the redefinition of the inspect method
1393 protected fun inspect_head
: String
1395 return "{class_name}:#{object_id.to_hex}"
1400 # assert true.to_s == "true"
1401 # assert false.to_s == "false"
1413 # C function to calculate the length of the `NativeString` to receive `self`
1414 private fun byte_to_s_len
: Int `{
1415 return snprintf(NULL, 0, "0x%02x", self);
1418 # C function to convert an nit Int to a NativeString (char*)
1419 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) `{
1420 snprintf(nstr, strlen, "0x%02x", self);
1423 # Displayable byte in its hexadecimal form (0x..)
1425 # assert 1.to_b.to_s == "0x01"
1426 # assert (-123).to_b.to_s == "0x85"
1428 var nslen
= byte_to_s_len
1429 var ns
= new NativeString(nslen
+ 1)
1431 native_byte_to_s
(ns
, nslen
+ 1)
1432 return ns
.to_s_with_length
(nslen
)
1438 # Wrapper of strerror C function
1439 private fun strerror_ext
: NativeString `{ return strerror(self); `}
1441 # Returns a string describing error number
1442 fun strerror: String do return strerror_ext.to_s
1444 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if 'signed' and negative).
1445 # assume < to_c max const of char
1446 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1453 else if self == 0 then
1460 var pos = digit_count(base) - 1
1461 while pos >= 0 and n > 0 do
1462 s.chars[pos] = (n % base).to_c
1468 # C function to calculate the length of the `NativeString` to receive `self`
1469 private fun int_to_s_len: Int `{
1470 return snprintf
(NULL, 0, "%ld", self);
1473 # C function to convert an nit Int to a NativeString (char*)
1474 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1475 snprintf
(nstr
, strlen
, "%ld", self);
1478 # return displayable int in base base and signed
1479 fun to_base(base: Int, signed: Bool): String is abstract
1481 # return displayable int in hexadecimal
1483 # assert 1.to_hex == "1"
1484 # assert (-255).to_hex == "-ff"
1485 fun to_hex: String do return to_base(16,false)
1489 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1491 # assert 12.34.to_s == "12.34"
1492 # assert (-0120.030).to_s == "-120.03"
1494 # see `to_precision
` for a custom precision.
1496 var str = to_precision( 3 )
1497 if is_inf != 0 or is_nan then return str
1498 var len = str.length
1499 for i in [0..len-1] do
1501 var c = str.chars[j]
1504 else if c == '.' then
1505 return str.substring( 0, j+2 )
1507 return str.substring( 0, j+1 )
1513 # `String` representation of `self` with the given number of `decimals
`
1515 # assert 12.345.to_precision(0) == "12"
1516 # assert 12.345.to_precision(3) == "12.345"
1517 # assert (-12.345).to_precision(3) == "-12.345"
1518 # assert (-0.123).to_precision(3) == "-0.123"
1519 # assert 0.999.to_precision(2) == "1.00"
1520 # assert 0.999.to_precision(4) == "0.9990"
1521 fun to_precision(decimals: Int): String
1523 if is_nan then return "nan"
1525 var isinf = self.is_inf
1528 else if isinf == -1 then
1532 if decimals == 0 then return self.to_i.to_s
1534 for i in [0..decimals[ do f = f * 10.0
1541 if i == 0 then return "0." + "0"*decimals
1543 # Prepare both parts of the float, before and after the "."
1548 if sl > decimals then
1549 # Has something before the "."
1550 p1 = s.substring(0, sl-decimals)
1551 p2 = s.substring(sl-decimals, decimals)
1554 p2 = "0"*(decimals-sl) + s
1557 if i < 0 then p1 = "-" + p1
1559 return p1 + "." + p2
1565 # Returns a sequence with the UTF-8 bytes of `self`
1567 # assert 'a'.bytes == [0x61u8]
1568 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1569 fun bytes: SequenceRead[Byte] do return to_s.bytes
1571 # Length of `self` in a UTF-8 String
1572 private fun u8char_len: Int do
1573 var c = self.code_point
1574 if c < 0x80 then return 1
1575 if c <= 0x7FF then return 2
1576 if c <= 0xFFFF then return 3
1577 if c <= 0x10FFFF then return 4
1578 # Bad character format
1582 # assert 'x'.to_s == "x"
1585 var ns = new NativeString(ln + 1)
1587 return ns.to_s_with_length(ln)
1590 private fun u8char_tos(r: NativeString, len: Int) `{
1597 r
[0] = 0xC0 | ((self & 0x7C0) >> 6);
1598 r
[1] = 0x80 | (self & 0x3F);
1601 r
[0] = 0xE0 | ((self & 0xF000) >> 12);
1602 r
[1] = 0x80 | ((self & 0xFC0) >> 6);
1603 r
[2] = 0x80 | (self & 0x3F);
1606 r
[0] = 0xF0 | ((self & 0x1C0000) >> 18);
1607 r
[1] = 0x80 | ((self & 0x3F000) >> 12);
1608 r
[2] = 0x80 | ((self & 0xFC0) >> 6);
1609 r
[3] = 0x80 | (self & 0x3F);
1614 # Returns true if the char is a numerical digit
1616 # assert '0'.is_numeric
1617 # assert '9'.is_numeric
1618 # assert not 'a'.is_numeric
1619 # assert not '?'.is_numeric
1621 # FIXME: Works on ASCII-range only
1622 fun is_numeric: Bool
1624 return self >= '0' and self <= '9'
1627 # Returns true if the char is an alpha digit
1629 # assert 'a'.is_alpha
1630 # assert 'Z'.is_alpha
1631 # assert not '0'.is_alpha
1632 # assert not '?'.is_alpha
1634 # FIXME: Works on ASCII-range only
1637 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1640 # Returns true if the char is an alpha or a numeric digit
1642 # assert 'a'.is_alphanumeric
1643 # assert 'Z'.is_alphanumeric
1644 # assert '0'.is_alphanumeric
1645 # assert '9'.is_alphanumeric
1646 # assert not '?'.is_alphanumeric
1648 # FIXME: Works on ASCII-range only
1649 fun is_alphanumeric: Bool
1651 return self.is_numeric or self.is_alpha
1655 redef class Collection[E]
1656 # String representation of the content of the collection.
1658 # The standard representation is the list of elements separated with commas.
1661 # assert [1,2,3].to_s == "[1,2,3]"
1662 # assert [1..3].to_s == "[1,2,3]"
1663 # assert (new Array[Int]).to_s == "[]" # empty collection
1666 # Subclasses may return a more specific string representation.
1669 return "[" + join(",") + "]"
1672 # Concatenate elements without separators
1675 # assert [1,2,3].plain_to_s == "123"
1676 # assert [11..13].plain_to_s == "111213"
1677 # assert (new Array[Int]).plain_to_s == "" # empty collection
1679 fun plain_to_s: String
1682 for e in self do if e != null then s.append(e.to_s)
1686 # Concatenate and separate each elements with `separator
`.
1688 # Only concatenate if `separator
== null`.
1690 # assert [1, 2, 3].join(":") == "1:2:3"
1691 # assert [1..3].join(":") == "1:2:3"
1692 # assert [1..3].join == "123"
1693 fun join(separator: nullable Text): String
1695 if is_empty then return ""
1697 var s = new Buffer # Result
1702 if e != null then s.append(e.to_s)
1704 # Concat other items
1707 if separator != null then s.append(separator)
1709 if e != null then s.append(e.to_s)
1716 redef class Map[K,V]
1717 # Concatenate couples of key value.
1718 # Key and value are separated by `couple_sep
`.
1719 # Couples are separated by `sep
`.
1721 # var m = new HashMap[Int, String]
1724 # assert m.join("; ", "=") == "1=one; 10=ten"
1725 fun join(sep, couple_sep: String): String is abstract
1729 private var args_cache: nullable Sequence[String] = null
1731 # The arguments of the program as given by the OS
1732 fun program_args: Sequence[String]
1734 if _args_cache == null then init_args
1735 return _args_cache.as(not null)
1738 # The name of the program as given by the OS
1739 fun program_name: String
1741 return native_argv(0).to_s
1744 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
1745 private fun init_args
1747 var argc = native_argc
1748 var args = new Array[String].with_capacity(0)
1751 args[i-1] = native_argv(i).to_s
1757 # First argument of the main C function.
1758 private fun native_argc: Int is intern
1760 # Second argument of the main C function.
1761 private fun native_argv(i: Int): NativeString is intern
1764 # Comparator that efficienlty use `to_s
` to compare things
1766 # The comparaison call `to_s
` on object and use the result to order things.
1768 # var a = [1, 2, 3, 10, 20]
1769 # (new CachedAlphaComparator).sort(a)
1770 # assert a == [1, 10, 2, 20, 3]
1772 # Internally the result of `to_s
` is cached in a HashMap to counter
1773 # uneficient implementation of `to_s
`.
1775 # Note: it caching is not usefull, see `alpha_comparator
`
1776 class CachedAlphaComparator
1778 redef type COMPARED: Object
1780 private var cache = new HashMap[Object, String]
1782 private fun do_to_s(a: Object): String do
1783 if cache.has_key(a) then return cache[a]
1789 redef fun compare(a, b) do
1790 return do_to_s(a) <=> do_to_s(b)
1794 # see `alpha_comparator
`
1795 private class AlphaComparator
1797 redef fun compare(a, b) do return a.to_s <=> b.to_s
1800 # Stateless comparator that naively use `to_s
` to compare things.
1802 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
1803 # on a single instace. See `CachedAlphaComparator` as an alternative.
1805 # var a = [1, 2, 3, 10, 20]
1806 # alpha_comparator.sort(a)
1807 # assert a == [1, 10, 2, 20, 3]
1808 fun alpha_comparator: Comparator do return once new AlphaComparator
1810 # The arguments of the program as given by the OS
1811 fun args: Sequence[String]
1813 return sys.program_args
1816 redef class NativeString
1817 # Returns `self` as a new String.
1818 fun to_s_with_copy: String is abstract
1820 # Returns `self` as a String of `length
`.
1821 fun to_s_with_length(length: Int): String is abstract
1823 # Returns `self` as a String with `bytelen
` and `length
` set
1825 # SEE: `abstract_text
::Text` for more infos on the difference
1826 # between `Text::bytelen
` and `Text::length
`
1827 fun to_s_full(bytelen, unilen: Int): String is abstract
1830 redef class NativeArray[E]
1831 # Join all the elements using `to_s
`
1833 # REQUIRE: `self isa NativeArray[String]`
1834 # REQUIRE: all elements are initialized
1835 fun native_to_s: String is abstract