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 # `Char::is_whitespace` determines what is a whitespace.
356 var iter
= self.chars
.iterator
358 if not iter
.item
.is_whitespace
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 # `Char::is_whitespace` determines what is a whitespace.
372 var iter
= self.chars
.reverse_iterator
374 if not iter
.item
.is_whitespace
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
383 # assert " Hello World ! ".trim == "Hello World !"
384 # assert "\na\nb\tc\t".trim == "a\nb\tc"
386 # `Char::is_whitespace` determines what is a whitespace.
387 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
389 # Is the string non-empty but only made of whitespaces?
391 # assert " \n\t ".is_whitespace == true
392 # assert " hello ".is_whitespace == false
393 # assert "".is_whitespace == false
395 # `Char::is_whitespace` determines what is a whitespace.
396 fun is_whitespace
: Bool
398 if is_empty
then return false
399 for c
in self.chars
do
400 if not c
.is_whitespace
then return false
405 # Returns `self` removed from its last line terminator (if any).
407 # assert "Hello\n".chomp == "Hello"
408 # assert "Hello".chomp == "Hello"
410 # assert "\n".chomp == ""
411 # assert "".chomp == ""
413 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
414 # A single line terminator, the last one, is removed.
416 # assert "\r\n".chomp == ""
417 # assert "\r\n\n".chomp == "\r\n"
418 # assert "\r\n\r\n".chomp == "\r\n"
419 # assert "\r\n\r".chomp == "\r\n"
421 # Note: unlike with most IO methods like `Reader::read_line`,
422 # a single `\r` is considered here to be a line terminator and will be removed.
426 if len
== 0 then return self
427 var l
= self.chars
.last
429 return substring
(0, len-1
)
430 else if l
!= '\n' then
432 else if len
> 1 and self.chars
[len-2
] == '\r' then
433 return substring
(0, len-2
)
435 return substring
(0, len-1
)
439 # Justify a self in a space of `length`
441 # `left` is the space ratio on the left side.
442 # * 0.0 for left-justified (no space at the left)
443 # * 1.0 for right-justified (all spaces at the left)
444 # * 0.5 for centered (half the spaces at the left)
448 # assert "hello".justify(10, 0.0) == "hello "
449 # assert "hello".justify(10, 1.0) == " hello"
450 # assert "hello".justify(10, 0.5) == " hello "
452 # If `length` is not enough, `self` is returned as is.
454 # assert "hello".justify(2, 0.0) == "hello"
456 # REQUIRE: `left >= 0.0 and left <= 1.0`
457 # ENSURE: `self.length <= length implies result.length == length`
458 # ENSURE: `self.length >= length implies result == self`
459 fun justify
(length
: Int, left
: Float): String
461 var diff
= length
- self.length
462 if diff
<= 0 then return to_s
463 assert left
>= 0.0 and left
<= 1.0
464 var before
= (diff
.to_f
* left
).to_i
465 return " " * before
+ self + " " * (diff-before
)
468 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
470 # This method is injective (two different inputs never produce the same
471 # output) and the returned string always respect the following rules:
473 # * Contains only US-ASCII letters, digits and underscores.
474 # * Never starts with a digit.
475 # * Never ends with an underscore.
476 # * Never contains two contiguous underscores.
478 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
479 # assert "__".to_cmangle == "_95d_95d"
480 # assert "__d".to_cmangle == "_95d_d"
481 # assert "_d_".to_cmangle == "_d_95d"
482 # assert "_42".to_cmangle == "_95d42"
483 # assert "foo".to_cmangle == "foo"
484 # assert "".to_cmangle == ""
485 fun to_cmangle
: String
487 if is_empty
then return ""
488 var res
= new FlatBuffer
489 var underscore
= false
493 if c
>= '0' and c
<= '9' then
495 res
.append
(c
.ascii
.to_s
)
499 for i
in [start
..length
[ do
501 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
507 res
.append
('_'.ascii
.to_s
)
510 if c
>= '0' and c
<= '9' then
513 else if c
== '_' then
518 res
.append
(c
.ascii
.to_s
)
524 res
.append
('_'.ascii
.to_s
)
530 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
532 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
533 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
534 fun escape_to_c
: String
536 var b
= new FlatBuffer
537 for i
in [0..length
[ do
541 else if c
== '\0' then
543 else if c
== '"' then
545 else if c == '\'' then
547 else if c == '\\
' then
549 else if c.ascii < 32 then
550 b.append("\\{c.ascii.to_base(8, false)}")
558 # Escape additionnal characters
559 # The result might no be legal in C but be used in other languages
561 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
562 fun escape_more_to_c(chars: String): String
564 var b = new FlatBuffer
565 for c in escape_to_c.chars do
566 if chars.chars.has(c) then
574 # Escape to C plus braces
576 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
577 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
579 # Escape to POSIX Shell (sh).
581 # Abort if the text contains a null byte.
583 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
584 fun escape_to_sh
: String do
585 var b
= new FlatBuffer
587 for i in [0..length[ do
592 assert without_null_byte
: c
!= '\0'
600 # Escape to include in a Makefile
602 # Unfortunately, some characters are not escapable in Makefile.
603 # These characters are `;`, `|`, `\`, and the non-printable ones.
604 # They will be rendered as `"?{hex}"`.
605 fun escape_to_mk: String do
606 var b = new FlatBuffer
607 for i in [0..length[ do
611 else if c == ':' or c == ' ' or c == '#' then
614 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
615 b
.append
("?{c.ascii.to_base(16, false)}")
623 # Return a string where Nit escape sequences are transformed.
626 # assert s.length == 2
627 # var u = s.unescape_nit
628 # assert u.length == 1
629 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
630 fun unescape_nit
: String
632 var res
= new FlatBuffer.with_capacity
(self.length
)
633 var was_slash
= false
634 for i
in [0..length
[ do
636 if not was_slash
then
647 else if c
== 'r' then
649 else if c
== 't' then
651 else if c
== '0' then
660 # Encode `self` to percent (or URL) encoding
662 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
663 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
664 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
665 fun to_percent_encoding
: String
667 var buf
= new FlatBuffer
669 for i
in [0..length
[ do
671 if (c
>= '0' and c
<= '9') or
672 (c
>= 'a' and c
<= 'z') or
673 (c
>= 'A' and c
<= 'Z') or
674 c
== '-' or c
== '.' or
678 else buf
.append
"%{c.ascii.to_hex}"
684 # Decode `self` from percent (or URL) encoding to a clear string
686 # Replace invalid use of '%' with '?'.
688 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
689 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
690 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
691 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
692 # assert "incomplete %".from_percent_encoding == "incomplete ?"
693 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
694 fun from_percent_encoding
: String
696 var buf
= new FlatBuffer
702 if i
+ 2 >= length
then
703 # What follows % has been cut off
707 var hex_s
= substring
(i
, 2)
709 var hex_i
= hex_s
.to_hex
713 # What follows a % is not Hex
726 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
728 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
730 # 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>
731 fun html_escape
: String
733 var buf
= new FlatBuffer
735 for i
in [0..length
[ do
739 else if c
== '<' then
741 else if c
== '>' then
743 else if c
== '"' then
745 else if c
== '\'' then
747 else if c == '/' then
756 # Two pieces of text are equals if thez have the same characters in the same order.
758 # assert "hello" == "hello"
759 # assert "hello" != "HELLO"
760 # assert "hello" == "hel"+"lo"
762 # Things that are not Text are not equal.
765 # assert "9" != ['9']
768 # assert "9".chars.first == '9' # equality of Char
769 # assert "9".chars == ['9'] # equality of Sequence
770 # assert "9".to_i == 9 # equality of Int
773 if o == null then return false
774 if not o isa Text then return false
775 if self.is_same_instance(o) then return true
776 if self.length != o.length then return false
777 return self.chars == o.chars
780 # Lexicographical comparaison
782 # assert "abc" < "xy"
783 # assert "ABC" < "abc"
786 var self_chars = self.chars.iterator
787 var other_chars = other.chars.iterator
789 while self_chars.is_ok and other_chars.is_ok do
790 if self_chars.item < other_chars.item then return true
791 if self_chars.item > other_chars.item then return false
796 if self_chars.is_ok then
803 # Escape string used in labels for graphviz
805 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
806 fun escape_to_dot: String
808 return escape_more_to_c("|\{\}<>")
811 # Flat representation of self
812 fun flatten: FlatText is abstract
814 private var hash_cache: nullable Int = null
818 if hash_cache == null then
819 # djb2 hash algorithm
822 for i in [0..length[ do
824 h = h.lshift(5) + h + char.ascii
829 return hash_cache.as(not null)
834 # All kinds of array-based text representations.
835 abstract class FlatText
838 # Underlying C-String (`char*`)
840 # Warning : Might be void in some subclasses, be sure to check
841 # if set before using it.
842 private var items: NativeString is noinit
844 # Real items, used as cache for to_cstring is called
845 private var real_items: nullable NativeString = null
847 redef var length: Int = 0
858 redef fun flatten do return self
861 # Abstract class for the SequenceRead compatible
862 # views on String and Buffer objects
863 private abstract class StringCharView
864 super SequenceRead[Char]
870 redef fun is_empty do return target.is_empty
872 redef fun length do return target.length
874 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
876 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
879 # View on Buffer objects, extends Sequence
880 # for mutation operations
881 private abstract class BufferCharView
885 redef type SELFTYPE: Buffer
889 # A `String` holds and manipulates an arbitrary sequence of characters.
891 # String objects may be created using literals.
893 # assert "Hello World!" isa String
894 abstract class String
897 redef type SELFTYPE: String is fixed
899 redef fun to_s do return self
901 # Concatenates `o` to `self`
903 # assert "hello" + "world" == "helloworld"
904 # assert "" + "hello" + "" == "hello"
905 fun +(o: Text): SELFTYPE is abstract
907 # Concatenates self `i` times
909 # assert "abc" * 4 == "abcabcabcabc"
910 # assert "abc" * 1 == "abc"
911 # assert "abc" * 0 == ""
912 fun *(i: Int): SELFTYPE is abstract
914 # Insert `s` at `pos`.
916 # assert "helloworld".insert_at(" ", 5) == "hello world"
917 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
919 redef fun substrings: Iterator[String] is abstract
921 # Returns a reversed version of self
923 # assert "hello".reversed == "olleh"
924 # assert "bob".reversed == "bob"
925 # assert "".reversed == ""
926 fun reversed: SELFTYPE is abstract
928 # A upper case version of `self`
930 # assert "Hello World!".to_upper == "HELLO WORLD!"
931 fun to_upper: SELFTYPE is abstract
933 # A lower case version of `self`
935 # assert "Hello World!".to_lower == "hello world!"
936 fun to_lower : SELFTYPE is abstract
938 # Takes a camel case `self` and converts it to snake case
940 # assert "randomMethodId".to_snake_case == "random_method_id"
942 # If `self` is upper, it is returned unchanged
944 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
946 # If the identifier is prefixed by an underscore, the underscore is ignored
948 # assert "_privateField".to_snake_case == "_private_field"
949 fun to_snake_case: SELFTYPE
951 if self.is_upper then return self
953 var new_str = new FlatBuffer.with_capacity(self.length)
954 var is_first_char = true
956 for i in [0..length[ do
958 if is_first_char then
959 new_str.add(char.to_lower)
960 is_first_char = false
961 else if char.is_upper then
963 new_str.add(char.to_lower)
972 # Takes a snake case `self` and converts it to camel case
974 # assert "random_method_id".to_camel_case == "randomMethodId"
976 # If the identifier is prefixed by an underscore, the underscore is ignored
978 # assert "_private_field".to_camel_case == "_privateField"
980 # If `self` is upper, it is returned unchanged
982 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
984 # If there are several consecutive underscores, they are considered as a single one
986 # assert "random__method_id".to_camel_case == "randomMethodId"
987 fun to_camel_case: SELFTYPE
989 if self.is_upper then return self
991 var new_str = new FlatBuffer
992 var is_first_char = true
993 var follows_us = false
995 for i in [0..length[ do
997 if is_first_char then
999 is_first_char = false
1000 else if char == '_
' then
1002 else if follows_us then
1003 new_str.add(char.to_upper)
1013 # Returns a capitalized `self`
1015 # Letters that follow a letter are lowercased
1016 # Letters that follow a non-letter are upcased.
1018 # SEE : `Char::is_letter` for the definition of letter.
1020 # assert "jAVASCRIPT".capitalized == "Javascript"
1021 # assert "i am root".capitalized == "I Am Root"
1022 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1023 fun capitalized: SELFTYPE do
1024 if length == 0 then return self
1026 var buf = new FlatBuffer.with_capacity(length)
1028 var curr = chars[0].to_upper
1032 for i in [1 .. length[ do
1035 if prev.is_letter then
1036 buf[i] = curr.to_lower
1038 buf[i] = curr.to_upper
1046 private class FlatSubstringsIter
1047 super Iterator[FlatText]
1049 var tgt: nullable FlatText
1053 return tgt.as(not null)
1056 redef fun is_ok do return tgt != null
1058 redef fun next do tgt = null
1061 # Immutable strings of characters.
1066 # Index in _items of the start of the string
1067 private var index_from: Int is noinit
1069 # Indes in _items of the last item of the string
1070 private var index_to: Int is noinit
1072 redef var chars: SequenceRead[Char] = new FlatStringCharView(self) is lazy
1076 # Check that the index (+ index_from) is not larger than indexTo
1077 # In other terms, if the index is valid
1079 assert (index + index_from) <= index_to
1080 return items[index + index_from]
1083 ################################################
1084 # AbstractString specific methods #
1085 ################################################
1089 var native = new NativeString(self.length + 1)
1090 var length = self.length
1091 var items = self.items
1094 while pos < length do
1095 native[pos] = items[ipos]
1099 return native.to_s_with_length(self.length)
1102 redef fun substring(from, count)
1108 if count < 0 then count = 0
1112 var new_from = index_from + from
1114 if (new_from + count) > index_to then
1115 var new_len = index_to - new_from + 1
1116 if new_len <= 0 then return empty
1117 return new FlatString.with_infos(items, new_len, new_from, index_to)
1120 if count <= 0 then return empty
1122 var to = new_from + count - 1
1124 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1127 redef fun empty do return "".as(FlatString)
1131 var outstr = new NativeString(self.length + 1)
1134 var myitems = self.items
1135 var index_from = self.index_from
1136 var max = self.index_to
1138 while index_from <= max do
1139 outstr[out_index] = myitems[index_from].to_upper
1144 outstr[self.length] = '\
0'
1146 return outstr.to_s_with_length(self.length)
1151 var outstr = new NativeString(self.length + 1)
1154 var myitems = self.items
1155 var index_from = self.index_from
1156 var max = self.index_to
1158 while index_from <= max do
1159 outstr[out_index] = myitems[index_from].to_lower
1164 outstr[self.length] = '\
0'
1166 return outstr.to_s_with_length(self.length)
1171 var i = self.index_from
1172 var imax = self.index_to
1179 ##################################################
1180 # String Specific Methods #
1181 ##################################################
1183 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1191 redef fun to_cstring: NativeString
1193 if real_items != null then
1194 return real_items.as(not null)
1196 var newItems = new NativeString(length + 1)
1197 self.items.copy_to(newItems, length, index_from, 0)
1198 newItems[length] = '\
0'
1199 self.real_items = newItems
1206 if not other isa FlatString then return super
1208 if self.object_id == other.object_id then return true
1210 var my_length = length
1212 if other.length != my_length then return false
1214 var my_index = index_from
1215 var its_index = other.index_from
1217 var last_iteration = my_index + my_length
1219 var itsitems = other.items
1220 var myitems = self.items
1222 while my_index < last_iteration do
1223 if myitems[my_index] != itsitems[its_index] then return false
1233 if not other isa FlatString then return super
1235 if self.object_id == other.object_id then return false
1237 var my_curr_char : Char
1238 var its_curr_char : Char
1240 var curr_id_self = self.index_from
1241 var curr_id_other = other.index_from
1243 var my_items = self.items
1244 var its_items = other.items
1246 var my_length = self.length
1247 var its_length = other.length
1249 var max_iterations = curr_id_self + my_length
1251 while curr_id_self < max_iterations do
1252 my_curr_char = my_items[curr_id_self]
1253 its_curr_char = its_items[curr_id_other]
1255 if my_curr_char != its_curr_char then
1256 if my_curr_char < its_curr_char then return true
1264 return my_length < its_length
1269 var my_length = self.length
1270 var its_length = s.length
1272 var total_length = my_length + its_length
1274 var target_string = new NativeString(my_length + its_length + 1)
1276 self.items.copy_to(target_string, my_length, index_from, 0)
1277 if s isa FlatString then
1278 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1279 else if s isa FlatBuffer then
1280 s.items.copy_to(target_string, its_length, 0, my_length)
1282 var curr_pos = my_length
1283 for i in [0..s.length[ do
1285 target_string[curr_pos] = c
1290 target_string[total_length] = '\
0'
1292 return target_string.to_s_with_length(total_length)
1299 var my_length = self.length
1301 var final_length = my_length * i
1303 var my_items = self.items
1305 var target_string = new NativeString(final_length + 1)
1307 target_string[final_length] = '\
0'
1309 var current_last = 0
1311 for iteration in [1 .. i] do
1312 my_items.copy_to(target_string, my_length, 0, current_last)
1313 current_last += my_length
1316 return target_string.to_s_with_length(final_length)
1321 if hash_cache == null then
1322 # djb2 hash algorithm
1328 while i <= index_to do
1329 h = h.lshift(5) + h + myitems[i].ascii
1336 return hash_cache.as(not null)
1339 redef fun substrings do return new FlatSubstringsIter(self)
1342 private class FlatStringReverseIterator
1343 super IndexedIterator[Char]
1345 var target: FlatString
1347 var target_items: NativeString
1351 init with_pos(tgt: FlatString, pos: Int)
1354 target_items = tgt.items
1355 curr_pos = pos + tgt.index_from
1358 redef fun is_ok do return curr_pos >= target.index_from
1360 redef fun item do return target_items[curr_pos]
1362 redef fun next do curr_pos -= 1
1364 redef fun index do return curr_pos - target.index_from
1368 private class FlatStringIterator
1369 super IndexedIterator[Char]
1371 var target: FlatString
1373 var target_items: NativeString
1377 init with_pos(tgt: FlatString, pos: Int)
1380 target_items = tgt.items
1381 curr_pos = pos + target.index_from
1384 redef fun is_ok do return curr_pos <= target.index_to
1386 redef fun item do return target_items[curr_pos]
1388 redef fun next do curr_pos += 1
1390 redef fun index do return curr_pos - target.index_from
1394 private class FlatStringCharView
1395 super StringCharView
1397 redef type SELFTYPE: FlatString
1401 # Check that the index (+ index_from) is not larger than indexTo
1402 # In other terms, if the index is valid
1404 var target = self.target
1405 assert (index + target.index_from) <= target.index_to
1406 return target.items[index + target.index_from]
1409 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1411 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1415 # A mutable sequence of characters.
1416 abstract class Buffer
1419 redef type SELFTYPE: Buffer is fixed
1421 # Specific implementations MUST set this to `true` in order to invalidate caches
1422 protected var is_dirty = true
1424 # Copy-On-Write flag
1426 # If the `Buffer` was to_s'd
, the next in-place altering
1427 # operation will cause the current `Buffer` to be re-allocated.
1429 # The flag will then be set at `false`.
1430 protected var written
= false
1432 # Modifies the char contained at pos `index`
1434 # DEPRECATED : Use self.chars.[]= instead
1435 fun []=(index
: Int, item
: Char) is abstract
1437 # Adds a char `c` at the end of self
1439 # DEPRECATED : Use self.chars.add instead
1440 fun add
(c
: Char) is abstract
1444 # var b = new FlatBuffer
1446 # assert not b.is_empty
1449 fun clear
is abstract
1451 # Enlarges the subsequent array containing the chars of self
1452 fun enlarge
(cap
: Int) is abstract
1454 # Adds the content of text `s` at the end of self
1456 # var b = new FlatBuffer
1459 # assert b == "helloworld"
1460 fun append
(s
: Text) is abstract
1462 # `self` is appended in such a way that `self` is repeated `r` times
1464 # var b = new FlatBuffer
1467 # assert b == "hellohellohello"
1468 fun times
(r
: Int) is abstract
1470 # Reverses itself in-place
1472 # var b = new FlatBuffer
1475 # assert b == "olleh"
1476 fun reverse
is abstract
1478 # Changes each lower-case char in `self` by its upper-case variant
1480 # var b = new FlatBuffer
1481 # b.append("Hello World!")
1483 # assert b == "HELLO WORLD!"
1484 fun upper
is abstract
1486 # Changes each upper-case char in `self` by its lower-case variant
1488 # var b = new FlatBuffer
1489 # b.append("Hello World!")
1491 # assert b == "hello world!"
1492 fun lower
is abstract
1494 # Capitalizes each word in `self`
1496 # Letters that follow a letter are lowercased
1497 # Letters that follow a non-letter are upcased.
1499 # SEE: `Char::is_letter` for the definition of a letter.
1501 # var b = new FlatBuffer.from("jAVAsCriPt")
1503 # assert b == "Javascript"
1504 # b = new FlatBuffer.from("i am root")
1506 # assert b == "I Am Root"
1507 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1509 # assert b == "Ab_C -Ab0C Ab\nC"
1511 if length
== 0 then return
1512 var c
= self[0].to_upper
1515 for i
in [1 .. length
[ do
1518 if prev
.is_letter
then
1519 self[i
] = c
.to_lower
1521 self[i
] = c
.to_upper
1528 if is_dirty
then hash_cache
= null
1532 # In Buffers, the internal sequence of character is mutable
1533 # Thus, `chars` can be used to modify the buffer.
1534 redef fun chars
: Sequence[Char] is abstract
1537 # Mutable strings of characters.
1542 redef var chars
: Sequence[Char] = new FlatBufferCharView(self) is lazy
1544 private var capacity
: Int = 0
1546 redef fun substrings
do return new FlatSubstringsIter(self)
1548 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1550 # This happens when an operation modifies the current `Buffer` and
1551 # the Copy-On-Write flag `written` is set at true.
1552 private fun reset
do
1553 var nns
= new NativeString(capacity
)
1554 items
.copy_to
(nns
, length
, 0, 0)
1562 assert index
< length
1566 redef fun []=(index
, item
)
1569 if index
== length
then
1573 if written
then reset
1574 assert index
>= 0 and index
< length
1581 if capacity
<= length
then enlarge
(length
+ 5)
1588 if written
then reset
1592 redef fun empty
do return new FlatBuffer
1594 redef fun enlarge
(cap
)
1597 if cap
<= c
then return
1598 while c
<= cap
do c
= c
* 2 + 2
1599 # The COW flag can be set at false here, since
1600 # it does a copy of the current `Buffer`
1602 var a
= new NativeString(c
+1)
1603 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1608 redef fun to_s
: String
1611 if length
== 0 then items
= new NativeString(1)
1612 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1615 redef fun to_cstring
1618 var new_native
= new NativeString(length
+ 1)
1619 new_native
[length
] = '\0'
1620 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1621 real_items
= new_native
1624 return real_items
.as(not null)
1627 # Create a new empty string.
1630 # Create a new string copied from `s`.
1633 capacity
= s
.length
+ 1
1635 items
= new NativeString(capacity
)
1636 if s
isa FlatString then
1637 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1638 else if s
isa FlatBuffer then
1639 s
.items
.copy_to
(items
, length
, 0, 0)
1642 for i
in [0..s
.length
[ do
1650 # Create a new empty string with a given capacity.
1651 init with_capacity
(cap
: Int)
1654 # _items = new NativeString.calloc(cap)
1655 items
= new NativeString(cap
+1)
1662 if s
.is_empty
then return
1665 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1666 if s
isa FlatString then
1667 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1668 else if s
isa FlatBuffer then
1669 s
.items
.copy_to
(items
, sl
, 0, length
)
1671 var curr_pos
= self.length
1672 for i
in [0..s
.length
[ do
1681 # Copies the content of self in `dest`
1682 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1684 var self_chars
= self.chars
1685 var dest_chars
= dest
.chars
1686 for i
in [0..len-1
] do
1687 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1691 redef fun substring
(from
, count
)
1695 if from
< 0 then from
= 0
1696 if count
> length
then count
= length
1697 if from
< count
then
1698 var r
= new FlatBuffer.with_capacity
(count
- from
)
1699 while from
< count
do
1700 r
.chars
.push
(items
[from
])
1705 return new FlatBuffer
1712 var ns
= new NativeString(capacity
)
1724 redef fun times
(repeats
)
1726 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1727 for i
in [1..repeats
[ do
1734 if written
then reset
1738 it
[id
] = it
[id
].to_upper
1745 if written
then reset
1749 it
[id
] = it
[id
].to_lower
1755 private class FlatBufferReverseIterator
1756 super IndexedIterator[Char]
1758 var target
: FlatBuffer
1760 var target_items
: NativeString
1764 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1767 if tgt
.length
> 0 then target_items
= tgt
.items
1771 redef fun index
do return curr_pos
1773 redef fun is_ok
do return curr_pos
>= 0
1775 redef fun item
do return target_items
[curr_pos
]
1777 redef fun next
do curr_pos
-= 1
1781 private class FlatBufferCharView
1782 super BufferCharView
1784 redef type SELFTYPE: FlatBuffer
1786 redef fun [](index
) do return target
.items
[index
]
1788 redef fun []=(index
, item
)
1790 assert index
>= 0 and index
<= length
1791 if index
== length
then
1795 target
.items
[index
] = item
1808 fun enlarge
(cap
: Int)
1815 var s_length
= s
.length
1816 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1819 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1821 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1825 private class FlatBufferIterator
1826 super IndexedIterator[Char]
1828 var target
: FlatBuffer
1830 var target_items
: NativeString
1834 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1837 if tgt
.length
> 0 then target_items
= tgt
.items
1841 redef fun index
do return curr_pos
1843 redef fun is_ok
do return curr_pos
< target
.length
1845 redef fun item
do return target_items
[curr_pos
]
1847 redef fun next
do curr_pos
+= 1
1851 ###############################################################################
1853 ###############################################################################
1856 # User readable representation of `self`.
1857 fun to_s
: String do return inspect
1859 # The class name of the object in NativeString format.
1860 private fun native_class_name
: NativeString is intern
1862 # The class name of the object.
1864 # assert 5.class_name == "Int"
1865 fun class_name
: String do return native_class_name
.to_s
1867 # Developer readable representation of `self`.
1868 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1871 return "<{inspect_head}>"
1874 # Return "CLASSNAME:#OBJECTID".
1875 # This function is mainly used with the redefinition of the inspect method
1876 protected fun inspect_head
: String
1878 return "{class_name}:#{object_id.to_hex}"
1883 # assert true.to_s == "true"
1884 # assert false.to_s == "false"
1897 # Wrapper of strerror C function
1898 private fun strerror_ext
: NativeString is extern `{
1899 return strerror(recv);
1902 # Returns a string describing error number
1903 fun strerror
: String do return strerror_ext
.to_s
1905 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1906 # assume < to_c max const of char
1907 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1914 else if self == 0 then
1921 var pos
= digit_count
(base
) - 1
1922 while pos
>= 0 and n
> 0 do
1923 s
.chars
[pos
] = (n
% base
).to_c
1929 # C function to calculate the length of the `NativeString` to receive `self`
1930 private fun int_to_s_len
: Int is extern "native_int_length_str"
1932 # C function to convert an nit Int to a NativeString (char*)
1933 private fun native_int_to_s
(nstr
: NativeString, strlen
: Int) is extern "native_int_to_s"
1935 # return displayable int in base 10 and signed
1937 # assert 1.to_s == "1"
1938 # assert (-123).to_s == "-123"
1940 var nslen
= int_to_s_len
1941 var ns
= new NativeString(nslen
+ 1)
1943 native_int_to_s
(ns
, nslen
+ 1)
1944 return ns
.to_s_with_length
(nslen
)
1947 # return displayable int in hexadecimal
1949 # assert 1.to_hex == "1"
1950 # assert (-255).to_hex == "-ff"
1951 fun to_hex
: String do return to_base
(16,false)
1953 # return displayable int in base base and signed
1954 fun to_base
(base
: Int, signed
: Bool): String
1956 var l
= digit_count
(base
)
1957 var s
= new FlatBuffer.from
(" " * l
)
1958 fill_buffer
(s
, base
, signed
)
1964 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1966 # assert 12.34.to_s == "12.34"
1967 # assert (-0120.030).to_s == "-120.03"
1969 # see `to_precision` for a custom precision.
1971 var str
= to_precision
( 3 )
1972 if is_inf
!= 0 or is_nan
then return str
1973 var len
= str
.length
1974 for i
in [0..len-1
] do
1976 var c
= str
.chars
[j
]
1979 else if c
== '.' then
1980 return str
.substring
( 0, j
+2 )
1982 return str
.substring
( 0, j
+1 )
1988 # `String` representation of `self` with the given number of `decimals`
1990 # assert 12.345.to_precision(0) == "12"
1991 # assert 12.345.to_precision(3) == "12.345"
1992 # assert (-12.345).to_precision(3) == "-12.345"
1993 # assert (-0.123).to_precision(3) == "-0.123"
1994 # assert 0.999.to_precision(2) == "1.00"
1995 # assert 0.999.to_precision(4) == "0.9990"
1996 fun to_precision
(decimals
: Int): String
1998 if is_nan
then return "nan"
2000 var isinf
= self.is_inf
2003 else if isinf
== -1 then
2007 if decimals
== 0 then return self.to_i
.to_s
2009 for i
in [0..decimals
[ do f
= f
* 10.0
2016 if i
== 0 then return "0." + "0"*decimals
2018 # Prepare both parts of the float, before and after the "."
2023 if sl
> decimals
then
2024 # Has something before the "."
2025 p1
= s
.substring
(0, sl-decimals
)
2026 p2
= s
.substring
(sl-decimals
, decimals
)
2029 p2
= "0"*(decimals-sl
) + s
2032 if i
< 0 then p1
= "-" + p1
2034 return p1
+ "." + p2
2039 # assert 'x'.to_s == "x"
2042 var s
= new FlatBuffer.with_capacity
(1)
2047 # Returns true if the char is a numerical digit
2049 # assert '0'.is_numeric
2050 # assert '9'.is_numeric
2051 # assert not 'a'.is_numeric
2052 # assert not '?'.is_numeric
2053 fun is_numeric
: Bool
2055 return self >= '0' and self <= '9'
2058 # Returns true if the char is an alpha digit
2060 # assert 'a'.is_alpha
2061 # assert 'Z'.is_alpha
2062 # assert not '0'.is_alpha
2063 # assert not '?'.is_alpha
2066 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2069 # Returns true if the char is an alpha or a numeric digit
2071 # assert 'a'.is_alphanumeric
2072 # assert 'Z'.is_alphanumeric
2073 # assert '0'.is_alphanumeric
2074 # assert '9'.is_alphanumeric
2075 # assert not '?'.is_alphanumeric
2076 fun is_alphanumeric
: Bool
2078 return self.is_numeric
or self.is_alpha
2082 redef class Collection[E
]
2083 # Concatenate elements.
2086 var s
= new FlatBuffer
2087 for e
in self do if e
!= null then s
.append
(e
.to_s
)
2091 # Concatenate and separate each elements with `sep`.
2093 # assert [1, 2, 3].join(":") == "1:2:3"
2094 # assert [1..3].join(":") == "1:2:3"
2095 fun join
(sep
: Text): String
2097 if is_empty
then return ""
2099 var s
= new FlatBuffer # Result
2104 if e
!= null then s
.append
(e
.to_s
)
2106 # Concat other items
2111 if e
!= null then s
.append
(e
.to_s
)
2118 redef class Array[E
]
2120 # Fast implementation
2124 if l
== 0 then return ""
2125 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
2127 var na
= new NativeArray[String](l
)
2133 if itsi
== null then
2143 var ns
= new NativeString(sl
+ 1)
2149 var tpl
= tmp
.length
2150 if tmp
isa FlatString then
2151 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2154 for j
in tmp
.substrings
do
2155 var s
= j
.as(FlatString)
2157 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2163 return ns
.to_s_with_length
(sl
)
2167 redef class Map[K
,V
]
2168 # Concatenate couple of 'key value'.
2169 # key and value are separated by `couple_sep`.
2170 # each couple is separated each couple with `sep`.
2172 # var m = new ArrayMap[Int, String]
2175 # assert m.join("; ", "=") == "1=one; 10=ten"
2176 fun join
(sep
: String, couple_sep
: String): String
2178 if is_empty
then return ""
2180 var s
= new FlatBuffer # Result
2186 s
.append
("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2188 # Concat other items
2194 s
.append
("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2201 ###############################################################################
2203 ###############################################################################
2205 # Native strings are simple C char *
2206 extern class NativeString `{ char* `}
2207 # Creates a new NativeString with a capacity of `length
`
2208 new(length: Int) is intern
2210 # Get char at `index
`.
2211 fun [](index: Int): Char is intern
2213 # Set char `item
` at index.
2214 fun []=(index: Int, item: Char) is intern
2216 # Copy `self` to `dest
`.
2217 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2219 # Position of the first nul character.
2220 fun cstring_length: Int
2223 while self[l] != '\0' do l += 1
2227 # Parse `self` as an Int.
2228 fun atoi: Int is intern
2230 # Parse `self` as a Float.
2231 fun atof: Float is extern "atof"
2235 return to_s_with_length(cstring_length)
2238 # Returns `self` as a String of `length
`.
2239 fun to_s_with_length(length: Int): FlatString
2242 var str = new FlatString.with_infos(self, length, 0, length - 1)
2246 # Returns `self` as a new String.
2247 fun to_s_with_copy: FlatString
2249 var length = cstring_length
2250 var new_self = new NativeString(length + 1)
2251 copy_to(new_self, length, 0, 0)
2252 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2253 new_self[length] = '\0'
2254 str.real_items = new_self
2260 private var args_cache: nullable Sequence[String]
2262 # The arguments of the program as given by the OS
2263 fun program_args: Sequence[String]
2265 if _args_cache == null then init_args
2266 return _args_cache.as(not null)
2269 # The name of the program as given by the OS
2270 fun program_name: String
2272 return native_argv(0).to_s
2275 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2276 private fun init_args
2278 var argc = native_argc
2279 var args = new Array[String].with_capacity(0)
2282 args[i-1] = native_argv(i).to_s
2288 # First argument of the main C function.
2289 private fun native_argc: Int is intern
2291 # Second argument of the main C function.
2292 private fun native_argv(i: Int): NativeString is intern
2295 # Comparator that efficienlty use `to_s
` to compare things
2297 # The comparaison call `to_s
` on object and use the result to order things.
2299 # var a = [1, 2, 3, 10, 20]
2300 # (new CachedAlphaComparator).sort(a)
2301 # assert a == [1, 10, 2, 20, 3]
2303 # Internally the result of `to_s
` is cached in a HashMap to counter
2304 # uneficient implementation of `to_s
`.
2306 # Note: it caching is not usefull, see `alpha_comparator
`
2307 class CachedAlphaComparator
2309 redef type COMPARED: Object
2311 private var cache = new HashMap[Object, String]
2313 private fun do_to_s(a: Object): String do
2314 if cache.has_key(a) then return cache[a]
2320 redef fun compare(a, b) do
2321 return do_to_s(a) <=> do_to_s(b)
2325 # see `alpha_comparator
`
2326 private class AlphaComparator
2328 redef fun compare(a, b) do return a.to_s <=> b.to_s
2331 # Stateless comparator that naively use `to_s
` to compare things.
2333 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2334 # on a single instace. See `CachedAlphaComparator` as an alternative.
2336 # var a = [1, 2, 3, 10, 20]
2337 # alpha_comparator.sort(a)
2338 # assert a == [1, 10, 2, 20, 3]
2339 fun alpha_comparator: Comparator do return once new AlphaComparator
2341 # The arguments of the program as given by the OS
2342 fun args: Sequence[String]
2344 return sys.program_args