1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
14 # Basic manipulations of strings of characters
19 intrude import collection
::array
26 ###############################################################################
28 ###############################################################################
30 # High-level abstraction for all text representations
34 redef type OTHER: Text
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
39 # Gets a view on the chars of the Text object
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars
: SequenceRead[Char] is abstract
44 # Number of characters contained in self.
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length
: Int is abstract
52 # assert "abcd".substring(1, 2) == "bc"
53 # assert "abcd".substring(-1, 2) == "a"
54 # assert "abcd".substring(1, 0) == ""
55 # assert "abcd".substring(2, 5) == "cd"
57 # A `from` index < 0 will be replaced by 0.
58 # Unless a `count` value is > 0 at the same time.
59 # In this case, `from += count` and `count -= from`.
60 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
62 # Iterates on the substrings of self if any
63 fun substrings
: Iterator[Text] is abstract
65 # Is the current Text empty (== "")
68 # assert not "foo".is_empty
69 fun is_empty
: Bool do return self.length
== 0
71 # Returns an empty Text of the right type
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty
: SELFTYPE is abstract
77 # Gets the first char of the Text
79 # DEPRECATED : Use self.chars.first instead
80 fun first
: Char do return self.chars
[0]
82 # Access a character at `index` in the string.
84 # assert "abcd"[2] == 'c'
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index
: Int): Char do return self.chars
[index
]
89 # Gets the index of the first occurence of 'c'
91 # Returns -1 if not found
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of
(c
: Char): Int
96 return index_of_from
(c
, 0)
99 # Gets the last char of self
101 # DEPRECATED : Use self.chars.last instead
102 fun last
: Char do return self.chars
[length-1
]
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
106 # Returns -1 if not found
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from
(c
: Char, pos
: Int): Int
111 var iter
= self.chars
.iterator_from
(pos
)
113 if iter
.item
== c
then return iter
.index
119 # Gets the last index of char ´c´
121 # Returns -1 if not found
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of
(c
: Char): Int
126 return last_index_of_from
(c
, length
- 1)
129 # Return a null terminated char *
130 fun to_cstring
: NativeString do return flatten
.to_cstring
132 # The index of the last occurrence of an element starting from pos (in reverse order).
134 # var s = "/etc/bin/test/test.nit"
135 # assert s.last_index_of_from('/', s.length-1) == 13
136 # assert s.last_index_of_from('/', 12) == 8
138 # Returns -1 if not found
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from
(item
: Char, pos
: Int): Int
143 var iter
= self.chars
.reverse_iterator_from
(pos
)
145 if iter
.item
== item
then return iter
.index
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 # If `self` contains only digits, return the corresponding integer
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
233 return to_s
.to_cstring
.atoi
236 # If `self` contains a float, return the corresponding float
238 # assert "123".to_f == 123.0
239 # assert "-1".to_f == -1.0
240 # assert "-1.2e-3".to_f == -0.0012
244 return to_s
.to_cstring
.atof
247 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
249 # assert "ff".to_hex == 255
250 fun to_hex
: Int do return a_to
(16)
252 # If `self` contains only digits and letters, return the corresponding integer in a given base
254 # assert "120".a_to(3) == 15
255 fun a_to
(base
: Int) : Int
260 for j
in [0..length
[ do
282 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
284 # assert "123".is_numeric == true
285 # assert "1.2".is_numeric == true
286 # assert "1,2".is_numeric == true
287 # assert "1..2".is_numeric == false
290 var has_point_or_comma
= false
291 for i
in [0..length
[ do
293 if not c
.is_numeric
then
294 if (c
== '.' or c
== ',') and not has_point_or_comma
then
295 has_point_or_comma
= true
304 # Returns `true` if the string contains only Hex chars
306 # assert "048bf".is_hex == true
307 # assert "ABCDEF".is_hex == true
308 # assert "0G".is_hex == false
311 for i
in [0..length
[ do
313 if not (c
>= 'a' and c
<= 'f') and
314 not (c
>= 'A' and c
<= 'F') and
315 not (c
>= '0' and c
<= '9') then return false
320 # Are all letters in `self` upper-case ?
322 # assert "HELLO WORLD".is_upper == true
323 # assert "%$&%!".is_upper == true
324 # assert "hello world".is_upper == false
325 # assert "Hello World".is_upper == false
328 for i
in [0..length
[ do
330 if char
.is_lower
then return false
335 # Are all letters in `self` lower-case ?
337 # assert "hello world".is_lower == true
338 # assert "%$&%!".is_lower == true
339 # assert "Hello World".is_lower == false
342 for i
in [0..length
[ do
344 if char
.is_upper
then return false
349 # Removes the whitespaces at the beginning of self
351 # assert " \n\thello \n\t".l_trim == "hello \n\t"
353 # A whitespace is defined as any character which ascii value is less than or equal to 32
356 var iter
= self.chars
.iterator
358 if iter
.item
.ascii
> 32 then break
361 if iter
.index
== length
then return self.empty
362 return self.substring_from
(iter
.index
)
365 # Removes the whitespaces at the end of self
367 # assert " \n\thello \n\t".r_trim == " \n\thello"
369 # A whitespace is defined as any character which ascii value is less than or equal to 32
372 var iter
= self.chars
.reverse_iterator
374 if iter
.item
.ascii
> 32 then break
377 if iter
.index
< 0 then return self.empty
378 return self.substring
(0, iter
.index
+ 1)
381 # Trims trailing and preceding white spaces
382 # A whitespace is defined as any character which ascii value is less than or equal to 32
384 # assert " Hello World ! ".trim == "Hello World !"
385 # assert "\na\nb\tc\t".trim == "a\nb\tc"
386 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
388 # Returns `self` removed from its last line terminator (if any).
390 # assert "Hello\n".chomp == "Hello"
391 # assert "Hello".chomp == "Hello"
393 # assert "\n".chomp == ""
394 # assert "".chomp == ""
396 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
397 # A single line terminator, the last one, is removed.
399 # assert "\r\n".chomp == ""
400 # assert "\r\n\n".chomp == "\r\n"
401 # assert "\r\n\r\n".chomp == "\r\n"
402 # assert "\r\n\r".chomp == "\r\n"
404 # Note: unlike with most IO methods like `IStream::read_line`,
405 # a single `\r` is considered here to be a line terminator and will be removed.
409 if len
== 0 then return self
410 var l
= self.chars
.last
412 return substring
(0, len-1
)
413 else if l
!= '\n' then
415 else if len
> 1 and self.chars
[len-2
] == '\r' then
416 return substring
(0, len-2
)
418 return substring
(0, len-1
)
422 # Justify a self in a space of `length`
424 # `left` is the space ratio on the left side.
425 # * 0.0 for left-justified (no space at the left)
426 # * 1.0 for right-justified (all spaces at the left)
427 # * 0.5 for centered (half the spaces at the left)
431 # assert "hello".justify(10, 0.0) == "hello "
432 # assert "hello".justify(10, 1.0) == " hello"
433 # assert "hello".justify(10, 0.5) == " hello "
435 # If `length` is not enough, `self` is returned as is.
437 # assert "hello".justify(2, 0.0) == "hello"
439 # REQUIRE: `left >= 0.0 and left <= 1.0`
440 # ENSURE: `self.length <= length implies result.length == length`
441 # ENSURE: `self.length >= length implies result == self`
442 fun justify
(length
: Int, left
: Float): SELFTYPE
444 var diff
= length
- self.length
445 if diff
<= 0 then return self
446 assert left
>= 0.0 and left
<= 1.0
447 var before
= (diff
.to_f
* left
).to_i
448 return " " * before
+ self + " " * (diff-before
)
451 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
453 # This method is injective (two different inputs never produce the same
454 # output) and the returned string always respect the following rules:
456 # * Contains only US-ASCII letters, digits and underscores.
457 # * Never starts with a digit.
458 # * Never ends with an underscore.
459 # * Never contains two contiguous underscores.
461 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
462 # assert "__".to_cmangle == "_95d_95d"
463 # assert "__d".to_cmangle == "_95d_d"
464 # assert "_d_".to_cmangle == "_d_95d"
465 # assert "_42".to_cmangle == "_95d42"
466 # assert "foo".to_cmangle == "foo"
467 # assert "".to_cmangle == ""
468 fun to_cmangle
: String
470 if is_empty
then return ""
471 var res
= new FlatBuffer
472 var underscore
= false
476 if c
>= '0' and c
<= '9' then
478 res
.append
(c
.ascii
.to_s
)
482 for i
in [start
..length
[ do
484 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
490 res
.append
('_'.ascii
.to_s
)
493 if c
>= '0' and c
<= '9' then
496 else if c
== '_' then
501 res
.append
(c
.ascii
.to_s
)
507 res
.append
('_'.ascii
.to_s
)
513 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
515 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
516 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
517 fun escape_to_c
: String
519 var b
= new FlatBuffer
520 for i
in [0..length
[ do
524 else if c
== '\0' then
526 else if c
== '"' then
528 else if c == '\'' then
530 else if c == '\\
' then
532 else if c.ascii < 32 then
533 b.append("\\{c.ascii.to_base(8, false)}")
541 # Escape additionnal characters
542 # The result might no be legal in C but be used in other languages
544 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
545 fun escape_more_to_c(chars: String): String
547 var b = new FlatBuffer
548 for c in escape_to_c.chars do
549 if chars.chars.has(c) then
557 # Escape to C plus braces
559 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
560 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
562 # Escape to POSIX Shell (sh).
564 # Abort if the text contains a null byte.
566 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
567 fun escape_to_sh
: String do
568 var b
= new FlatBuffer
570 for i in [0..length[ do
575 assert without_null_byte
: c
!= '\0'
583 # Escape to include in a Makefile
585 # Unfortunately, some characters are not escapable in Makefile.
586 # These characters are `;`, `|`, `\`, and the non-printable ones.
587 # They will be rendered as `"?{hex}"`.
588 fun escape_to_mk: String do
589 var b = new FlatBuffer
590 for i in [0..length[ do
594 else if c == ':' or c == ' ' or c == '#' then
597 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
598 b
.append
("?{c.ascii.to_base(16, false)}")
606 # Return a string where Nit escape sequences are transformed.
609 # assert s.length == 2
610 # var u = s.unescape_nit
611 # assert u.length == 1
612 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
613 fun unescape_nit
: String
615 var res
= new FlatBuffer.with_capacity
(self.length
)
616 var was_slash
= false
617 for i
in [0..length
[ do
619 if not was_slash
then
630 else if c
== 'r' then
632 else if c
== 't' then
634 else if c
== '0' then
643 # Encode `self` to percent (or URL) encoding
645 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
646 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
647 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
648 fun to_percent_encoding
: String
650 var buf
= new FlatBuffer
652 for i
in [0..length
[ do
654 if (c
>= '0' and c
<= '9') or
655 (c
>= 'a' and c
<= 'z') or
656 (c
>= 'A' and c
<= 'Z') or
657 c
== '-' or c
== '.' or
661 else buf
.append
"%{c.ascii.to_hex}"
667 # Decode `self` from percent (or URL) encoding to a clear string
669 # Replace invalid use of '%' with '?'.
671 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
672 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
673 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
674 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
675 # assert "incomplete %".from_percent_encoding == "incomplete ?"
676 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
677 fun from_percent_encoding
: String
679 var buf
= new FlatBuffer
685 if i
+ 2 >= length
then
686 # What follows % has been cut off
690 var hex_s
= substring
(i
, 2)
692 var hex_i
= hex_s
.to_hex
696 # What follows a % is not Hex
709 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
711 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
713 # 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>
714 fun html_escape
: SELFTYPE
716 var buf
= new FlatBuffer
718 for i
in [0..length
[ do
722 else if c
== '<' then
724 else if c
== '>' then
726 else if c
== '"' then
728 else if c
== '\'' then
730 else if c == '/' then
739 # Two pieces of text are equals if thez have the same characters in the same order.
741 # assert "hello" == "hello"
742 # assert "hello" != "HELLO"
743 # assert "hello" == "hel"+"lo"
745 # Things that are not Text are not equal.
748 # assert "9" != ['9']
751 # assert "9".chars.first == '9' # equality of Char
752 # assert "9".chars == ['9'] # equality of Sequence
753 # assert "9".to_i == 9 # equality of Int
756 if o == null then return false
757 if not o isa Text then return false
758 if self.is_same_instance(o) then return true
759 if self.length != o.length then return false
760 return self.chars == o.chars
763 # Lexicographical comparaison
765 # assert "abc" < "xy"
766 # assert "ABC" < "abc"
769 var self_chars = self.chars.iterator
770 var other_chars = other.chars.iterator
772 while self_chars.is_ok and other_chars.is_ok do
773 if self_chars.item < other_chars.item then return true
774 if self_chars.item > other_chars.item then return false
779 if self_chars.is_ok then
786 # Escape string used in labels for graphviz
788 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
789 fun escape_to_dot: String
791 return escape_more_to_c("|\{\}<>")
794 # Flat representation of self
795 fun flatten: FlatText is abstract
797 private var hash_cache: nullable Int = null
801 if hash_cache == null then
802 # djb2 hash algorithm
805 for i in [0..length[ do
807 h = h.lshift(5) + h + char.ascii
812 return hash_cache.as(not null)
817 # All kinds of array-based text representations.
818 abstract class FlatText
821 # Underlying C-String (`char*`)
823 # Warning : Might be void in some subclasses, be sure to check
824 # if set before using it.
825 private var items: NativeString is noinit
827 # Real items, used as cache for to_cstring is called
828 private var real_items: nullable NativeString = null
830 redef var length: Int = 0
841 redef fun flatten do return self
844 # Abstract class for the SequenceRead compatible
845 # views on String and Buffer objects
846 private abstract class StringCharView
847 super SequenceRead[Char]
853 redef fun is_empty do return target.is_empty
855 redef fun length do return target.length
857 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
859 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
862 # View on Buffer objects, extends Sequence
863 # for mutation operations
864 private abstract class BufferCharView
868 redef type SELFTYPE: Buffer
872 # A `String` holds and manipulates an arbitrary sequence of characters.
874 # String objects may be created using literals.
876 # assert "Hello World!" isa String
877 abstract class String
880 redef type SELFTYPE: String
882 redef fun to_s do return self
884 # Concatenates `o` to `self`
886 # assert "hello" + "world" == "helloworld"
887 # assert "" + "hello" + "" == "hello"
888 fun +(o: Text): SELFTYPE is abstract
890 # Concatenates self `i` times
892 # assert "abc" * 4 == "abcabcabcabc"
893 # assert "abc" * 1 == "abc"
894 # assert "abc" * 0 == ""
895 fun *(i: Int): SELFTYPE is abstract
897 # Insert `s` at `pos`.
899 # assert "helloworld".insert_at(" ", 5) == "hello world"
900 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
902 redef fun substrings: Iterator[String] is abstract
904 # Returns a reversed version of self
906 # assert "hello".reversed == "olleh"
907 # assert "bob".reversed == "bob"
908 # assert "".reversed == ""
909 fun reversed: SELFTYPE is abstract
911 # A upper case version of `self`
913 # assert "Hello World!".to_upper == "HELLO WORLD!"
914 fun to_upper: SELFTYPE is abstract
916 # A lower case version of `self`
918 # assert "Hello World!".to_lower == "hello world!"
919 fun to_lower : SELFTYPE is abstract
921 # Takes a camel case `self` and converts it to snake case
923 # assert "randomMethodId".to_snake_case == "random_method_id"
925 # If `self` is upper, it is returned unchanged
927 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
929 # If the identifier is prefixed by an underscore, the underscore is ignored
931 # assert "_privateField".to_snake_case == "_private_field"
932 fun to_snake_case: SELFTYPE
934 if self.is_upper then return self
936 var new_str = new FlatBuffer.with_capacity(self.length)
937 var is_first_char = true
939 for i in [0..length[ do
941 if is_first_char then
942 new_str.add(char.to_lower)
943 is_first_char = false
944 else if char.is_upper then
946 new_str.add(char.to_lower)
955 # Takes a snake case `self` and converts it to camel case
957 # assert "random_method_id".to_camel_case == "randomMethodId"
959 # If the identifier is prefixed by an underscore, the underscore is ignored
961 # assert "_private_field".to_camel_case == "_privateField"
963 # If `self` is upper, it is returned unchanged
965 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
967 # If there are several consecutive underscores, they are considered as a single one
969 # assert "random__method_id".to_camel_case == "randomMethodId"
970 fun to_camel_case: SELFTYPE
972 if self.is_upper then return self
974 var new_str = new FlatBuffer
975 var is_first_char = true
976 var follows_us = false
978 for i in [0..length[ do
980 if is_first_char then
982 is_first_char = false
983 else if char == '_
' then
985 else if follows_us then
986 new_str.add(char.to_upper)
996 # Returns a capitalized `self`
998 # Letters that follow a letter are lowercased
999 # Letters that follow a non-letter are upcased.
1001 # SEE : `Char::is_letter` for the definition of letter.
1003 # assert "jAVASCRIPT".capitalized == "Javascript"
1004 # assert "i am root".capitalized == "I Am Root"
1005 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1006 fun capitalized: SELFTYPE do
1007 if length == 0 then return self
1009 var buf = new FlatBuffer.with_capacity(length)
1011 var curr = chars[0].to_upper
1015 for i in [1 .. length[ do
1018 if prev.is_letter then
1019 buf[i] = curr.to_lower
1021 buf[i] = curr.to_upper
1029 private class FlatSubstringsIter
1030 super Iterator[FlatText]
1032 var tgt: nullable FlatText
1036 return tgt.as(not null)
1039 redef fun is_ok do return tgt != null
1041 redef fun next do tgt = null
1044 # Immutable strings of characters.
1049 # Index in _items of the start of the string
1050 private var index_from: Int is noinit
1052 # Indes in _items of the last item of the string
1053 private var index_to: Int is noinit
1055 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
1059 # Check that the index (+ index_from) is not larger than indexTo
1060 # In other terms, if the index is valid
1062 assert (index + index_from) <= index_to
1063 return items[index + index_from]
1066 ################################################
1067 # AbstractString specific methods #
1068 ################################################
1072 var native = new NativeString(self.length + 1)
1073 var length = self.length
1074 var items = self.items
1077 while pos < length do
1078 native[pos] = items[ipos]
1082 return native.to_s_with_length(self.length)
1085 redef fun substring(from, count)
1091 if count < 0 then count = 0
1095 var realFrom = index_from + from
1097 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
1099 if count == 0 then return empty
1101 var to = realFrom + count - 1
1103 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
1106 redef fun empty do return "".as(FlatString)
1110 var outstr = new NativeString(self.length + 1)
1113 var myitems = self.items
1114 var index_from = self.index_from
1115 var max = self.index_to
1117 while index_from <= max do
1118 outstr[out_index] = myitems[index_from].to_upper
1123 outstr[self.length] = '\
0'
1125 return outstr.to_s_with_length(self.length)
1130 var outstr = new NativeString(self.length + 1)
1133 var myitems = self.items
1134 var index_from = self.index_from
1135 var max = self.index_to
1137 while index_from <= max do
1138 outstr[out_index] = myitems[index_from].to_lower
1143 outstr[self.length] = '\
0'
1145 return outstr.to_s_with_length(self.length)
1150 var i = self.index_from
1151 var imax = self.index_to
1158 ##################################################
1159 # String Specific Methods #
1160 ##################################################
1162 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1170 redef fun to_cstring: NativeString
1172 if real_items != null then
1173 return real_items.as(not null)
1175 var newItems = new NativeString(length + 1)
1176 self.items.copy_to(newItems, length, index_from, 0)
1177 newItems[length] = '\
0'
1178 self.real_items = newItems
1185 if not other isa FlatString then return super
1187 if self.object_id == other.object_id then return true
1189 var my_length = length
1191 if other.length != my_length then return false
1193 var my_index = index_from
1194 var its_index = other.index_from
1196 var last_iteration = my_index + my_length
1198 var itsitems = other.items
1199 var myitems = self.items
1201 while my_index < last_iteration do
1202 if myitems[my_index] != itsitems[its_index] then return false
1212 if not other isa FlatString then return super
1214 if self.object_id == other.object_id then return false
1216 var my_curr_char : Char
1217 var its_curr_char : Char
1219 var curr_id_self = self.index_from
1220 var curr_id_other = other.index_from
1222 var my_items = self.items
1223 var its_items = other.items
1225 var my_length = self.length
1226 var its_length = other.length
1228 var max_iterations = curr_id_self + my_length
1230 while curr_id_self < max_iterations do
1231 my_curr_char = my_items[curr_id_self]
1232 its_curr_char = its_items[curr_id_other]
1234 if my_curr_char != its_curr_char then
1235 if my_curr_char < its_curr_char then return true
1243 return my_length < its_length
1248 var my_length = self.length
1249 var its_length = s.length
1251 var total_length = my_length + its_length
1253 var target_string = new NativeString(my_length + its_length + 1)
1255 self.items.copy_to(target_string, my_length, index_from, 0)
1256 if s isa FlatString then
1257 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1258 else if s isa FlatBuffer then
1259 s.items.copy_to(target_string, its_length, 0, my_length)
1261 var curr_pos = my_length
1262 for i in [0..s.length[ do
1264 target_string[curr_pos] = c
1269 target_string[total_length] = '\
0'
1271 return target_string.to_s_with_length(total_length)
1278 var my_length = self.length
1280 var final_length = my_length * i
1282 var my_items = self.items
1284 var target_string = new NativeString(final_length + 1)
1286 target_string[final_length] = '\
0'
1288 var current_last = 0
1290 for iteration in [1 .. i] do
1291 my_items.copy_to(target_string, my_length, 0, current_last)
1292 current_last += my_length
1295 return target_string.to_s_with_length(final_length)
1300 if hash_cache == null then
1301 # djb2 hash algorithm
1307 while i <= index_to do
1308 h = h.lshift(5) + h + myitems[i].ascii
1315 return hash_cache.as(not null)
1318 redef fun substrings do return new FlatSubstringsIter(self)
1321 private class FlatStringReverseIterator
1322 super IndexedIterator[Char]
1324 var target: FlatString
1326 var target_items: NativeString
1330 init with_pos(tgt: FlatString, pos: Int)
1333 target_items = tgt.items
1334 curr_pos = pos + tgt.index_from
1337 redef fun is_ok do return curr_pos >= target.index_from
1339 redef fun item do return target_items[curr_pos]
1341 redef fun next do curr_pos -= 1
1343 redef fun index do return curr_pos - target.index_from
1347 private class FlatStringIterator
1348 super IndexedIterator[Char]
1350 var target: FlatString
1352 var target_items: NativeString
1356 init with_pos(tgt: FlatString, pos: Int)
1359 target_items = tgt.items
1360 curr_pos = pos + target.index_from
1363 redef fun is_ok do return curr_pos <= target.index_to
1365 redef fun item do return target_items[curr_pos]
1367 redef fun next do curr_pos += 1
1369 redef fun index do return curr_pos - target.index_from
1373 private class FlatStringCharView
1374 super StringCharView
1376 redef type SELFTYPE: FlatString
1380 # Check that the index (+ index_from) is not larger than indexTo
1381 # In other terms, if the index is valid
1383 var target = self.target
1384 assert (index + target.index_from) <= target.index_to
1385 return target.items[index + target.index_from]
1388 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1390 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1394 # A mutable sequence of characters.
1395 abstract class Buffer
1398 redef type SELFTYPE: Buffer
1400 # Specific implementations MUST set this to `true` in order to invalidate caches
1401 protected var is_dirty = true
1403 # Copy-On-Write flag
1405 # If the `Buffer` was to_s'd
, the next in-place altering
1406 # operation will cause the current `Buffer` to be re-allocated.
1408 # The flag will then be set at `false`.
1409 protected var written
= false
1411 # Modifies the char contained at pos `index`
1413 # DEPRECATED : Use self.chars.[]= instead
1414 fun []=(index
: Int, item
: Char) is abstract
1416 # Adds a char `c` at the end of self
1418 # DEPRECATED : Use self.chars.add instead
1419 fun add
(c
: Char) is abstract
1423 # var b = new FlatBuffer
1425 # assert not b.is_empty
1428 fun clear
is abstract
1430 # Enlarges the subsequent array containing the chars of self
1431 fun enlarge
(cap
: Int) is abstract
1433 # Adds the content of text `s` at the end of self
1435 # var b = new FlatBuffer
1438 # assert b == "helloworld"
1439 fun append
(s
: Text) is abstract
1441 # `self` is appended in such a way that `self` is repeated `r` times
1443 # var b = new FlatBuffer
1446 # assert b == "hellohellohello"
1447 fun times
(r
: Int) is abstract
1449 # Reverses itself in-place
1451 # var b = new FlatBuffer
1454 # assert b == "olleh"
1455 fun reverse
is abstract
1457 # Changes each lower-case char in `self` by its upper-case variant
1459 # var b = new FlatBuffer
1460 # b.append("Hello World!")
1462 # assert b == "HELLO WORLD!"
1463 fun upper
is abstract
1465 # Changes each upper-case char in `self` by its lower-case variant
1467 # var b = new FlatBuffer
1468 # b.append("Hello World!")
1470 # assert b == "hello world!"
1471 fun lower
is abstract
1473 # Capitalizes each word in `self`
1475 # Letters that follow a letter are lowercased
1476 # Letters that follow a non-letter are upcased.
1478 # SEE: `Char::is_letter` for the definition of a letter.
1480 # var b = new FlatBuffer.from("jAVAsCriPt")
1482 # assert b == "Javascript"
1483 # b = new FlatBuffer.from("i am root")
1485 # assert b == "I Am Root"
1486 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1488 # assert b == "Ab_C -Ab0C Ab\nC"
1490 if length
== 0 then return
1491 var c
= self[0].to_upper
1494 for i
in [1 .. length
[ do
1497 if prev
.is_letter
then
1498 self[i
] = c
.to_lower
1500 self[i
] = c
.to_upper
1507 if is_dirty
then hash_cache
= null
1511 # In Buffers, the internal sequence of character is mutable
1512 # Thus, `chars` can be used to modify the buffer.
1513 redef fun chars
: Sequence[Char] is abstract
1516 # Mutable strings of characters.
1521 redef type SELFTYPE: FlatBuffer
1523 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1525 private var capacity
: Int = 0
1527 redef fun substrings
do return new FlatSubstringsIter(self)
1529 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1531 # This happens when an operation modifies the current `Buffer` and
1532 # the Copy-On-Write flag `written` is set at true.
1533 private fun reset
do
1534 var nns
= new NativeString(capacity
)
1535 items
.copy_to
(nns
, length
, 0, 0)
1543 assert index
< length
1547 redef fun []=(index
, item
)
1550 if index
== length
then
1554 if written
then reset
1555 assert index
>= 0 and index
< length
1562 if capacity
<= length
then enlarge
(length
+ 5)
1569 if written
then reset
1573 redef fun empty
do return new FlatBuffer
1575 redef fun enlarge
(cap
)
1578 if cap
<= c
then return
1579 while c
<= cap
do c
= c
* 2 + 2
1580 # The COW flag can be set at false here, since
1581 # it does a copy of the current `Buffer`
1583 var a
= new NativeString(c
+1)
1584 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1589 redef fun to_s
: String
1592 if length
== 0 then items
= new NativeString(1)
1593 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1596 redef fun to_cstring
1599 var new_native
= new NativeString(length
+ 1)
1600 new_native
[length
] = '\0'
1601 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1602 real_items
= new_native
1605 return real_items
.as(not null)
1608 # Create a new empty string.
1611 # Create a new string copied from `s`.
1614 capacity
= s
.length
+ 1
1616 items
= new NativeString(capacity
)
1617 if s
isa FlatString then
1618 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1619 else if s
isa FlatBuffer then
1620 s
.items
.copy_to
(items
, length
, 0, 0)
1623 for i
in [0..s
.length
[ do
1631 # Create a new empty string with a given capacity.
1632 init with_capacity
(cap
: Int)
1635 # _items = new NativeString.calloc(cap)
1636 items
= new NativeString(cap
+1)
1643 if s
.is_empty
then return
1646 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1647 if s
isa FlatString then
1648 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1649 else if s
isa FlatBuffer then
1650 s
.items
.copy_to
(items
, sl
, 0, length
)
1652 var curr_pos
= self.length
1653 for i
in [0..s
.length
[ do
1662 # Copies the content of self in `dest`
1663 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1665 var self_chars
= self.chars
1666 var dest_chars
= dest
.chars
1667 for i
in [0..len-1
] do
1668 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1672 redef fun substring
(from
, count
)
1676 if from
< 0 then from
= 0
1677 if count
> length
then count
= length
1678 if from
< count
then
1679 var r
= new FlatBuffer.with_capacity
(count
- from
)
1680 while from
< count
do
1681 r
.chars
.push
(items
[from
])
1686 return new FlatBuffer
1693 var ns
= new NativeString(capacity
)
1705 redef fun times
(repeats
)
1707 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1708 for i
in [1..repeats
[ do
1715 if written
then reset
1719 it
[id
] = it
[id
].to_upper
1726 if written
then reset
1730 it
[id
] = it
[id
].to_lower
1736 private class FlatBufferReverseIterator
1737 super IndexedIterator[Char]
1739 var target
: FlatBuffer
1741 var target_items
: NativeString
1745 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1748 if tgt
.length
> 0 then target_items
= tgt
.items
1752 redef fun index
do return curr_pos
1754 redef fun is_ok
do return curr_pos
>= 0
1756 redef fun item
do return target_items
[curr_pos
]
1758 redef fun next
do curr_pos
-= 1
1762 private class FlatBufferCharView
1763 super BufferCharView
1765 redef type SELFTYPE: FlatBuffer
1767 redef fun [](index
) do return target
.items
[index
]
1769 redef fun []=(index
, item
)
1771 assert index
>= 0 and index
<= length
1772 if index
== length
then
1776 target
.items
[index
] = item
1789 fun enlarge
(cap
: Int)
1796 var s_length
= s
.length
1797 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1800 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1802 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1806 private class FlatBufferIterator
1807 super IndexedIterator[Char]
1809 var target
: FlatBuffer
1811 var target_items
: NativeString
1815 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1818 if tgt
.length
> 0 then target_items
= tgt
.items
1822 redef fun index
do return curr_pos
1824 redef fun is_ok
do return curr_pos
< target
.length
1826 redef fun item
do return target_items
[curr_pos
]
1828 redef fun next
do curr_pos
+= 1
1832 ###############################################################################
1834 ###############################################################################
1837 # User readable representation of `self`.
1838 fun to_s
: String do return inspect
1840 # The class name of the object in NativeString format.
1841 private fun native_class_name
: NativeString is intern
1843 # The class name of the object.
1845 # assert 5.class_name == "Int"
1846 fun class_name
: String do return native_class_name
.to_s
1848 # Developer readable representation of `self`.
1849 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1852 return "<{inspect_head}>"
1855 # Return "CLASSNAME:#OBJECTID".
1856 # This function is mainly used with the redefinition of the inspect method
1857 protected fun inspect_head
: String
1859 return "{class_name}:#{object_id.to_hex}"
1864 # assert true.to_s == "true"
1865 # assert false.to_s == "false"
1878 # Wrapper of strerror C function
1879 private fun strerror_ext
: NativeString is extern `{
1880 return strerror(recv);
1883 # Returns a string describing error number
1884 fun strerror
: String do return strerror_ext
.to_s
1886 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1887 # assume < to_c max const of char
1888 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1895 else if self == 0 then
1902 var pos
= digit_count
(base
) - 1
1903 while pos
>= 0 and n
> 0 do
1904 s
.chars
[pos
] = (n
% base
).to_c
1910 # C function to convert an nit Int to a NativeString (char*)
1911 private fun native_int_to_s
: NativeString is extern "native_int_to_s"
1913 # return displayable int in base 10 and signed
1915 # assert 1.to_s == "1"
1916 # assert (-123).to_s == "-123"
1918 return native_int_to_s
.to_s
1921 # return displayable int in hexadecimal
1923 # assert 1.to_hex == "1"
1924 # assert (-255).to_hex == "-ff"
1925 fun to_hex
: String do return to_base
(16,false)
1927 # return displayable int in base base and signed
1928 fun to_base
(base
: Int, signed
: Bool): String
1930 var l
= digit_count
(base
)
1931 var s
= new FlatBuffer.from
(" " * l
)
1932 fill_buffer
(s
, base
, signed
)
1938 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1940 # assert 12.34.to_s == "12.34"
1941 # assert (-0120.030).to_s == "-120.03"
1943 # see `to_precision` for a custom precision.
1945 var str
= to_precision
( 3 )
1946 if is_inf
!= 0 or is_nan
then return str
1947 var len
= str
.length
1948 for i
in [0..len-1
] do
1950 var c
= str
.chars
[j
]
1953 else if c
== '.' then
1954 return str
.substring
( 0, j
+2 )
1956 return str
.substring
( 0, j
+1 )
1962 # `String` representation of `self` with the given number of `decimals`
1964 # assert 12.345.to_precision(0) == "12"
1965 # assert 12.345.to_precision(3) == "12.345"
1966 # assert (-12.345).to_precision(3) == "-12.345"
1967 # assert (-0.123).to_precision(3) == "-0.123"
1968 # assert 0.999.to_precision(2) == "1.00"
1969 # assert 0.999.to_precision(4) == "0.9990"
1970 fun to_precision
(decimals
: Int): String
1972 if is_nan
then return "nan"
1974 var isinf
= self.is_inf
1977 else if isinf
== -1 then
1981 if decimals
== 0 then return self.to_i
.to_s
1983 for i
in [0..decimals
[ do f
= f
* 10.0
1990 if i
== 0 then return "0." + "0"*decimals
1992 # Prepare both parts of the float, before and after the "."
1997 if sl
> decimals
then
1998 # Has something before the "."
1999 p1
= s
.substring
(0, sl-decimals
)
2000 p2
= s
.substring
(sl-decimals
, decimals
)
2003 p2
= "0"*(decimals-sl
) + s
2006 if i
< 0 then p1
= "-" + p1
2008 return p1
+ "." + p2
2011 # `self` representation with `nb` digits after the '.'.
2013 # assert 12.345.to_precision_native(1) == "12.3"
2014 # assert 12.345.to_precision_native(2) == "12.35"
2015 # assert 12.345.to_precision_native(3) == "12.345"
2016 # assert 12.345.to_precision_native(4) == "12.3450"
2017 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
2021 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
2022 str = malloc(size + 1);
2023 sprintf(str, "%.*f", (int)nb, recv );
2025 return NativeString_to_s( str );
2030 # assert 'x'.to_s == "x"
2033 var s
= new FlatBuffer.with_capacity
(1)
2038 # Returns true if the char is a numerical digit
2040 # assert '0'.is_numeric
2041 # assert '9'.is_numeric
2042 # assert not 'a'.is_numeric
2043 # assert not '?'.is_numeric
2044 fun is_numeric
: Bool
2046 return self >= '0' and self <= '9'
2049 # Returns true if the char is an alpha digit
2051 # assert 'a'.is_alpha
2052 # assert 'Z'.is_alpha
2053 # assert not '0'.is_alpha
2054 # assert not '?'.is_alpha
2057 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2060 # Returns true if the char is an alpha or a numeric digit
2062 # assert 'a'.is_alphanumeric
2063 # assert 'Z'.is_alphanumeric
2064 # assert '0'.is_alphanumeric
2065 # assert '9'.is_alphanumeric
2066 # assert not '?'.is_alphanumeric
2067 fun is_alphanumeric
: Bool
2069 return self.is_numeric
or self.is_alpha
2073 redef class Collection[E
]
2074 # Concatenate elements.
2077 var s
= new FlatBuffer
2078 for e
in self do if e
!= null then s
.append
(e
.to_s
)
2082 # Concatenate and separate each elements with `sep`.
2084 # assert [1, 2, 3].join(":") == "1:2:3"
2085 # assert [1..3].join(":") == "1:2:3"
2086 fun join
(sep
: Text): String
2088 if is_empty
then return ""
2090 var s
= new FlatBuffer # Result
2095 if e
!= null then s
.append
(e
.to_s
)
2097 # Concat other items
2102 if e
!= null then s
.append
(e
.to_s
)
2109 redef class Array[E
]
2111 # Fast implementation
2115 if l
== 0 then return ""
2116 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
2118 var na
= new NativeArray[String](l
)
2124 if itsi
== null then
2134 var ns
= new NativeString(sl
+ 1)
2140 var tpl
= tmp
.length
2141 if tmp
isa FlatString then
2142 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2145 for j
in tmp
.substrings
do
2146 var s
= j
.as(FlatString)
2148 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2154 return ns
.to_s_with_length
(sl
)
2158 redef class Map[K
,V
]
2159 # Concatenate couple of 'key value'.
2160 # key and value are separated by `couple_sep`.
2161 # each couple is separated each couple with `sep`.
2163 # var m = new ArrayMap[Int, String]
2166 # assert m.join("; ", "=") == "1=one; 10=ten"
2167 fun join
(sep
: String, couple_sep
: String): String
2169 if is_empty
then return ""
2171 var s
= new FlatBuffer # Result
2177 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2179 # Concat other items
2185 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2192 ###############################################################################
2194 ###############################################################################
2196 # Native strings are simple C char *
2197 extern class NativeString `{ char* `}
2198 # Creates a new NativeString with a capacity of `length
`
2199 new(length: Int) is intern
2201 # Get char at `index
`.
2202 fun [](index: Int): Char is intern
2204 # Set char `item
` at index.
2205 fun []=(index: Int, item: Char) is intern
2207 # Copy `self` to `dest
`.
2208 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2210 # Position of the first nul character.
2211 fun cstring_length: Int
2214 while self[l] != '\0' do l += 1
2218 # Parse `self` as an Int.
2219 fun atoi: Int is intern
2221 # Parse `self` as a Float.
2222 fun atof: Float is extern "atof"
2226 return to_s_with_length(cstring_length)
2229 # Returns `self` as a String of `length
`.
2230 fun to_s_with_length(length: Int): FlatString
2233 var str = new FlatString.with_infos(self, length, 0, length - 1)
2237 # Returns `self` as a new String.
2238 fun to_s_with_copy: FlatString
2240 var length = cstring_length
2241 var new_self = new NativeString(length + 1)
2242 copy_to(new_self, length, 0, 0)
2243 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2244 new_self[length] = '\0'
2245 str.real_items = new_self
2251 private var args_cache: nullable Sequence[String]
2253 # The arguments of the program as given by the OS
2254 fun program_args: Sequence[String]
2256 if _args_cache == null then init_args
2257 return _args_cache.as(not null)
2260 # The name of the program as given by the OS
2261 fun program_name: String
2263 return native_argv(0).to_s
2266 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2267 private fun init_args
2269 var argc = native_argc
2270 var args = new Array[String].with_capacity(0)
2273 args[i-1] = native_argv(i).to_s
2279 # First argument of the main C function.
2280 private fun native_argc: Int is intern
2282 # Second argument of the main C function.
2283 private fun native_argv(i: Int): NativeString is intern
2286 # Comparator that efficienlty use `to_s
` to compare things
2288 # The comparaison call `to_s
` on object and use the result to order things.
2290 # var a = [1, 2, 3, 10, 20]
2291 # (new CachedAlphaComparator).sort(a)
2292 # assert a == [1, 10, 2, 20, 3]
2294 # Internally the result of `to_s
` is cached in a HashMap to counter
2295 # uneficient implementation of `to_s
`.
2297 # Note: it caching is not usefull, see `alpha_comparator
`
2298 class CachedAlphaComparator
2300 redef type COMPARED: Object
2302 private var cache = new HashMap[Object, String]
2304 private fun do_to_s(a: Object): String do
2305 if cache.has_key(a) then return cache[a]
2311 redef fun compare(a, b) do
2312 return do_to_s(a) <=> do_to_s(b)
2316 # see `alpha_comparator
`
2317 private class AlphaComparator
2319 redef fun compare(a, b) do return a.to_s <=> b.to_s
2322 # Stateless comparator that naively use `to_s
` to compare things.
2324 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2325 # on a single instace. See `CachedAlphaComparator` as an alternative.
2327 # var a = [1, 2, 3, 10, 20]
2328 # alpha_comparator.sort(a)
2329 # assert a == [1, 10, 2, 20, 3]
2330 fun alpha_comparator: Comparator do return once new AlphaComparator
2332 # The arguments of the program as given by the OS
2333 fun args: Sequence[String]
2335 return sys.program_args