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
18 intrude import collection
# FIXME should be collection::array
24 ###############################################################################
26 ###############################################################################
28 # Common subclass for String and Buffer
29 abstract class AbstractString
30 super AbstractArrayRead[Char]
32 readable private var _items
: NativeString
34 fun chars
: StringCharView is abstract
36 # Access a character at `index` in the string.
38 # assert "abcd"[2] == 'c'
39 redef fun [](index
) do return _items
[index
]
43 # assert "abcd".substring(1, 2) == "bc"
44 # assert "abcd".substring(-1, 2) == "a"
45 # assert "abcd".substring(1, 0) == ""
46 # assert "abcd".substring(2, 5) == "cd"
48 # A `from` index < 0 will be replaced by 0.
49 # Unless a `count` value is > 0 at the same time.
50 # In this case, `from += count` and `count -= from`.
51 fun substring
(from
: Int, count
: Int): String
55 if from
< 0 then from
= 0
56 if count
> length
then count
= length
58 var r
= new Buffer.with_capacity
(count
- from
)
60 r
.chars
.push
(_items
[from
])
69 # Create a substring from `self` beginning at the `from` position
71 # assert "abcd".substring_from(1) == "bcd"
72 # assert "abcd".substring_from(-1) == "abcd"
73 # assert "abcd".substring_from(2) == "cd"
75 # As with substring, a `from` index < 0 will be replaced by 0
76 fun substring_from
(from
: Int): String
79 return substring
(from
, length
- from
)
82 # Does self have a substring `str` starting from position `pos`?
84 # assert "abcd".has_substring("bc",1) == true
85 # assert "abcd".has_substring("bc",2) == false
86 fun has_substring
(str
: String, pos
: Int): Bool
88 var itsindex
= str
.length
- 1
89 var myindex
= pos
+ itsindex
91 var itsitems
= str
._items
92 if myindex
> length
or itsindex
> myindex
then return false
93 var its_index_from
= str
._index_from
94 itsindex
+= its_index_from
95 while itsindex
>= its_index_from
do
96 if myitems
[myindex
] != itsitems
[itsindex
] then return false
103 # Is this string prefixed by `prefix`?
105 # assert "abcd".has_prefix("ab") == true
106 # assert "abcbc".has_prefix("bc") == false
107 # assert "ab".has_prefix("abcd") == false
108 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
110 # Is this string suffixed by `suffix`?
112 # assert "abcd".has_suffix("abc") == false
113 # assert "abcd".has_suffix("bcd") == true
114 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
116 # If `self` contains only digits, return the corresponding integer
118 # assert "123".to_i == 123
119 # assert "-1".to_i == -1
123 return to_s
.to_cstring
.atoi
126 # If `self` contains a float, return the corresponding float
128 # assert "123".to_f == 123.0
129 # assert "-1".to_f == -1.0
130 # assert "-1.2e-3".to_f == -0.0012
134 return to_s
.to_cstring
.atof
137 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
138 fun to_hex
: Int do return a_to
(16)
140 # If `self` contains only digits and letters, return the corresponding integer in a given base
142 # assert "120".a_to(3) == 15
143 fun a_to
(base
: Int) : Int
170 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
172 # assert "123".is_numeric == true
173 # assert "1.2".is_numeric == true
174 # assert "1,2".is_numeric == true
175 # assert "1..2".is_numeric == false
178 var has_point_or_comma
= false
183 if (i
== '.' or i
== ',') and not has_point_or_comma
185 has_point_or_comma
= true
194 # A upper case version of `self`
196 # assert "Hello World!".to_upper == "HELLO WORLD!"
199 var s
= new Buffer.with_capacity
(length
)
200 for i
in self.chars
do s
.add
(i
.to_upper
)
204 # A lower case version of `self`
206 # assert "Hello World!".to_lower == "hello world!"
207 fun to_lower
: String
209 var s
= new Buffer.with_capacity
(length
)
210 for i
in self.chars
do s
.add
(i
.to_lower
)
214 # Trims trailing and preceding white spaces
215 # A whitespace is defined as any character which ascii value is less than or equal to 32
217 # assert " Hello World ! ".trim == "Hello World !"
218 # assert "\na\nb\tc\t".trim == "a\nb\tc"
221 if self.length
== 0 then return self.to_s
222 # find position of the first non white space char (ascii < 32) from the start of the string
224 while self.chars
[start_pos
].ascii
<= 32 do
226 if start_pos
== length
then return ""
228 # find position of the first non white space char from the end of the string
229 var end_pos
= length
- 1
230 while self.chars
[end_pos
].ascii
<= 32 do
232 if end_pos
== start_pos
then return self.chars
[start_pos
].to_s
234 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
246 # Mangle a string to be a unique string only made of alphanumeric characters
247 fun to_cmangle
: String
250 var underscore
= false
251 for c
in self.chars
do
252 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
258 res
.append
('_'.ascii
.to_s
)
261 if c
>= '0' and c
<= '9' then
264 else if c
== '_' then
269 res
.append
(c
.ascii
.to_s
)
277 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
279 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
280 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
281 fun escape_to_c
: String
284 for c
in self.chars
do
287 else if c
== '\0' then
289 else if c
== '"' then
291 else if c == '\'' then
293 else if c == '\\
' then
295 else if c.ascii < 32 then
296 b.append("\\{c.ascii.to_base(8, false)}")
304 # Escape additionnal characters
305 # The result might no be legal in C but be used in other languages
307 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
308 fun escape_more_to_c(chars: String): String
311 for c in escape_to_c do
320 # Escape to c plus braces
322 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
323 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
325 # Return a string where Nit escape sequences are transformed.
329 # assert s.length == 2
330 # var u = s.unescape_nit
331 # assert u.length == 1
332 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
333 fun unescape_nit
: String
335 var res
= new Buffer.with_capacity
(self.length
)
336 var was_slash
= false
338 if not was_slash
then
349 else if c
== 'r' then
351 else if c
== 't' then
353 else if c
== '0' then
363 # Abstract class for the SequenceRead compatible
364 # views on String and Buffer objects
365 abstract class StringCharView
366 super SequenceRead[Char]
368 type SELFTYPE: AbstractString
370 private var target
: SELFTYPE
372 private init(tgt
: SELFTYPE)
377 redef fun is_empty
do return target
.is_empty
379 redef fun length
do return target
.length
381 redef fun has
(c
: Char): Bool
384 if i
== c
then return true
391 # View on Buffer objects, extends Sequence
392 # for mutation operations
393 abstract class BufferCharView
397 redef type SELFTYPE: Buffer
401 # Immutable strings of characters.
407 redef type OTHER: String
409 # Index in _items of the start of the string
410 readable var _index_from
: Int
412 # Indes in _items of the last item of the string
413 readable var _index_to
: Int
415 redef var chars
: StringCharView = new FlatStringCharView(self)
417 ################################################
418 # AbstractString specific methods #
419 ################################################
421 redef fun [](index
) do
423 # Check that the index (+ index_from) is not larger than indexTo
424 # In other terms, if the index is valid
425 assert (index
+ _index_from
) <= _index_to
426 return _items
[index
+ _index_from
]
429 redef fun substring
(from
: Int, count
: Int): String
435 if count
< 0 then count
= 0
439 var realFrom
= _index_from
+ from
441 if (realFrom
+ count
) > _index_to
then return new String.with_infos
(_items
, _index_to
- realFrom
+ 1, realFrom
, _index_to
)
443 if count
== 0 then return ""
445 var to
= realFrom
+ count
- 1
447 return new String.with_infos
(_items
, to
- realFrom
+ 1, realFrom
, to
)
450 redef fun substring_from
(from
: Int): String
452 if from
> _length
then return ""
453 if from
< 0 then from
= 0
454 return substring
(from
, _length
)
457 redef fun has_substring
(str
: String, pos
: Int): Bool
459 var itsindex
= str
._length
- 1
461 var myindex
= pos
+ itsindex
464 var itsitems
= str
._items
466 if myindex
> _length
or itsindex
> myindex
then return false
468 var itsindexfrom
= str
.index_from
469 itsindex
+= itsindexfrom
470 myindex
+= index_from
472 while itsindex
>= itsindexfrom
do
473 if myitems
[myindex
] != itsitems
[itsindex
] then return false
481 redef fun to_upper
: String
483 var outstr
= calloc_string
(self._length
+ 1)
486 var myitems
= self._items
487 var index_from
= self._index_from
488 var max
= self._index_to
490 while index_from
<= max
do
491 outstr
[out_index
] = myitems
[index_from
].to_upper
496 outstr
[self.length
] = '\0'
498 return outstr
.to_s_with_length
(self._length
)
501 redef fun to_lower
: String
503 var outstr
= calloc_string
(self._length
+ 1)
506 var myitems
= self._items
507 var index_from
= self._index_from
508 var max
= self._index_to
510 while index_from
<= max
do
511 outstr
[out_index
] = myitems
[index_from
].to_lower
516 outstr
[self.length
] = '\0'
518 return outstr
.to_s_with_length
(self._length
)
521 redef fun trim
: String
523 if self._length
== 0 then return self
524 # find position of the first non white space char (ascii < 32) from the start of the string
525 var start_pos
= self._index_from
526 while _items
[start_pos
].ascii
<= 32 do
528 if start_pos
== _index_to
+ 1 then return ""
530 # find position of the first non white space char from the end of the string
531 var end_pos
= _index_to
532 while _items
[end_pos
].ascii
<= 32 do
534 if end_pos
== start_pos
then return _items
[start_pos
].to_s
536 start_pos
-= index_from
537 end_pos
-= index_from
538 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
543 var i
= self._index_from
544 var imax
= self._index_to
551 ##################################################
552 # String Specific Methods #
553 ##################################################
555 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
563 # Return a null terminated char *
564 fun to_cstring
: NativeString
566 if _index_from
> 0 or _index_to
!= items
.cstring_length
- 1 then
567 var newItems
= calloc_string
(_length
+ 1)
568 self.items
.copy_to
(newItems
, _length
, _index_from
, 0)
569 newItems
[length
] = '\0'
577 if not other
isa String then return false
579 if self.object_id
== other
.object_id
then return true
581 var my_length
= _length
583 if other
._length
!= my_length
then return false
585 var my_index
= _index_from
586 var its_index
= other
._index_from
588 var last_iteration
= my_index
+ my_length
590 var itsitems
= other
._items
591 var myitems
= self._items
593 while my_index
< last_iteration
do
594 if myitems
[my_index
] != itsitems
[its_index
] then return false
602 # The comparison between two strings is done on a lexicographical basis
604 # assert ("aa" < "b") == true
607 if self.object_id
== other
.object_id
then return false
609 var my_curr_char
: Char
610 var its_curr_char
: Char
612 var curr_id_self
= self._index_from
613 var curr_id_other
= other
._index_from
615 var my_items
= self._items
616 var its_items
= other
._items
618 var my_length
= self._length
619 var its_length
= other
._length
621 var max_iterations
= curr_id_self
+ my_length
623 while curr_id_self
< max_iterations
do
624 my_curr_char
= my_items
[curr_id_self
]
625 its_curr_char
= its_items
[curr_id_other
]
627 if my_curr_char
!= its_curr_char
then
628 if my_curr_char
< its_curr_char
then return true
636 return my_length
< its_length
639 # The concatenation of `self` with `s`
641 # assert "hello " + "world!" == "hello world!"
642 fun +(s
: String): String
644 var my_length
= self._length
645 var its_length
= s
._length
647 var total_length
= my_length
+ its_length
649 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
651 self._items
.copy_to
(target_string
, my_length
, _index_from
, 0)
652 s
._items
.copy_to
(target_string
, its_length
, s
._index_from
, my_length
)
654 target_string
[total_length
] = '\0'
656 return target_string
.to_s_with_length
(total_length
)
659 # `i` repetitions of `self`
661 # assert "abc"*3 == "abcabcabc"
662 # assert "abc"*1 == "abc"
663 # assert "abc"*0 == ""
664 fun *(i
: Int): String
668 var my_length
= self._length
670 var final_length
= my_length
* i
672 var my_items
= self._items
674 var target_string
= calloc_string
((final_length
) + 1)
676 target_string
[final_length
] = '\0'
680 for iteration
in [1 .. i
] do
681 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
682 current_last
+= my_length
685 return target_string
.to_s_with_length
(final_length
)
688 redef fun to_s
do return self
692 # djb2 hash algorythm
697 var strStart
= _index_from
701 while i
>= strStart
do
702 h
= (h
* 32) + h
+ self._items
[i
].ascii
710 private class FlatStringIterator
711 super IndexedIterator[Char]
715 var target_items
: NativeString
719 init with_pos
(tgt
: String, pos
: Int)
722 target_items
= tgt
.items
723 curr_pos
= pos
+ target
.index_from
726 redef fun is_ok
do return curr_pos
<= target
.index_to
728 redef fun item
do return target_items
[curr_pos
]
730 redef fun next
do curr_pos
+= 1
732 redef fun index
do return curr_pos
- target
.index_from
736 private class FlatStringCharView
739 redef type SELFTYPE: String
743 # Check that the index (+ index_from) is not larger than indexTo
744 # In other terms, if the index is valid
746 assert (index
+ target
._index_from
) <= target
._index_to
747 return target
._items
[index
+ target
._index_from
]
750 redef fun iterator
: IndexedIterator[Char] do return new FlatStringIterator.with_pos
(target
, 0)
754 # Mutable strings of characters.
759 super AbstractArray[Char]
761 redef type OTHER: String
763 redef var chars
: BufferCharView = new FlatBufferCharView(self)
765 redef fun []=(index
, item
)
767 if index
== length
then
771 assert index
>= 0 and index
< length
777 if _capacity
<= length
then enlarge
(length
+ 5)
782 redef fun enlarge
(cap
)
785 if cap
<= c
then return
786 while c
<= cap
do c
= c
* 2 + 2
787 var a
= calloc_string
(c
+1)
788 _items
.copy_to
(a
, length
, 0, 0)
797 if _capacity
< _length
+ sl
then enlarge
(_length
+ sl
)
798 s
.items
.copy_to
(_items
, sl
, s
._index_from
, _length
)
805 redef fun to_s
: String
808 var a
= calloc_string
(l
+1)
809 _items
.copy_to
(a
, l
, 0, 0)
811 # Ensure the afterlast byte is '\0' to nul-terminated char *
814 return a
.to_s_with_length
(length
)
822 while i
< l1
and i
< l2
do
823 var c1
= self.chars
[i
].ascii
824 var c2
= s
.chars
[i
].ascii
839 # Create a new empty string.
847 _capacity
= s
.length
+ 1
849 _items
= calloc_string
(_capacity
)
850 s
.items
.copy_to
(_items
, _length
, s
._index_from
, 0)
853 # Create a new empty string with a given capacity.
854 init with_capacity
(cap
: Int)
857 # _items = new NativeString.calloc(cap)
858 _items
= calloc_string
(cap
+1)
865 if not o
isa Buffer then return false
867 if o
.length
!= l
then return false
872 if it
[i
] != oit
[i
] then return false
878 readable private var _capacity
: Int
881 private class FlatBufferCharView
885 redef type SELFTYPE: Buffer
887 redef fun [](index
) do return target
._items
[index
]
889 redef fun []=(index
, item
)
891 assert index
>= 0 and index
<= length
892 if index
== length
then
896 target
._items
[index
] = item
909 fun enlarge
(cap
: Int)
916 var my_items
= target
.items
917 var s_length
= s
.length
918 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
921 redef fun iterator
: IndexedIterator[Char] do return new FlatBufferIterator.with_pos
(target
, 0)
925 private class FlatBufferIterator
926 super IndexedIterator[Char]
930 var target_items
: NativeString
934 init with_pos
(tgt
: Buffer, pos
: Int)
937 target_items
= tgt
.items
941 redef fun index
do return curr_pos
943 redef fun is_ok
do return curr_pos
< target
.length
945 redef fun item
do return target_items
[curr_pos
]
947 redef fun next
do curr_pos
+= 1
951 ###############################################################################
953 ###############################################################################
956 # User readable representation of `self`.
957 fun to_s
: String do return inspect
959 # The class name of the object in NativeString format.
960 private fun native_class_name
: NativeString is intern
962 # The class name of the object.
964 # assert 5.class_name == "Int"
965 fun class_name
: String do return native_class_name
.to_s
967 # Developer readable representation of `self`.
968 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
971 return "<{inspect_head}>"
974 # Return "CLASSNAME:#OBJECTID".
975 # This function is mainly used with the redefinition of the inspect method
976 protected fun inspect_head
: String
978 return "{class_name}:#{object_id.to_hex}"
981 protected fun args
: Sequence[String]
988 # assert true.to_s == "true"
989 # assert false.to_s == "false"
1001 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1002 # assume < to_c max const of char
1003 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1010 else if self == 0 then
1017 var pos
= digit_count
(base
) - 1
1018 while pos
>= 0 and n
> 0 do
1019 s
.chars
[pos
] = (n
% base
).to_c
1025 # C function to convert an nit Int to a NativeString (char*)
1026 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1028 # return displayable int in base 10 and signed
1030 # assert 1.to_s == "1"
1031 # assert (-123).to_s == "-123"
1033 var len
= digit_count
(10)
1034 return native_int_to_s
(len
).to_s_with_length
(len
)
1037 # return displayable int in hexadecimal (unsigned (not now))
1038 fun to_hex
: String do return to_base
(16,false)
1040 # return displayable int in base base and signed
1041 fun to_base
(base
: Int, signed
: Bool): String
1043 var l
= digit_count
(base
)
1044 var s
= new Buffer.from
(" " * l
)
1045 fill_buffer
(s
, base
, signed
)
1051 # Pretty print self, print needoed decimals up to a max of 3.
1053 var str
= to_precision
( 3 )
1054 if is_inf
!= 0 or is_nan
then return str
1055 var len
= str
.length
1056 for i
in [0..len-1
] do
1058 var c
= str
.chars
[j
]
1061 else if c
== '.' then
1062 return str
.substring
( 0, j
+2 )
1064 return str
.substring
( 0, j
+1 )
1070 # `self` representation with `nb` digits after the '.'.
1071 fun to_precision
(nb
: Int): String
1073 if is_nan
then return "nan"
1075 var isinf
= self.is_inf
1078 else if isinf
== -1 then
1082 if nb
== 0 then return self.to_i
.to_s
1084 for i
in [0..nb
[ do f
= f
* 10.0
1091 if i
== 0 then return "0.0"
1095 var p1
= s
.substring
(0, s
.length-nb
)
1096 var p2
= s
.substring
(s
.length-nb
, nb
)
1097 return p1
+ "." + p2
1099 return "0." + ("0"*(nb-sl
)) + s
1103 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1107 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1108 str = malloc(size + 1);
1109 sprintf(str, "%.*f", (int)nb, recv );
1111 return NativeString_to_s( str );
1116 # assert 'x'.to_s == "x"
1119 var s
= new Buffer.with_capacity
(1)
1124 # Returns true if the char is a numerical digit
1125 fun is_numeric
: Bool
1127 if self >= '0' and self <= '9'
1134 # Returns true if the char is an alpha digit
1137 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1141 # Returns true if the char is an alpha or a numeric digit
1142 fun is_alphanumeric
: Bool
1144 if self.is_numeric
or self.is_alpha
then return true
1149 redef class Collection[E
]
1150 # Concatenate elements.
1154 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1158 # Concatenate and separate each elements with `sep`.
1160 # assert [1, 2, 3].join(":") == "1:2:3"
1161 # assert [1..3].join(":") == "1:2:3"
1162 fun join
(sep
: String): String
1164 if is_empty
then return ""
1166 var s
= new Buffer # Result
1171 if e
!= null then s
.append
(e
.to_s
)
1173 # Concat other items
1178 if e
!= null then s
.append
(e
.to_s
)
1185 redef class Array[E
]
1186 # Fast implementation
1194 if e
!= null then s
.append
(e
.to_s
)
1201 redef class Map[K
,V
]
1202 # Concatenate couple of 'key value'.
1203 # key and value are separated by `couple_sep`.
1204 # each couple is separated each couple with `sep`.
1206 # var m = new ArrayMap[Int, String]
1209 # assert m.join("; ", "=") == "1=one; 10=ten"
1210 fun join
(sep
: String, couple_sep
: String): String
1212 if is_empty
then return ""
1214 var s
= new Buffer # Result
1220 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1222 # Concat other items
1228 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1235 ###############################################################################
1237 ###############################################################################
1239 # Native strings are simple C char *
1243 fun [](index
: Int): Char is intern
1244 fun []=(index
: Int, item
: Char) is intern
1245 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1247 # Position of the first nul character.
1248 fun cstring_length
: Int
1251 while self[l
] != '\0' do l
+= 1
1254 fun atoi
: Int is intern
1255 fun atof
: Float is extern "atof"
1259 return to_s_with_length
(cstring_length
)
1262 fun to_s_with_length
(length
: Int): String
1265 return new String.with_infos
(self, length
, 0, length
- 1)
1268 fun to_s_with_copy
: String
1270 var length
= cstring_length
1271 var new_self
= calloc_string
(length
+ 1)
1272 copy_to
(new_self
, length
, 0, 0)
1273 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1278 # StringCapable objects can create native strings
1279 interface StringCapable
1280 protected fun calloc_string
(size
: Int): NativeString is intern
1284 var _args_cache
: nullable Sequence[String]
1286 redef fun args
: Sequence[String]
1288 if _args_cache
== null then init_args
1289 return _args_cache
.as(not null)
1292 # The name of the program as given by the OS
1293 fun program_name
: String
1295 return native_argv
(0).to_s
1298 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1299 private fun init_args
1301 var argc
= native_argc
1302 var args
= new Array[String].with_capacity
(0)
1305 args
[i-1
] = native_argv
(i
).to_s
1311 # First argument of the main C function.
1312 private fun native_argc
: Int is intern
1314 # Second argument of the main C function.
1315 private fun native_argv
(i
: Int): NativeString is intern
1318 # Comparator that efficienlty use `to_s` to compare things
1320 # The comparaison call `to_s` on object and use the result to order things.
1322 # var a = [1, 2, 3, 10, 20]
1323 # (new CachedAlphaComparator).sort(a)
1324 # assert a == [1, 10, 2, 20, 3]
1326 # Internally the result of `to_s` is cached in a HashMap to counter
1327 # uneficient implementation of `to_s`.
1329 # Note: it caching is not usefull, see `alpha_comparator`
1330 class CachedAlphaComparator
1331 super Comparator[Object]
1333 private var cache
= new HashMap[Object, String]
1335 private fun do_to_s
(a
: Object): String do
1336 if cache
.has_key
(a
) then return cache
[a
]
1342 redef fun compare
(a
, b
) do
1343 return do_to_s
(a
) <=> do_to_s
(b
)
1347 # see `alpha_comparator`
1348 private class AlphaComparator
1349 super Comparator[Object]
1350 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1353 # Stateless comparator that naively use `to_s` to compare things.
1355 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1356 # on a single instace. See `CachedAlphaComparator` as an alternative.
1358 # var a = [1, 2, 3, 10, 20]
1359 # alpha_comparator.sort(a)
1360 # assert a == [1, 10, 2, 20, 3]
1361 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator