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 fun length
: Int is abstract
50 # Number of bytes in `self`
52 # TODO: Implement correctly once UTF-8 is supported
53 fun bytelen
: Int do return length
57 # assert "abcd".substring(1, 2) == "bc"
58 # assert "abcd".substring(-1, 2) == "a"
59 # assert "abcd".substring(1, 0) == ""
60 # assert "abcd".substring(2, 5) == "cd"
62 # A `from` index < 0 will be replaced by 0.
63 # Unless a `count` value is > 0 at the same time.
64 # In this case, `from += count` and `count -= from`.
65 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
67 # Iterates on the substrings of self if any
68 fun substrings
: Iterator[FlatText] is abstract
70 # Is the current Text empty (== "")
73 # assert not "foo".is_empty
74 fun is_empty
: Bool do return self.length
== 0
76 # Returns an empty Text of the right type
78 # This method is used internally to get the right
79 # implementation of an empty string.
80 protected fun empty
: SELFTYPE is abstract
82 # Gets the first char of the Text
84 # DEPRECATED : Use self.chars.first instead
85 fun first
: Char do return self.chars
[0]
87 # Access a character at `index` in the string.
89 # assert "abcd"[2] == 'c'
91 # DEPRECATED : Use self.chars.[] instead
92 fun [](index
: Int): Char do return self.chars
[index
]
94 # Gets the index of the first occurence of 'c'
96 # Returns -1 if not found
98 # DEPRECATED : Use self.chars.index_of instead
99 fun index_of
(c
: Char): Int
101 return index_of_from
(c
, 0)
104 # Gets the last char of self
106 # DEPRECATED : Use self.chars.last instead
107 fun last
: Char do return self.chars
[length-1
]
109 # Gets the index of the first occurence of ´c´ starting from ´pos´
111 # Returns -1 if not found
113 # DEPRECATED : Use self.chars.index_of_from instead
114 fun index_of_from
(c
: Char, pos
: Int): Int
116 var iter
= self.chars
.iterator_from
(pos
)
118 if iter
.item
== c
then return iter
.index
124 # Gets the last index of char ´c´
126 # Returns -1 if not found
128 # DEPRECATED : Use self.chars.last_index_of instead
129 fun last_index_of
(c
: Char): Int
131 return last_index_of_from
(c
, length
- 1)
134 # Return a null terminated char *
135 fun to_cstring
: NativeString is abstract
137 # The index of the last occurrence of an element starting from pos (in reverse order).
139 # var s = "/etc/bin/test/test.nit"
140 # assert s.last_index_of_from('/', s.length-1) == 13
141 # assert s.last_index_of_from('/', 12) == 8
143 # Returns -1 if not found
145 # DEPRECATED : Use self.chars.last_index_of_from instead
146 fun last_index_of_from
(item
: Char, pos
: Int): Int
148 var iter
= self.chars
.reverse_iterator_from
(pos
)
150 if iter
.item
== item
then return iter
.index
156 # Gets an iterator on the chars of self
158 # DEPRECATED : Use self.chars.iterator instead
159 fun iterator
: Iterator[Char]
161 return self.chars
.iterator
165 # Gets an Array containing the chars of self
167 # DEPRECATED : Use self.chars.to_a instead
168 fun to_a
: Array[Char] do return chars
.to_a
170 # Create a substring from `self` beginning at the `from` position
172 # assert "abcd".substring_from(1) == "bcd"
173 # assert "abcd".substring_from(-1) == "abcd"
174 # assert "abcd".substring_from(2) == "cd"
176 # As with substring, a `from` index < 0 will be replaced by 0
177 fun substring_from
(from
: Int): SELFTYPE
179 if from
>= self.length
then return empty
180 if from
< 0 then from
= 0
181 return substring
(from
, length
- from
)
184 # Does self have a substring `str` starting from position `pos`?
186 # assert "abcd".has_substring("bc",1) == true
187 # assert "abcd".has_substring("bc",2) == false
189 # Returns true iff all characters of `str` are presents
190 # at the expected index in `self.`
191 # The first character of `str` being at `pos`, the second
192 # character being at `pos+1` and so on...
194 # This means that all characters of `str` need to be inside `self`.
196 # assert "abcd".has_substring("xab", -1) == false
197 # assert "abcd".has_substring("cdx", 2) == false
199 # And that the empty string is always a valid substring.
201 # assert "abcd".has_substring("", 2) == true
202 # assert "abcd".has_substring("", 200) == true
203 fun has_substring
(str
: String, pos
: Int): Bool
205 if str
.is_empty
then return true
206 if pos
< 0 or pos
+ str
.length
> length
then return false
207 var myiter
= self.chars
.iterator_from
(pos
)
208 var itsiter
= str
.chars
.iterator
209 while myiter
.is_ok
and itsiter
.is_ok
do
210 if myiter
.item
!= itsiter
.item
then return false
214 if itsiter
.is_ok
then return false
218 # Is this string prefixed by `prefix`?
220 # assert "abcd".has_prefix("ab") == true
221 # assert "abcbc".has_prefix("bc") == false
222 # assert "ab".has_prefix("abcd") == false
223 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
225 # Is this string suffixed by `suffix`?
227 # assert "abcd".has_suffix("abc") == false
228 # assert "abcd".has_suffix("bcd") == true
229 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
231 # If `self` contains only digits, return the corresponding integer
233 # assert "123".to_i == 123
234 # assert "-1".to_i == -1
238 return to_s
.to_cstring
.atoi
241 # If `self` contains a float, return the corresponding float
243 # assert "123".to_f == 123.0
244 # assert "-1".to_f == -1.0
245 # assert "-1.2e-3".to_f == -0.0012
249 return to_s
.to_cstring
.atof
252 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
254 # assert "ff".to_hex == 255
255 fun to_hex
: Int do return a_to
(16)
257 # If `self` contains only digits <= '7', return the corresponding integer.
259 # assert "714".to_oct == 460
260 fun to_oct
: Int do return a_to
(8)
262 # If `self` contains only '0' et '1', return the corresponding integer.
264 # assert "101101".to_bin == 45
265 fun to_bin
: Int do return a_to
(2)
267 # If `self` contains only digits and letters, return the corresponding integer in a given base
269 # assert "120".a_to(3) == 15
270 fun a_to
(base
: Int) : Int
275 for j
in [0..length
[ do
297 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
299 # assert "123".is_numeric == true
300 # assert "1.2".is_numeric == true
301 # assert "1,2".is_numeric == true
302 # assert "1..2".is_numeric == false
305 var has_point_or_comma
= false
306 for i
in [0..length
[ do
308 if not c
.is_numeric
then
309 if (c
== '.' or c
== ',') and not has_point_or_comma
then
310 has_point_or_comma
= true
319 # Returns `true` if the string contains only Hex chars
321 # assert "048bf".is_hex == true
322 # assert "ABCDEF".is_hex == true
323 # assert "0G".is_hex == false
326 for i
in [0..length
[ do
328 if not (c
>= 'a' and c
<= 'f') and
329 not (c
>= 'A' and c
<= 'F') and
330 not (c
>= '0' and c
<= '9') then return false
335 # Are all letters in `self` upper-case ?
337 # assert "HELLO WORLD".is_upper == true
338 # assert "%$&%!".is_upper == true
339 # assert "hello world".is_upper == false
340 # assert "Hello World".is_upper == false
343 for i
in [0..length
[ do
345 if char
.is_lower
then return false
350 # Are all letters in `self` lower-case ?
352 # assert "hello world".is_lower == true
353 # assert "%$&%!".is_lower == true
354 # assert "Hello World".is_lower == false
357 for i
in [0..length
[ do
359 if char
.is_upper
then return false
364 # Removes the whitespaces at the beginning of self
366 # assert " \n\thello \n\t".l_trim == "hello \n\t"
368 # `Char::is_whitespace` determines what is a whitespace.
371 var iter
= self.chars
.iterator
373 if not iter
.item
.is_whitespace
then break
376 if iter
.index
== length
then return self.empty
377 return self.substring_from
(iter
.index
)
380 # Removes the whitespaces at the end of self
382 # assert " \n\thello \n\t".r_trim == " \n\thello"
384 # `Char::is_whitespace` determines what is a whitespace.
387 var iter
= self.chars
.reverse_iterator
389 if not iter
.item
.is_whitespace
then break
392 if iter
.index
< 0 then return self.empty
393 return self.substring
(0, iter
.index
+ 1)
396 # Trims trailing and preceding white spaces
398 # assert " Hello World ! ".trim == "Hello World !"
399 # assert "\na\nb\tc\t".trim == "a\nb\tc"
401 # `Char::is_whitespace` determines what is a whitespace.
402 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
404 # Is the string non-empty but only made of whitespaces?
406 # assert " \n\t ".is_whitespace == true
407 # assert " hello ".is_whitespace == false
408 # assert "".is_whitespace == false
410 # `Char::is_whitespace` determines what is a whitespace.
411 fun is_whitespace
: Bool
413 if is_empty
then return false
414 for c
in self.chars
do
415 if not c
.is_whitespace
then return false
420 # Returns `self` removed from its last line terminator (if any).
422 # assert "Hello\n".chomp == "Hello"
423 # assert "Hello".chomp == "Hello"
425 # assert "\n".chomp == ""
426 # assert "".chomp == ""
428 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
429 # A single line terminator, the last one, is removed.
431 # assert "\r\n".chomp == ""
432 # assert "\r\n\n".chomp == "\r\n"
433 # assert "\r\n\r\n".chomp == "\r\n"
434 # assert "\r\n\r".chomp == "\r\n"
436 # Note: unlike with most IO methods like `Reader::read_line`,
437 # a single `\r` is considered here to be a line terminator and will be removed.
441 if len
== 0 then return self
442 var l
= self.chars
.last
444 return substring
(0, len-1
)
445 else if l
!= '\n' then
447 else if len
> 1 and self.chars
[len-2
] == '\r' then
448 return substring
(0, len-2
)
450 return substring
(0, len-1
)
454 # Justify a self in a space of `length`
456 # `left` is the space ratio on the left side.
457 # * 0.0 for left-justified (no space at the left)
458 # * 1.0 for right-justified (all spaces at the left)
459 # * 0.5 for centered (half the spaces at the left)
463 # assert "hello".justify(10, 0.0) == "hello "
464 # assert "hello".justify(10, 1.0) == " hello"
465 # assert "hello".justify(10, 0.5) == " hello "
467 # If `length` is not enough, `self` is returned as is.
469 # assert "hello".justify(2, 0.0) == "hello"
471 # REQUIRE: `left >= 0.0 and left <= 1.0`
472 # ENSURE: `self.length <= length implies result.length == length`
473 # ENSURE: `self.length >= length implies result == self`
474 fun justify
(length
: Int, left
: Float): String
476 var diff
= length
- self.length
477 if diff
<= 0 then return to_s
478 assert left
>= 0.0 and left
<= 1.0
479 var before
= (diff
.to_f
* left
).to_i
480 return " " * before
+ self + " " * (diff-before
)
483 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
485 # This method is injective (two different inputs never produce the same
486 # output) and the returned string always respect the following rules:
488 # * Contains only US-ASCII letters, digits and underscores.
489 # * Never starts with a digit.
490 # * Never ends with an underscore.
491 # * Never contains two contiguous underscores.
493 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
494 # assert "__".to_cmangle == "_95d_95d"
495 # assert "__d".to_cmangle == "_95d_d"
496 # assert "_d_".to_cmangle == "_d_95d"
497 # assert "_42".to_cmangle == "_95d42"
498 # assert "foo".to_cmangle == "foo"
499 # assert "".to_cmangle == ""
500 fun to_cmangle
: String
502 if is_empty
then return ""
504 var underscore
= false
508 if c
>= '0' and c
<= '9' then
510 res
.append
(c
.ascii
.to_s
)
514 for i
in [start
..length
[ do
516 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
522 res
.append
('_'.ascii
.to_s
)
525 if c
>= '0' and c
<= '9' then
528 else if c
== '_' then
533 res
.append
(c
.ascii
.to_s
)
539 res
.append
('_'.ascii
.to_s
)
545 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
547 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
548 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
550 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
551 # Three digits are always used to avoid following digits to be interpreted as an element
552 # of the octal sequence.
554 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
556 # The exceptions are the common `\t` and `\n`.
557 fun escape_to_c
: String
560 for i
in [0..length
[ do
564 else if c
== '\t' then
566 else if c
== '\0' then
568 else if c
== '"' then
570 else if c == '\'' then
572 else if c == '\\
' then
574 else if c.ascii < 32 then
576 var oct = c.ascii.to_base(8, false)
577 # Force 3 octal digits since it is the
578 # maximum allowed in the C specification
579 if oct.length == 1 then
582 else if oct.length == 2 then
593 # Escape additionnal characters
594 # The result might no be legal in C but be used in other languages
596 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
597 fun escape_more_to_c(chars: String): String
600 for c in escape_to_c.chars do
601 if chars.chars.has(c) then
609 # Escape to C plus braces
611 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
612 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
614 # Escape to POSIX Shell (sh).
616 # Abort if the text contains a null byte.
618 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
619 fun escape_to_sh
: String do
622 for i in [0..length[ do
627 assert without_null_byte
: c
!= '\0'
635 # Escape to include in a Makefile
637 # Unfortunately, some characters are not escapable in Makefile.
638 # These characters are `;`, `|`, `\`, and the non-printable ones.
639 # They will be rendered as `"?{hex}"`.
640 fun escape_to_mk: String do
642 for i in [0..length[ do
646 else if c == ':' or c == ' ' or c == '#' then
649 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
650 b
.append
("?{c.ascii.to_base(16, false)}")
658 # Return a string where Nit escape sequences are transformed.
661 # assert s.length == 2
662 # var u = s.unescape_nit
663 # assert u.length == 1
664 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
665 fun unescape_nit
: String
667 var res
= new Buffer.with_cap
(self.length
)
668 var was_slash
= false
669 for i
in [0..length
[ do
671 if not was_slash
then
682 else if c
== 'r' then
684 else if c
== 't' then
686 else if c
== '0' then
695 # Encode `self` to percent (or URL) encoding
697 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
698 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
699 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
700 fun to_percent_encoding
: String
704 for i
in [0..length
[ do
706 if (c
>= '0' and c
<= '9') or
707 (c
>= 'a' and c
<= 'z') or
708 (c
>= 'A' and c
<= 'Z') or
709 c
== '-' or c
== '.' or
713 else buf
.append
"%{c.ascii.to_hex}"
719 # Decode `self` from percent (or URL) encoding to a clear string
721 # Replace invalid use of '%' with '?'.
723 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
724 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
725 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
726 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
727 # assert "incomplete %".from_percent_encoding == "incomplete ?"
728 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
729 fun from_percent_encoding
: String
737 if i
+ 2 >= length
then
738 # What follows % has been cut off
742 var hex_s
= substring
(i
, 2)
744 var hex_i
= hex_s
.to_hex
748 # What follows a % is not Hex
761 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
763 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
765 # 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>
766 fun html_escape
: String
770 for i
in [0..length
[ do
774 else if c
== '<' then
776 else if c
== '>' then
778 else if c
== '"' then
780 else if c
== '\'' then
782 else if c == '/' then
791 # Two pieces of text are equals if thez have the same characters in the same order.
793 # assert "hello" == "hello"
794 # assert "hello" != "HELLO"
795 # assert "hello" == "hel"+"lo"
797 # Things that are not Text are not equal.
800 # assert "9" != ['9']
803 # assert "9".chars.first == '9' # equality of Char
804 # assert "9".chars == ['9'] # equality of Sequence
805 # assert "9".to_i == 9 # equality of Int
808 if o == null then return false
809 if not o isa Text then return false
810 if self.is_same_instance(o) then return true
811 if self.length != o.length then return false
812 return self.chars == o.chars
815 # Lexicographical comparaison
817 # assert "abc" < "xy"
818 # assert "ABC" < "abc"
821 var self_chars = self.chars.iterator
822 var other_chars = other.chars.iterator
824 while self_chars.is_ok and other_chars.is_ok do
825 if self_chars.item < other_chars.item then return true
826 if self_chars.item > other_chars.item then return false
831 if self_chars.is_ok then
838 # Escape string used in labels for graphviz
840 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
841 fun escape_to_dot: String
843 return escape_more_to_c("|\{\}<>")
846 private var hash_cache: nullable Int = null
850 if hash_cache == null then
851 # djb2 hash algorithm
854 for i in [0..length[ do
856 h = h.lshift(5) + h + char.ascii
861 return hash_cache.as(not null)
864 # Gives the formatted string back as a Nit string with `args` in place
866 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
867 # assert "\\%1 This string".format("String") == "\\%1 This string"
868 fun format(args: Object...): String do
869 var s = new Array[Text]
873 # Skip escaped characters
874 if self[i] == '\\
' then
877 else if self[i] == '%' then
881 while i < length and self[i].is_numeric do
886 var ciph_len = fmt_end - ciph_st + 1
888 var arg_index = substring(ciph_st, ciph_len).to_i - 1
889 if arg_index >= args.length then continue
891 s.push substring(curr_st, fmt_st - curr_st)
892 s.push args[arg_index].to_s
897 s.push substring(curr_st, length - curr_st)
901 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
903 # Basically a high-level synonym of NativeString::copy_to
905 # REQUIRE: `n` must be large enough to contain `len` bytes
907 # var ns = new NativeString(8)
908 # "Text is String".copy_to_native(ns, 8, 2, 0)
909 # assert ns.to_s_with_length(8) == "xt is St"
911 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
912 var mypos = src_offset
913 var itspos = dest_offset
915 dest[itspos] = self.bytes[mypos]
924 # All kinds of array-based text representations.
925 abstract class FlatText
928 # Underlying C-String (`char*`)
930 # Warning : Might be void in some subclasses, be sure to check
931 # if set before using it.
932 private var items: NativeString is noinit
934 # Real items, used as cache for to_cstring is called
935 private var real_items: nullable NativeString = null
937 # Returns a char* starting at position `index_from`
939 # WARNING: If you choose to use this service, be careful of the following.
941 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
942 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
943 # deallocated at any moment, rendering the pointer returned by this function invalid.
944 # Any access to freed memory may very likely cause undefined behaviour or a crash.
945 # (Failure to do so will most certainly result in long and painful debugging hours)
947 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
948 # then immediately return).
950 # As always, do not modify the content of the String in C code, if this is what you want
951 # copy locally the char* as Nit Strings are immutable.
952 private fun fast_cstring: NativeString is abstract
965 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
966 items.copy_to(dest, n, src_offset, dest_offset)
970 # Abstract class for the SequenceRead compatible
971 # views on the chars of any Text
972 private abstract class StringCharView
973 super SequenceRead[Char]
979 redef fun is_empty do return target.is_empty
981 redef fun length do return target.length
983 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
985 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
988 # Abstract class for the SequenceRead compatible
989 # views on the bytes of any Text
990 private abstract class StringByteView
991 super SequenceRead[Byte]
997 redef fun is_empty do return target.is_empty
999 redef fun length do return target.length
1001 redef fun iterator do return self.iterator_from(0)
1003 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1006 # Immutable sequence of characters.
1008 # String objects may be created using literals.
1010 # assert "Hello World!" isa String
1011 abstract class String
1014 redef type SELFTYPE: String is fixed
1016 redef fun to_s do return self
1018 # Concatenates `o` to `self`
1020 # assert "hello" + "world" == "helloworld"
1021 # assert "" + "hello" + "" == "hello"
1022 fun +(o: Text): SELFTYPE is abstract
1024 # Concatenates self `i` times
1026 # assert "abc" * 4 == "abcabcabcabc"
1027 # assert "abc" * 1 == "abc"
1028 # assert "abc" * 0 == ""
1029 fun *(i: Int): SELFTYPE is abstract
1031 # Insert `s` at `pos`.
1033 # assert "helloworld".insert_at(" ", 5) == "hello world"
1034 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1036 redef fun substrings is abstract
1038 # Returns a reversed version of self
1040 # assert "hello".reversed == "olleh"
1041 # assert "bob".reversed == "bob"
1042 # assert "".reversed == ""
1043 fun reversed: SELFTYPE is abstract
1045 # A upper case version of `self`
1047 # assert "Hello World!".to_upper == "HELLO WORLD!"
1048 fun to_upper: SELFTYPE is abstract
1050 # A lower case version of `self`
1052 # assert "Hello World!".to_lower == "hello world!"
1053 fun to_lower : SELFTYPE is abstract
1055 # Takes a camel case `self` and converts it to snake case
1057 # assert "randomMethodId".to_snake_case == "random_method_id"
1059 # The rules are the following:
1061 # An uppercase is always converted to a lowercase
1063 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1065 # An uppercase that follows a lowercase is prefixed with an underscore
1067 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1069 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1071 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1073 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1075 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1076 fun to_snake_case: SELFTYPE
1078 if self.is_lower then return self
1080 var new_str = new Buffer.with_cap(self.length)
1081 var prev_is_lower = false
1082 var prev_is_upper = false
1084 for i in [0..length[ do
1086 if char.is_lower then
1088 prev_is_lower = true
1089 prev_is_upper = false
1090 else if char.is_upper then
1091 if prev_is_lower then
1093 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1096 new_str.add(char.to_lower)
1097 prev_is_lower = false
1098 prev_is_upper = true
1101 prev_is_lower = false
1102 prev_is_upper = false
1109 # Takes a snake case `self` and converts it to camel case
1111 # assert "random_method_id".to_camel_case == "randomMethodId"
1113 # If the identifier is prefixed by an underscore, the underscore is ignored
1115 # assert "_private_field".to_camel_case == "_privateField"
1117 # If `self` is upper, it is returned unchanged
1119 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1121 # If there are several consecutive underscores, they are considered as a single one
1123 # assert "random__method_id".to_camel_case == "randomMethodId"
1124 fun to_camel_case: SELFTYPE
1126 if self.is_upper then return self
1128 var new_str = new Buffer
1129 var is_first_char = true
1130 var follows_us = false
1132 for i in [0..length[ do
1134 if is_first_char then
1136 is_first_char = false
1137 else if char == '_
' then
1139 else if follows_us then
1140 new_str.add(char.to_upper)
1150 # Returns a capitalized `self`
1152 # Letters that follow a letter are lowercased
1153 # Letters that follow a non-letter are upcased.
1155 # SEE : `Char::is_letter` for the definition of letter.
1157 # assert "jAVASCRIPT".capitalized == "Javascript"
1158 # assert "i am root".capitalized == "I Am Root"
1159 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1160 fun capitalized: SELFTYPE do
1161 if length == 0 then return self
1163 var buf = new Buffer.with_cap(length)
1165 var curr = chars[0].to_upper
1169 for i in [1 .. length[ do
1172 if prev.is_letter then
1173 buf[i] = curr.to_lower
1175 buf[i] = curr.to_upper
1183 # A mutable sequence of characters.
1184 abstract class Buffer
1187 # Returns an arbitrary subclass of `Buffer` with default parameters
1190 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1191 new with_cap(i: Int) is abstract
1193 redef type SELFTYPE: Buffer is fixed
1195 # Specific implementations MUST set this to `true` in order to invalidate caches
1196 protected var is_dirty = true
1198 # Copy-On-Write flag
1200 # If the `Buffer` was to_s'd
, the next in-place altering
1201 # operation will cause the current `Buffer` to be re-allocated.
1203 # The flag will then be set at `false`.
1204 protected var written
= false
1206 # Modifies the char contained at pos `index`
1208 # DEPRECATED : Use self.chars.[]= instead
1209 fun []=(index
: Int, item
: Char) is abstract
1211 # Adds a char `c` at the end of self
1213 # DEPRECATED : Use self.chars.add instead
1214 fun add
(c
: Char) is abstract
1218 # var b = new Buffer
1220 # assert not b.is_empty
1223 fun clear
is abstract
1225 # Enlarges the subsequent array containing the chars of self
1226 fun enlarge
(cap
: Int) is abstract
1228 # Adds the content of text `s` at the end of self
1230 # var b = new Buffer
1233 # assert b == "helloworld"
1234 fun append
(s
: Text) is abstract
1236 # `self` is appended in such a way that `self` is repeated `r` times
1238 # var b = new Buffer
1241 # assert b == "hellohellohello"
1242 fun times
(r
: Int) is abstract
1244 # Reverses itself in-place
1246 # var b = new Buffer
1249 # assert b == "olleh"
1250 fun reverse
is abstract
1252 # Changes each lower-case char in `self` by its upper-case variant
1254 # var b = new Buffer
1255 # b.append("Hello World!")
1257 # assert b == "HELLO WORLD!"
1258 fun upper
is abstract
1260 # Changes each upper-case char in `self` by its lower-case variant
1262 # var b = new Buffer
1263 # b.append("Hello World!")
1265 # assert b == "hello world!"
1266 fun lower
is abstract
1268 # Capitalizes each word in `self`
1270 # Letters that follow a letter are lowercased
1271 # Letters that follow a non-letter are upcased.
1273 # SEE: `Char::is_letter` for the definition of a letter.
1275 # var b = new FlatBuffer.from("jAVAsCriPt")
1277 # assert b == "Javascript"
1278 # b = new FlatBuffer.from("i am root")
1280 # assert b == "I Am Root"
1281 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1283 # assert b == "Ab_C -Ab0C Ab\nC"
1285 if length
== 0 then return
1286 var c
= self[0].to_upper
1289 for i
in [1 .. length
[ do
1292 if prev
.is_letter
then
1293 self[i
] = c
.to_lower
1295 self[i
] = c
.to_upper
1302 if is_dirty
then hash_cache
= null
1306 # In Buffers, the internal sequence of character is mutable
1307 # Thus, `chars` can be used to modify the buffer.
1308 redef fun chars
: Sequence[Char] is abstract
1310 # In Buffers, the internal sequence of bytes is mutable
1311 # Thus, `bytes` can be used to modify the buffer.
1312 redef fun bytes
: Sequence[Byte] is abstract
1315 # View for chars on Buffer objects, extends Sequence
1316 # for mutation operations
1317 private abstract class BufferCharView
1318 super StringCharView
1319 super Sequence[Char]
1321 redef type SELFTYPE: Buffer
1325 # View for bytes on Buffer objects, extends Sequence
1326 # for mutation operations
1327 private abstract class BufferByteView
1328 super StringByteView
1329 super Sequence[Byte]
1331 redef type SELFTYPE: Buffer
1336 # User readable representation of `self`.
1337 fun to_s
: String do return inspect
1339 # The class name of the object in NativeString format.
1340 private fun native_class_name
: NativeString is intern
1342 # The class name of the object.
1344 # assert 5.class_name == "Int"
1345 fun class_name
: String do return native_class_name
.to_s
1347 # Developer readable representation of `self`.
1348 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1351 return "<{inspect_head}>"
1354 # Return "CLASSNAME:#OBJECTID".
1355 # This function is mainly used with the redefinition of the inspect method
1356 protected fun inspect_head
: String
1358 return "{class_name}:#{object_id.to_hex}"
1363 # assert true.to_s == "true"
1364 # assert false.to_s == "false"
1376 # C function to calculate the length of the `NativeString` to receive `self`
1377 private fun byte_to_s_len
: Int `{
1378 return snprintf(NULL, 0, "0x%02x", self);
1381 # C function to convert an nit Int to a NativeString (char*)
1382 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) `{
1383 snprintf(nstr, strlen, "0x%02x", self);
1386 # Displayable byte in its hexadecimal form (0x..)
1388 # assert 1.to_b.to_s == "0x01"
1389 # assert (-123).to_b.to_s == "0x85"
1391 var nslen
= byte_to_s_len
1392 var ns
= new NativeString(nslen
+ 1)
1394 native_byte_to_s
(ns
, nslen
+ 1)
1395 return ns
.to_s_with_length
(nslen
)
1401 # Wrapper of strerror C function
1402 private fun strerror_ext
: NativeString `{ return strerror(self); `}
1404 # Returns a string describing error number
1405 fun strerror: String do return strerror_ext.to_s
1407 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if 'signed' and negative).
1408 # assume < to_c max const of char
1409 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1416 else if self == 0 then
1423 var pos = digit_count(base) - 1
1424 while pos >= 0 and n > 0 do
1425 s.chars[pos] = (n % base).to_c
1431 # C function to calculate the length of the `NativeString` to receive `self`
1432 private fun int_to_s_len: Int `{
1433 return snprintf
(NULL, 0, "%ld", self);
1436 # C function to convert an nit Int to a NativeString (char*)
1437 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1438 snprintf
(nstr
, strlen
, "%ld", self);
1441 # return displayable int in base base and signed
1442 fun to_base(base: Int, signed: Bool): String is abstract
1444 # return displayable int in hexadecimal
1446 # assert 1.to_hex == "1"
1447 # assert (-255).to_hex == "-ff"
1448 fun to_hex: String do return to_base(16,false)
1452 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1454 # assert 12.34.to_s == "12.34"
1455 # assert (-0120.030).to_s == "-120.03"
1457 # see `to_precision
` for a custom precision.
1459 var str = to_precision( 3 )
1460 if is_inf != 0 or is_nan then return str
1461 var len = str.length
1462 for i in [0..len-1] do
1464 var c = str.chars[j]
1467 else if c == '.' then
1468 return str.substring( 0, j+2 )
1470 return str.substring( 0, j+1 )
1476 # `String` representation of `self` with the given number of `decimals
`
1478 # assert 12.345.to_precision(0) == "12"
1479 # assert 12.345.to_precision(3) == "12.345"
1480 # assert (-12.345).to_precision(3) == "-12.345"
1481 # assert (-0.123).to_precision(3) == "-0.123"
1482 # assert 0.999.to_precision(2) == "1.00"
1483 # assert 0.999.to_precision(4) == "0.9990"
1484 fun to_precision(decimals: Int): String
1486 if is_nan then return "nan"
1488 var isinf = self.is_inf
1491 else if isinf == -1 then
1495 if decimals == 0 then return self.to_i.to_s
1497 for i in [0..decimals[ do f = f * 10.0
1504 if i == 0 then return "0." + "0"*decimals
1506 # Prepare both parts of the float, before and after the "."
1511 if sl > decimals then
1512 # Has something before the "."
1513 p1 = s.substring(0, sl-decimals)
1514 p2 = s.substring(sl-decimals, decimals)
1517 p2 = "0"*(decimals-sl) + s
1520 if i < 0 then p1 = "-" + p1
1522 return p1 + "." + p2
1527 # assert 'x'.to_s == "x"
1530 var s = new Buffer.with_cap(1)
1535 # Returns true if the char is a numerical digit
1537 # assert '0'.is_numeric
1538 # assert '9'.is_numeric
1539 # assert not 'a'.is_numeric
1540 # assert not '?'.is_numeric
1541 fun is_numeric: Bool
1543 return self >= '0' and self <= '9'
1546 # Returns true if the char is an alpha digit
1548 # assert 'a'.is_alpha
1549 # assert 'Z'.is_alpha
1550 # assert not '0'.is_alpha
1551 # assert not '?'.is_alpha
1554 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1557 # Returns true if the char is an alpha or a numeric digit
1559 # assert 'a'.is_alphanumeric
1560 # assert 'Z'.is_alphanumeric
1561 # assert '0'.is_alphanumeric
1562 # assert '9'.is_alphanumeric
1563 # assert not '?'.is_alphanumeric
1564 fun is_alphanumeric: Bool
1566 return self.is_numeric or self.is_alpha
1570 redef class Collection[E]
1571 # String representation of the content of the collection.
1573 # The standard representation is the list of elements separated with commas.
1576 # assert [1,2,3].to_s == "[1,2,3]"
1577 # assert [1..3].to_s == "[1,2,3]"
1578 # assert (new Array[Int]).to_s == "[]" # empty collection
1581 # Subclasses may return a more specific string representation.
1584 return "[" + join(",") + "]"
1587 # Concatenate elements without separators
1590 # assert [1,2,3].plain_to_s == "123"
1591 # assert [11..13].plain_to_s == "111213"
1592 # assert (new Array[Int]).plain_to_s == "" # empty collection
1594 fun plain_to_s: String
1597 for e in self do if e != null then s.append(e.to_s)
1601 # Concatenate and separate each elements with `sep
`.
1603 # assert [1, 2, 3].join(":") == "1:2:3"
1604 # assert [1..3].join(":") == "1:2:3"
1605 fun join(sep: Text): String
1607 if is_empty then return ""
1609 var s = new Buffer # Result
1614 if e != null then s.append(e.to_s)
1616 # Concat other items
1621 if e != null then s.append(e.to_s)
1628 redef class Map[K,V]
1629 # Concatenate couple of 'key value'.
1630 # key and value are separated by `couple_sep
`.
1631 # each couple is separated each couple with `sep
`.
1633 # var m = new ArrayMap[Int, String]
1636 # assert m.join("; ", "=") == "1=one; 10=ten"
1637 fun join(sep: String, couple_sep: String): String is abstract
1641 private var args_cache: nullable Sequence[String] = null
1643 # The arguments of the program as given by the OS
1644 fun program_args: Sequence[String]
1646 if _args_cache == null then init_args
1647 return _args_cache.as(not null)
1650 # The name of the program as given by the OS
1651 fun program_name: String
1653 return native_argv(0).to_s
1656 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
1657 private fun init_args
1659 var argc = native_argc
1660 var args = new Array[String].with_capacity(0)
1663 args[i-1] = native_argv(i).to_s
1669 # First argument of the main C function.
1670 private fun native_argc: Int is intern
1672 # Second argument of the main C function.
1673 private fun native_argv(i: Int): NativeString is intern
1676 # Comparator that efficienlty use `to_s
` to compare things
1678 # The comparaison call `to_s
` on object and use the result to order things.
1680 # var a = [1, 2, 3, 10, 20]
1681 # (new CachedAlphaComparator).sort(a)
1682 # assert a == [1, 10, 2, 20, 3]
1684 # Internally the result of `to_s
` is cached in a HashMap to counter
1685 # uneficient implementation of `to_s
`.
1687 # Note: it caching is not usefull, see `alpha_comparator
`
1688 class CachedAlphaComparator
1690 redef type COMPARED: Object
1692 private var cache = new HashMap[Object, String]
1694 private fun do_to_s(a: Object): String do
1695 if cache.has_key(a) then return cache[a]
1701 redef fun compare(a, b) do
1702 return do_to_s(a) <=> do_to_s(b)
1706 # see `alpha_comparator
`
1707 private class AlphaComparator
1709 redef fun compare(a, b) do return a.to_s <=> b.to_s
1712 # Stateless comparator that naively use `to_s
` to compare things.
1714 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
1715 # on a single instace. See `CachedAlphaComparator` as an alternative.
1717 # var a = [1, 2, 3, 10, 20]
1718 # alpha_comparator.sort(a)
1719 # assert a == [1, 10, 2, 20, 3]
1720 fun alpha_comparator: Comparator do return once new AlphaComparator
1722 # The arguments of the program as given by the OS
1723 fun args: Sequence[String]
1725 return sys.program_args
1728 redef class NativeString
1729 # Returns `self` as a new String.
1730 fun to_s_with_copy: String is abstract
1732 # Returns `self` as a String of `length
`.
1733 fun to_s_with_length(length: Int): String is abstract
1736 redef class NativeArray[E]
1737 # Join all the elements using `to_s
`
1739 # REQUIRE: `self isa NativeArray[String]`
1740 # REQUIRE: all elements are initialized
1741 fun native_to_s: String is abstract