eea52be389bda98a60b5a4731e28f52877e6f8b0
[nit.git] / lib / standard / string.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
5 #
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
12 # another product.
13
14 # Basic manipulations of strings of characters
15 module string
16
17 import math
18 intrude import collection # FIXME should be collection::array
19
20 `{
21 #include <stdio.h>
22 #include <string.h>
23 `}
24
25 ###############################################################################
26 # String #
27 ###############################################################################
28
29 # High-level abstraction for all text representations
30 abstract class Text
31 super Comparable
32 super StringCapable
33
34 redef type OTHER: Text
35
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
37 type SELFTYPE: Text
38
39 # Gets a view on the chars of the Text object
40 #
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars: SequenceRead[Char] is abstract
43
44 # Number of characters contained in self.
45 #
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length: Int is abstract
49
50 # Create a substring.
51 #
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"
56 #
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
61
62 # Iterates on the substrings of self if any
63 fun substrings: Iterator[Text] is abstract
64
65 # Is the current Text empty (== "")
66 #
67 # assert "".is_empty
68 # assert not "foo".is_empty
69 fun is_empty: Bool do return self.length == 0
70
71 # Returns an empty Text of the right type
72 #
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty: SELFTYPE is abstract
76
77 # Gets the first char of the Text
78 #
79 # DEPRECATED : Use self.chars.first instead
80 fun first: Char do return self.chars[0]
81
82 # Access a character at `index` in the string.
83 #
84 # assert "abcd"[2] == 'c'
85 #
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index: Int): Char do return self.chars[index]
88
89 # Gets the index of the first occurence of 'c'
90 #
91 # Returns -1 if not found
92 #
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of(c: Char): Int
95 do
96 return index_of_from(c, 0)
97 end
98
99 # Gets the last char of self
100 #
101 # DEPRECATED : Use self.chars.last instead
102 fun last: Char do return self.chars[length-1]
103
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
105 #
106 # Returns -1 if not found
107 #
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from(c: Char, pos: Int): Int
110 do
111 var iter = self.chars.iterator_from(pos)
112 while iter.is_ok do
113 if iter.item == c then return iter.index
114 iter.next
115 end
116 return -1
117 end
118
119 # Gets the last index of char ´c´
120 #
121 # Returns -1 if not found
122 #
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of(c: Char): Int
125 do
126 return last_index_of_from(c, length - 1)
127 end
128
129 # Return a null terminated char *
130 fun to_cstring: NativeString do return flatten.to_cstring
131
132 # The index of the last occurrence of an element starting from pos (in reverse order).
133 #
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
137 #
138 # Returns -1 if not found
139 #
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from(item: Char, pos: Int): Int
142 do
143 var iter = self.chars.reverse_iterator_from(pos)
144 while iter.is_ok do
145 if iter.item == item then return iter.index
146 iter.next
147 end
148 return -1
149 end
150
151 # Gets an iterator on the chars of self
152 #
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator: Iterator[Char]
155 do
156 return self.chars.iterator
157 end
158
159 # Is 'c' contained in self ?
160 #
161 # DEPRECATED : Use self.chars.has instead
162 fun has(c: Char): Bool
163 do
164 return self.chars.has(c)
165 end
166
167 # Gets an Array containing the chars of self
168 #
169 # DEPRECATED : Use self.chars.to_a instead
170 fun to_a: Array[Char] do return chars.to_a
171
172 # Create a substring from `self` beginning at the `from` position
173 #
174 # assert "abcd".substring_from(1) == "bcd"
175 # assert "abcd".substring_from(-1) == "abcd"
176 # assert "abcd".substring_from(2) == "cd"
177 #
178 # As with substring, a `from` index < 0 will be replaced by 0
179 fun substring_from(from: Int): SELFTYPE
180 do
181 if from > self.length then return empty
182 if from < 0 then from = 0
183 return substring(from, length - from)
184 end
185
186 # Does self have a substring `str` starting from position `pos`?
187 #
188 # assert "abcd".has_substring("bc",1) == true
189 # assert "abcd".has_substring("bc",2) == false
190 fun has_substring(str: String, pos: Int): Bool
191 do
192 var myiter = self.chars.iterator_from(pos)
193 var itsiter = str.chars.iterator
194 while myiter.is_ok and itsiter.is_ok do
195 if myiter.item != itsiter.item then return false
196 myiter.next
197 itsiter.next
198 end
199 if itsiter.is_ok then return false
200 return true
201 end
202
203 # Is this string prefixed by `prefix`?
204 #
205 # assert "abcd".has_prefix("ab") == true
206 # assert "abcbc".has_prefix("bc") == false
207 # assert "ab".has_prefix("abcd") == false
208 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
209
210 # Is this string suffixed by `suffix`?
211 #
212 # assert "abcd".has_suffix("abc") == false
213 # assert "abcd".has_suffix("bcd") == true
214 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
215
216 # If `self` contains only digits, return the corresponding integer
217 #
218 # assert "123".to_i == 123
219 # assert "-1".to_i == -1
220 fun to_i: Int
221 do
222 # Shortcut
223 return to_s.to_cstring.atoi
224 end
225
226 # If `self` contains a float, return the corresponding float
227 #
228 # assert "123".to_f == 123.0
229 # assert "-1".to_f == -1.0
230 # assert "-1.2e-3".to_f == -0.0012
231 fun to_f: Float
232 do
233 # Shortcut
234 return to_s.to_cstring.atof
235 end
236
237 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
238 #
239 # assert "ff".to_hex == 255
240 fun to_hex: Int do return a_to(16)
241
242 # If `self` contains only digits and letters, return the corresponding integer in a given base
243 #
244 # assert "120".a_to(3) == 15
245 fun a_to(base: Int) : Int
246 do
247 var i = 0
248 var neg = false
249
250 for c in self.chars
251 do
252 var v = c.to_i
253 if v > base then
254 if neg then
255 return -i
256 else
257 return i
258 end
259 else if v < 0 then
260 neg = true
261 else
262 i = i * base + v
263 end
264 end
265 if neg then
266 return -i
267 else
268 return i
269 end
270 end
271
272 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
273 #
274 # assert "123".is_numeric == true
275 # assert "1.2".is_numeric == true
276 # assert "1,2".is_numeric == true
277 # assert "1..2".is_numeric == false
278 fun is_numeric: Bool
279 do
280 var has_point_or_comma = false
281 for i in self.chars
282 do
283 if not i.is_numeric
284 then
285 if (i == '.' or i == ',') and not has_point_or_comma
286 then
287 has_point_or_comma = true
288 else
289 return false
290 end
291 end
292 end
293 return true
294 end
295
296 # Are all letters in `self` upper-case ?
297 #
298 # assert "HELLO WORLD".is_upper == true
299 # assert "%$&%!".is_upper == true
300 # assert "hello world".is_upper == false
301 # assert "Hello World".is_upper == false
302 fun is_upper: Bool
303 do
304 for char in self.chars do
305 if char.is_lower then return false
306 end
307 return true
308 end
309
310 # Are all letters in `self` lower-case ?
311 #
312 # assert "hello world".is_lower == true
313 # assert "%$&%!".is_lower == true
314 # assert "Hello World".is_lower == false
315 fun is_lower: Bool
316 do
317 for char in self.chars do
318 if char.is_upper then return false
319 end
320 return true
321 end
322
323 # Removes the whitespaces at the beginning of self
324 #
325 # assert " \n\thello \n\t".l_trim == "hello \n\t"
326 #
327 # A whitespace is defined as any character which ascii value is less than or equal to 32
328 fun l_trim: SELFTYPE
329 do
330 var iter = self.chars.iterator
331 while iter.is_ok do
332 if iter.item.ascii > 32 then break
333 iter.next
334 end
335 if iter.index == length then return self.empty
336 return self.substring_from(iter.index)
337 end
338
339 # Removes the whitespaces at the end of self
340 #
341 # assert " \n\thello \n\t".r_trim == " \n\thello"
342 #
343 # A whitespace is defined as any character which ascii value is less than or equal to 32
344 fun r_trim: SELFTYPE
345 do
346 var iter = self.chars.reverse_iterator
347 while iter.is_ok do
348 if iter.item.ascii > 32 then break
349 iter.next
350 end
351 if iter.index == length then return self.empty
352 return self.substring(0, iter.index + 1)
353 end
354
355 # Trims trailing and preceding white spaces
356 # A whitespace is defined as any character which ascii value is less than or equal to 32
357 #
358 # assert " Hello World ! ".trim == "Hello World !"
359 # assert "\na\nb\tc\t".trim == "a\nb\tc"
360 fun trim: SELFTYPE do return (self.l_trim).r_trim
361
362 # Mangle a string to be a unique string only made of alphanumeric characters
363 fun to_cmangle: String
364 do
365 var res = new FlatBuffer
366 var underscore = false
367 for c in self.chars do
368 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
369 res.add(c)
370 underscore = false
371 continue
372 end
373 if underscore then
374 res.append('_'.ascii.to_s)
375 res.add('d')
376 end
377 if c >= '0' and c <= '9' then
378 res.add(c)
379 underscore = false
380 else if c == '_' then
381 res.add(c)
382 underscore = true
383 else
384 res.add('_')
385 res.append(c.ascii.to_s)
386 res.add('d')
387 underscore = false
388 end
389 end
390 return res.to_s
391 end
392
393 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
394 #
395 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
396 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
397 fun escape_to_c: String
398 do
399 var b = new FlatBuffer
400 for c in self.chars do
401 if c == '\n' then
402 b.append("\\n")
403 else if c == '\0' then
404 b.append("\\0")
405 else if c == '"' then
406 b.append("\\\"")
407 else if c == '\'' then
408 b.append("\\\'")
409 else if c == '\\' then
410 b.append("\\\\")
411 else if c.ascii < 32 then
412 b.append("\\{c.ascii.to_base(8, false)}")
413 else
414 b.add(c)
415 end
416 end
417 return b.to_s
418 end
419
420 # Escape additionnal characters
421 # The result might no be legal in C but be used in other languages
422 #
423 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
424 fun escape_more_to_c(chars: String): String
425 do
426 var b = new FlatBuffer
427 for c in escape_to_c.chars do
428 if chars.chars.has(c) then
429 b.add('\\')
430 end
431 b.add(c)
432 end
433 return b.to_s
434 end
435
436 # Escape to C plus braces
437 #
438 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
439 fun escape_to_nit: String do return escape_more_to_c("\{\}")
440
441 # Return a string where Nit escape sequences are transformed.
442 #
443 # var s = "\\n"
444 # assert s.length == 2
445 # var u = s.unescape_nit
446 # assert u.length == 1
447 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
448 fun unescape_nit: String
449 do
450 var res = new FlatBuffer.with_capacity(self.length)
451 var was_slash = false
452 for c in chars do
453 if not was_slash then
454 if c == '\\' then
455 was_slash = true
456 else
457 res.add(c)
458 end
459 continue
460 end
461 was_slash = false
462 if c == 'n' then
463 res.add('\n')
464 else if c == 'r' then
465 res.add('\r')
466 else if c == 't' then
467 res.add('\t')
468 else if c == '0' then
469 res.add('\0')
470 else
471 res.add(c)
472 end
473 end
474 return res.to_s
475 end
476
477 # Equality of text
478 # Two pieces of text are equals if thez have the same characters in the same order.
479 #
480 # assert "hello" == "hello"
481 # assert "hello" != "HELLO"
482 # assert "hello" == "hel"+"lo"
483 #
484 # Things that are not Text are not equal.
485 #
486 # assert "9" != '9'
487 # assert "9" != ['9']
488 # assert "9" != 9
489 #
490 # assert "9".chars.first == '9' # equality of Char
491 # assert "9".chars == ['9'] # equality of Sequence
492 # assert "9".to_i == 9 # equality of Int
493 redef fun ==(o)
494 do
495 if o == null then return false
496 if not o isa Text then return false
497 if self.is_same_instance(o) then return true
498 if self.length != o.length then return false
499 return self.chars == o.chars
500 end
501
502 # Lexicographical comparaison
503 #
504 # assert "abc" < "xy"
505 # assert "ABC" < "abc"
506 redef fun <(other)
507 do
508 var self_chars = self.chars.iterator
509 var other_chars = other.chars.iterator
510
511 while self_chars.is_ok and other_chars.is_ok do
512 if self_chars.item < other_chars.item then return true
513 if self_chars.item > other_chars.item then return false
514 self_chars.next
515 other_chars.next
516 end
517
518 if self_chars.is_ok then
519 return false
520 else
521 return true
522 end
523 end
524
525 # Flat representation of self
526 fun flatten: FlatText is abstract
527
528 private var hash_cache: nullable Int = null
529
530 redef fun hash
531 do
532 if hash_cache == null then
533 # djb2 hash algorithm
534 var h = 5381
535
536 for char in self.chars do
537 h = h.lshift(5) + h + char.ascii
538 end
539
540 hash_cache = h
541 end
542 return hash_cache.as(not null)
543 end
544
545 end
546
547 # All kinds of array-based text representations.
548 abstract class FlatText
549 super Text
550
551 private var items: NativeString
552
553 # Real items, used as cache for to_cstring is called
554 private var real_items: nullable NativeString = null
555
556 redef var length: Int = 0
557
558 init do end
559
560 redef fun output
561 do
562 var i = 0
563 while i < length do
564 items[i].output
565 i += 1
566 end
567 end
568
569 redef fun flatten do return self
570 end
571
572 # Abstract class for the SequenceRead compatible
573 # views on String and Buffer objects
574 private abstract class StringCharView
575 super SequenceRead[Char]
576
577 type SELFTYPE: Text
578
579 private var target: SELFTYPE
580
581 private init(tgt: SELFTYPE)
582 do
583 target = tgt
584 end
585
586 redef fun is_empty do return target.is_empty
587
588 redef fun length do return target.length
589
590 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
591
592 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
593 end
594
595 # View on Buffer objects, extends Sequence
596 # for mutation operations
597 private abstract class BufferCharView
598 super StringCharView
599 super Sequence[Char]
600
601 redef type SELFTYPE: Buffer
602
603 end
604
605 abstract class String
606 super Text
607
608 redef type SELFTYPE: String
609
610 redef fun to_s do return self
611
612 # Concatenates `o` to `self`
613 #
614 # assert "hello" + "world" == "helloworld"
615 # assert "" + "hello" + "" == "hello"
616 fun +(o: Text): SELFTYPE is abstract
617
618 # Concatenates self `i` times
619 #
620 # assert "abc" * 4 == "abcabcabcabc"
621 # assert "abc" * 1 == "abc"
622 # assert "abc" * 0 == ""
623 fun *(i: Int): SELFTYPE is abstract
624
625 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
626
627 # Returns a reversed version of self
628 #
629 # assert "hello".reversed == "olleh"
630 # assert "bob".reversed == "bob"
631 # assert "".reversed == ""
632 fun reversed: SELFTYPE is abstract
633
634 # A upper case version of `self`
635 #
636 # assert "Hello World!".to_upper == "HELLO WORLD!"
637 fun to_upper: SELFTYPE is abstract
638
639 # A lower case version of `self`
640 #
641 # assert "Hello World!".to_lower == "hello world!"
642 fun to_lower : SELFTYPE is abstract
643 end
644
645 private class FlatSubstringsIter
646 super Iterator[FlatText]
647
648 var tgt: nullable FlatText
649
650 init(tgt: FlatText) do self.tgt = tgt
651
652 redef fun item do
653 assert is_ok
654 return tgt.as(not null)
655 end
656
657 redef fun is_ok do return tgt != null
658
659 redef fun next do tgt = null
660 end
661
662 # Immutable strings of characters.
663 class FlatString
664 super FlatText
665 super String
666
667 # Index in _items of the start of the string
668 private var index_from: Int
669
670 # Indes in _items of the last item of the string
671 private var index_to: Int
672
673 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
674
675 ################################################
676 # AbstractString specific methods #
677 ################################################
678
679 redef fun reversed
680 do
681 var native = calloc_string(self.length + 1)
682 var length = self.length
683 var items = self.items
684 var pos = 0
685 var ipos = length-1
686 while pos < length do
687 native[pos] = items[ipos]
688 pos += 1
689 ipos -= 1
690 end
691 return native.to_s_with_length(self.length)
692 end
693
694 redef fun substring(from, count)
695 do
696 assert count >= 0
697
698 if from < 0 then
699 count += from
700 if count < 0 then count = 0
701 from = 0
702 end
703
704 var realFrom = index_from + from
705
706 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
707
708 if count == 0 then return empty
709
710 var to = realFrom + count - 1
711
712 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
713 end
714
715 redef fun empty do return "".as(FlatString)
716
717 redef fun to_upper
718 do
719 var outstr = calloc_string(self.length + 1)
720 var out_index = 0
721
722 var myitems = self.items
723 var index_from = self.index_from
724 var max = self.index_to
725
726 while index_from <= max do
727 outstr[out_index] = myitems[index_from].to_upper
728 out_index += 1
729 index_from += 1
730 end
731
732 outstr[self.length] = '\0'
733
734 return outstr.to_s_with_length(self.length)
735 end
736
737 redef fun to_lower
738 do
739 var outstr = calloc_string(self.length + 1)
740 var out_index = 0
741
742 var myitems = self.items
743 var index_from = self.index_from
744 var max = self.index_to
745
746 while index_from <= max do
747 outstr[out_index] = myitems[index_from].to_lower
748 out_index += 1
749 index_from += 1
750 end
751
752 outstr[self.length] = '\0'
753
754 return outstr.to_s_with_length(self.length)
755 end
756
757 redef fun output
758 do
759 var i = self.index_from
760 var imax = self.index_to
761 while i <= imax do
762 items[i].output
763 i += 1
764 end
765 end
766
767 ##################################################
768 # String Specific Methods #
769 ##################################################
770
771 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
772 do
773 self.items = items
774 length = len
775 index_from = from
776 index_to = to
777 end
778
779 redef fun to_cstring: NativeString
780 do
781 if real_items != null then return real_items.as(not null)
782 if index_from > 0 or index_to != items.cstring_length - 1 then
783 var newItems = calloc_string(length + 1)
784 self.items.copy_to(newItems, length, index_from, 0)
785 newItems[length] = '\0'
786 self.real_items = newItems
787 return newItems
788 end
789 return items
790 end
791
792 redef fun ==(other)
793 do
794 if not other isa FlatString then return super
795
796 if self.object_id == other.object_id then return true
797
798 var my_length = length
799
800 if other.length != my_length then return false
801
802 var my_index = index_from
803 var its_index = other.index_from
804
805 var last_iteration = my_index + my_length
806
807 var itsitems = other.items
808 var myitems = self.items
809
810 while my_index < last_iteration do
811 if myitems[my_index] != itsitems[its_index] then return false
812 my_index += 1
813 its_index += 1
814 end
815
816 return true
817 end
818
819 redef fun <(other)
820 do
821 if not other isa FlatString then return super
822
823 if self.object_id == other.object_id then return false
824
825 var my_curr_char : Char
826 var its_curr_char : Char
827
828 var curr_id_self = self.index_from
829 var curr_id_other = other.index_from
830
831 var my_items = self.items
832 var its_items = other.items
833
834 var my_length = self.length
835 var its_length = other.length
836
837 var max_iterations = curr_id_self + my_length
838
839 while curr_id_self < max_iterations do
840 my_curr_char = my_items[curr_id_self]
841 its_curr_char = its_items[curr_id_other]
842
843 if my_curr_char != its_curr_char then
844 if my_curr_char < its_curr_char then return true
845 return false
846 end
847
848 curr_id_self += 1
849 curr_id_other += 1
850 end
851
852 return my_length < its_length
853 end
854
855 redef fun +(s)
856 do
857 var my_length = self.length
858 var its_length = s.length
859
860 var total_length = my_length + its_length
861
862 var target_string = calloc_string(my_length + its_length + 1)
863
864 self.items.copy_to(target_string, my_length, index_from, 0)
865 if s isa FlatString then
866 s.items.copy_to(target_string, its_length, s.index_from, my_length)
867 else if s isa FlatBuffer then
868 s.items.copy_to(target_string, its_length, 0, my_length)
869 else
870 var curr_pos = my_length
871 for i in s.chars do
872 target_string[curr_pos] = i
873 curr_pos += 1
874 end
875 end
876
877 target_string[total_length] = '\0'
878
879 return target_string.to_s_with_length(total_length)
880 end
881
882 redef fun *(i)
883 do
884 assert i >= 0
885
886 var my_length = self.length
887
888 var final_length = my_length * i
889
890 var my_items = self.items
891
892 var target_string = calloc_string((final_length) + 1)
893
894 target_string[final_length] = '\0'
895
896 var current_last = 0
897
898 for iteration in [1 .. i] do
899 my_items.copy_to(target_string, my_length, 0, current_last)
900 current_last += my_length
901 end
902
903 return target_string.to_s_with_length(final_length)
904 end
905
906 redef fun hash
907 do
908 if hash_cache == null then
909 # djb2 hash algorithm
910 var h = 5381
911 var i = index_from
912
913 var myitems = items
914
915 while i <= index_to do
916 h = h.lshift(5) + h + myitems[i].ascii
917 i += 1
918 end
919
920 hash_cache = h
921 end
922
923 return hash_cache.as(not null)
924 end
925
926 redef fun substrings do return new FlatSubstringsIter(self)
927 end
928
929 private class FlatStringReverseIterator
930 super IndexedIterator[Char]
931
932 var target: FlatString
933
934 var target_items: NativeString
935
936 var curr_pos: Int
937
938 init with_pos(tgt: FlatString, pos: Int)
939 do
940 target = tgt
941 target_items = tgt.items
942 curr_pos = pos + tgt.index_from
943 end
944
945 redef fun is_ok do return curr_pos >= 0
946
947 redef fun item do return target_items[curr_pos]
948
949 redef fun next do curr_pos -= 1
950
951 redef fun index do return curr_pos - target.index_from
952
953 end
954
955 private class FlatStringIterator
956 super IndexedIterator[Char]
957
958 var target: FlatString
959
960 var target_items: NativeString
961
962 var curr_pos: Int
963
964 init with_pos(tgt: FlatString, pos: Int)
965 do
966 target = tgt
967 target_items = tgt.items
968 curr_pos = pos + target.index_from
969 end
970
971 redef fun is_ok do return curr_pos <= target.index_to
972
973 redef fun item do return target_items[curr_pos]
974
975 redef fun next do curr_pos += 1
976
977 redef fun index do return curr_pos - target.index_from
978
979 end
980
981 private class FlatStringCharView
982 super StringCharView
983
984 redef type SELFTYPE: FlatString
985
986 redef fun [](index)
987 do
988 # Check that the index (+ index_from) is not larger than indexTo
989 # In other terms, if the index is valid
990 assert index >= 0
991 var target = self.target
992 assert (index + target.index_from) <= target.index_to
993 return target.items[index + target.index_from]
994 end
995
996 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
997
998 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
999
1000 end
1001
1002 abstract class Buffer
1003 super Text
1004
1005 redef type SELFTYPE: Buffer
1006
1007 # Specific implementations MUST set this to `true` in order to invalidate caches
1008 protected var is_dirty = true
1009
1010 # Modifies the char contained at pos `index`
1011 #
1012 # DEPRECATED : Use self.chars.[]= instead
1013 fun []=(index: Int, item: Char) is abstract
1014
1015 # Adds a char `c` at the end of self
1016 #
1017 # DEPRECATED : Use self.chars.add instead
1018 fun add(c: Char) is abstract
1019
1020 # Clears the buffer
1021 #
1022 # var b = new FlatBuffer
1023 # b.append "hello"
1024 # assert not b.is_empty
1025 # b.clear
1026 # assert b.is_empty
1027 fun clear is abstract
1028
1029 # Enlarges the subsequent array containing the chars of self
1030 fun enlarge(cap: Int) is abstract
1031
1032 # Adds the content of text `s` at the end of self
1033 #
1034 # var b = new FlatBuffer
1035 # b.append "hello"
1036 # b.append "world"
1037 # assert b == "helloworld"
1038 fun append(s: Text) is abstract
1039
1040 # `self` is appended in such a way that `self` is repeated `r` times
1041 #
1042 # var b = new FlatBuffer
1043 # b.append "hello"
1044 # b.times 3
1045 # assert b == "hellohellohello"
1046 fun times(r: Int) is abstract
1047
1048 # Reverses itself in-place
1049 #
1050 # var b = new FlatBuffer
1051 # b.append("hello")
1052 # b.reverse
1053 # assert b == "olleh"
1054 fun reverse is abstract
1055
1056 # Changes each lower-case char in `self` by its upper-case variant
1057 #
1058 # var b = new FlatBuffer
1059 # b.append("Hello World!")
1060 # b.upper
1061 # assert b == "HELLO WORLD!"
1062 fun upper is abstract
1063
1064 # Changes each upper-case char in `self` by its lower-case variant
1065 #
1066 # var b = new FlatBuffer
1067 # b.append("Hello World!")
1068 # b.lower
1069 # assert b == "hello world!"
1070 fun lower is abstract
1071
1072 redef fun hash
1073 do
1074 if is_dirty then hash_cache = null
1075 return super
1076 end
1077
1078 # In Buffers, the internal sequence of character is mutable
1079 # Thus, `chars` can be used to modify the buffer.
1080 redef fun chars: Sequence[Char] is abstract
1081 end
1082
1083 # Mutable strings of characters.
1084 class FlatBuffer
1085 super FlatText
1086 super Buffer
1087
1088 redef type SELFTYPE: FlatBuffer
1089
1090 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1091
1092 private var capacity: Int = 0
1093
1094 redef fun substrings do return new FlatSubstringsIter(self)
1095
1096 redef fun []=(index, item)
1097 do
1098 is_dirty = true
1099 if index == length then
1100 add(item)
1101 return
1102 end
1103 assert index >= 0 and index < length
1104 items[index] = item
1105 end
1106
1107 redef fun add(c)
1108 do
1109 is_dirty = true
1110 if capacity <= length then enlarge(length + 5)
1111 items[length] = c
1112 length += 1
1113 end
1114
1115 redef fun clear do
1116 is_dirty = true
1117 length = 0
1118 end
1119
1120 redef fun empty do return new FlatBuffer
1121
1122 redef fun enlarge(cap)
1123 do
1124 var c = capacity
1125 if cap <= c then return
1126 while c <= cap do c = c * 2 + 2
1127 var a = calloc_string(c+1)
1128 if length > 0 then items.copy_to(a, length, 0, 0)
1129 items = a
1130 capacity = c
1131 end
1132
1133 redef fun to_s: String
1134 do
1135 return to_cstring.to_s_with_length(length)
1136 end
1137
1138 redef fun to_cstring
1139 do
1140 if is_dirty then
1141 var new_native = calloc_string(length + 1)
1142 new_native[length] = '\0'
1143 if length > 0 then items.copy_to(new_native, length, 0, 0)
1144 real_items = new_native
1145 is_dirty = false
1146 end
1147 return real_items.as(not null)
1148 end
1149
1150 # Create a new empty string.
1151 init do end
1152
1153 init from(s: Text)
1154 do
1155 capacity = s.length + 1
1156 length = s.length
1157 items = calloc_string(capacity)
1158 if s isa FlatString then
1159 s.items.copy_to(items, length, s.index_from, 0)
1160 else if s isa FlatBuffer then
1161 s.items.copy_to(items, length, 0, 0)
1162 else
1163 var curr_pos = 0
1164 for i in s.chars do
1165 items[curr_pos] = i
1166 curr_pos += 1
1167 end
1168 end
1169 end
1170
1171 # Create a new empty string with a given capacity.
1172 init with_capacity(cap: Int)
1173 do
1174 assert cap >= 0
1175 # _items = new NativeString.calloc(cap)
1176 items = calloc_string(cap+1)
1177 capacity = cap
1178 length = 0
1179 end
1180
1181 redef fun append(s)
1182 do
1183 if s.is_empty then return
1184 is_dirty = true
1185 var sl = s.length
1186 if capacity < length + sl then enlarge(length + sl)
1187 if s isa FlatString then
1188 s.items.copy_to(items, sl, s.index_from, length)
1189 else if s isa FlatBuffer then
1190 s.items.copy_to(items, sl, 0, length)
1191 else
1192 var curr_pos = self.length
1193 for i in s.chars do
1194 items[curr_pos] = i
1195 curr_pos += 1
1196 end
1197 end
1198 length += sl
1199 end
1200
1201 # Copies the content of self in `dest`
1202 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1203 do
1204 var self_chars = self.chars
1205 var dest_chars = dest.chars
1206 for i in [0..len-1] do
1207 dest_chars[new_start+i] = self_chars[start+i]
1208 end
1209 end
1210
1211 redef fun substring(from, count)
1212 do
1213 assert count >= 0
1214 count += from
1215 if from < 0 then from = 0
1216 if count > length then count = length
1217 if from < count then
1218 var r = new FlatBuffer.with_capacity(count - from)
1219 while from < count do
1220 r.chars.push(items[from])
1221 from += 1
1222 end
1223 return r
1224 else
1225 return new FlatBuffer
1226 end
1227 end
1228
1229 redef fun reverse
1230 do
1231 var ns = calloc_string(capacity)
1232 var si = length - 1
1233 var ni = 0
1234 var it = items
1235 while si >= 0 do
1236 ns[ni] = it[si]
1237 ni += 1
1238 si -= 1
1239 end
1240 items = ns
1241 end
1242
1243 redef fun times(repeats)
1244 do
1245 var x = new FlatString.with_infos(items, length, 0, length - 1)
1246 for i in [1..repeats[ do
1247 append(x)
1248 end
1249 end
1250
1251 redef fun upper
1252 do
1253 var it = items
1254 var id = length - 1
1255 while id >= 0 do
1256 it[id] = it[id].to_upper
1257 id -= 1
1258 end
1259 end
1260
1261 redef fun lower
1262 do
1263 var it = items
1264 var id = length - 1
1265 while id >= 0 do
1266 it[id] = it[id].to_lower
1267 id -= 1
1268 end
1269 end
1270 end
1271
1272 private class FlatBufferReverseIterator
1273 super IndexedIterator[Char]
1274
1275 var target: FlatBuffer
1276
1277 var target_items: NativeString
1278
1279 var curr_pos: Int
1280
1281 init with_pos(tgt: FlatBuffer, pos: Int)
1282 do
1283 target = tgt
1284 if tgt.length > 0 then target_items = tgt.items
1285 curr_pos = pos
1286 end
1287
1288 redef fun index do return curr_pos
1289
1290 redef fun is_ok do return curr_pos >= 0
1291
1292 redef fun item do return target_items[curr_pos]
1293
1294 redef fun next do curr_pos -= 1
1295
1296 end
1297
1298 private class FlatBufferCharView
1299 super BufferCharView
1300 super StringCapable
1301
1302 redef type SELFTYPE: FlatBuffer
1303
1304 redef fun [](index) do return target.items[index]
1305
1306 redef fun []=(index, item)
1307 do
1308 assert index >= 0 and index <= length
1309 if index == length then
1310 add(item)
1311 return
1312 end
1313 target.items[index] = item
1314 end
1315
1316 redef fun push(c)
1317 do
1318 target.add(c)
1319 end
1320
1321 redef fun add(c)
1322 do
1323 target.add(c)
1324 end
1325
1326 fun enlarge(cap: Int)
1327 do
1328 target.enlarge(cap)
1329 end
1330
1331 redef fun append(s)
1332 do
1333 var my_items = target.items
1334 var s_length = s.length
1335 if target.capacity < s.length then enlarge(s_length + target.length)
1336 end
1337
1338 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1339
1340 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1341
1342 end
1343
1344 private class FlatBufferIterator
1345 super IndexedIterator[Char]
1346
1347 var target: FlatBuffer
1348
1349 var target_items: NativeString
1350
1351 var curr_pos: Int
1352
1353 init with_pos(tgt: FlatBuffer, pos: Int)
1354 do
1355 target = tgt
1356 if tgt.length > 0 then target_items = tgt.items
1357 curr_pos = pos
1358 end
1359
1360 redef fun index do return curr_pos
1361
1362 redef fun is_ok do return curr_pos < target.length
1363
1364 redef fun item do return target_items[curr_pos]
1365
1366 redef fun next do curr_pos += 1
1367
1368 end
1369
1370 ###############################################################################
1371 # Refinement #
1372 ###############################################################################
1373
1374 redef class Object
1375 # User readable representation of `self`.
1376 fun to_s: String do return inspect
1377
1378 # The class name of the object in NativeString format.
1379 private fun native_class_name: NativeString is intern
1380
1381 # The class name of the object.
1382 #
1383 # assert 5.class_name == "Int"
1384 fun class_name: String do return native_class_name.to_s
1385
1386 # Developer readable representation of `self`.
1387 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1388 fun inspect: String
1389 do
1390 return "<{inspect_head}>"
1391 end
1392
1393 # Return "CLASSNAME:#OBJECTID".
1394 # This function is mainly used with the redefinition of the inspect method
1395 protected fun inspect_head: String
1396 do
1397 return "{class_name}:#{object_id.to_hex}"
1398 end
1399
1400 protected fun args: Sequence[String]
1401 do
1402 return sys.args
1403 end
1404 end
1405
1406 redef class Bool
1407 # assert true.to_s == "true"
1408 # assert false.to_s == "false"
1409 redef fun to_s
1410 do
1411 if self then
1412 return once "true"
1413 else
1414 return once "false"
1415 end
1416 end
1417 end
1418
1419 redef class Int
1420
1421 # Wrapper of strerror C function
1422 private fun strerror_ext: NativeString is extern `{
1423 return strerror(recv);
1424 `}
1425
1426 # Returns a string describing error number
1427 fun strerror: String do return strerror_ext.to_s
1428
1429 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1430 # assume < to_c max const of char
1431 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1432 do
1433 var n: Int
1434 # Sign
1435 if self < 0 then
1436 n = - self
1437 s.chars[0] = '-'
1438 else if self == 0 then
1439 s.chars[0] = '0'
1440 return
1441 else
1442 n = self
1443 end
1444 # Fill digits
1445 var pos = digit_count(base) - 1
1446 while pos >= 0 and n > 0 do
1447 s.chars[pos] = (n % base).to_c
1448 n = n / base # /
1449 pos -= 1
1450 end
1451 end
1452
1453 # C function to convert an nit Int to a NativeString (char*)
1454 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1455
1456 # return displayable int in base 10 and signed
1457 #
1458 # assert 1.to_s == "1"
1459 # assert (-123).to_s == "-123"
1460 redef fun to_s do
1461 var len = digit_count(10)
1462 return native_int_to_s(len).to_s_with_length(len)
1463 end
1464
1465 # return displayable int in hexadecimal
1466 #
1467 # assert 1.to_hex == "1"
1468 # assert (-255).to_hex == "-ff"
1469 fun to_hex: String do return to_base(16,false)
1470
1471 # return displayable int in base base and signed
1472 fun to_base(base: Int, signed: Bool): String
1473 do
1474 var l = digit_count(base)
1475 var s = new FlatBuffer.from(" " * l)
1476 fill_buffer(s, base, signed)
1477 return s.to_s
1478 end
1479 end
1480
1481 redef class Float
1482 # Pretty print self, print needoed decimals up to a max of 3.
1483 #
1484 # assert 12.34.to_s == "12.34"
1485 # assert (-0120.03450).to_s == "-120.035"
1486 #
1487 # see `to_precision` for a different precision.
1488 redef fun to_s do
1489 var str = to_precision( 3 )
1490 if is_inf != 0 or is_nan then return str
1491 var len = str.length
1492 for i in [0..len-1] do
1493 var j = len-1-i
1494 var c = str.chars[j]
1495 if c == '0' then
1496 continue
1497 else if c == '.' then
1498 return str.substring( 0, j+2 )
1499 else
1500 return str.substring( 0, j+1 )
1501 end
1502 end
1503 return str
1504 end
1505
1506 # `self` representation with `nb` digits after the '.'.
1507 #
1508 # assert 12.345.to_precision(1) == "12.3"
1509 # assert 12.345.to_precision(2) == "12.35"
1510 # assert 12.345.to_precision(3) == "12.345"
1511 # assert 12.345.to_precision(4) == "12.3450"
1512 fun to_precision(nb: Int): String
1513 do
1514 if is_nan then return "nan"
1515
1516 var isinf = self.is_inf
1517 if isinf == 1 then
1518 return "inf"
1519 else if isinf == -1 then
1520 return "-inf"
1521 end
1522
1523 if nb == 0 then return self.to_i.to_s
1524 var f = self
1525 for i in [0..nb[ do f = f * 10.0
1526 if self > 0.0 then
1527 f = f + 0.5
1528 else
1529 f = f - 0.5
1530 end
1531 var i = f.to_i
1532 if i == 0 then return "0.0"
1533 var s = i.to_s
1534 var sl = s.length
1535 if sl > nb then
1536 var p1 = s.substring(0, s.length-nb)
1537 var p2 = s.substring(s.length-nb, nb)
1538 return p1 + "." + p2
1539 else
1540 return "0." + ("0"*(nb-sl)) + s
1541 end
1542 end
1543
1544 # `self` representation with `nb` digits after the '.'.
1545 #
1546 # assert 12.345.to_precision_native(1) == "12.3"
1547 # assert 12.345.to_precision_native(2) == "12.35"
1548 # assert 12.345.to_precision_native(3) == "12.345"
1549 # assert 12.345.to_precision_native(4) == "12.3450"
1550 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1551 int size;
1552 char *str;
1553
1554 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1555 str = malloc(size + 1);
1556 sprintf(str, "%.*f", (int)nb, recv );
1557
1558 return NativeString_to_s( str );
1559 `}
1560 end
1561
1562 redef class Char
1563 # assert 'x'.to_s == "x"
1564 redef fun to_s
1565 do
1566 var s = new FlatBuffer.with_capacity(1)
1567 s.chars[0] = self
1568 return s.to_s
1569 end
1570
1571 # Returns true if the char is a numerical digit
1572 #
1573 # assert '0'.is_numeric
1574 # assert '9'.is_numeric
1575 # assert not 'a'.is_numeric
1576 # assert not '?'.is_numeric
1577 fun is_numeric: Bool
1578 do
1579 return self >= '0' and self <= '9'
1580 end
1581
1582 # Returns true if the char is an alpha digit
1583 #
1584 # assert 'a'.is_alpha
1585 # assert 'Z'.is_alpha
1586 # assert not '0'.is_alpha
1587 # assert not '?'.is_alpha
1588 fun is_alpha: Bool
1589 do
1590 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1591 end
1592
1593 # Returns true if the char is an alpha or a numeric digit
1594 #
1595 # assert 'a'.is_alphanumeric
1596 # assert 'Z'.is_alphanumeric
1597 # assert '0'.is_alphanumeric
1598 # assert '9'.is_alphanumeric
1599 # assert not '?'.is_alphanumeric
1600 fun is_alphanumeric: Bool
1601 do
1602 return self.is_numeric or self.is_alpha
1603 end
1604 end
1605
1606 redef class Collection[E]
1607 # Concatenate elements.
1608 redef fun to_s
1609 do
1610 var s = new FlatBuffer
1611 for e in self do if e != null then s.append(e.to_s)
1612 return s.to_s
1613 end
1614
1615 # Concatenate and separate each elements with `sep`.
1616 #
1617 # assert [1, 2, 3].join(":") == "1:2:3"
1618 # assert [1..3].join(":") == "1:2:3"
1619 fun join(sep: Text): String
1620 do
1621 if is_empty then return ""
1622
1623 var s = new FlatBuffer # Result
1624
1625 # Concat first item
1626 var i = iterator
1627 var e = i.item
1628 if e != null then s.append(e.to_s)
1629
1630 # Concat other items
1631 i.next
1632 while i.is_ok do
1633 s.append(sep)
1634 e = i.item
1635 if e != null then s.append(e.to_s)
1636 i.next
1637 end
1638 return s.to_s
1639 end
1640 end
1641
1642 redef class Array[E]
1643 # Fast implementation
1644 redef fun to_s
1645 do
1646 var s = new FlatBuffer
1647 var i = 0
1648 var l = length
1649 while i < l do
1650 var e = self[i]
1651 if e != null then s.append(e.to_s)
1652 i += 1
1653 end
1654 return s.to_s
1655 end
1656 end
1657
1658 redef class Map[K,V]
1659 # Concatenate couple of 'key value'.
1660 # key and value are separated by `couple_sep`.
1661 # each couple is separated each couple with `sep`.
1662 #
1663 # var m = new ArrayMap[Int, String]
1664 # m[1] = "one"
1665 # m[10] = "ten"
1666 # assert m.join("; ", "=") == "1=one; 10=ten"
1667 fun join(sep: String, couple_sep: String): String
1668 do
1669 if is_empty then return ""
1670
1671 var s = new FlatBuffer # Result
1672
1673 # Concat first item
1674 var i = iterator
1675 var k = i.key
1676 var e = i.item
1677 s.append("{k}{couple_sep}{e or else "<null>"}")
1678
1679 # Concat other items
1680 i.next
1681 while i.is_ok do
1682 s.append(sep)
1683 k = i.key
1684 e = i.item
1685 s.append("{k}{couple_sep}{e or else "<null>"}")
1686 i.next
1687 end
1688 return s.to_s
1689 end
1690 end
1691
1692 ###############################################################################
1693 # Native classes #
1694 ###############################################################################
1695
1696 # Native strings are simple C char *
1697 extern class NativeString `{ char* `}
1698 super StringCapable
1699
1700 fun [](index: Int): Char is intern
1701 fun []=(index: Int, item: Char) is intern
1702 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1703
1704 # Position of the first nul character.
1705 fun cstring_length: Int
1706 do
1707 var l = 0
1708 while self[l] != '\0' do l += 1
1709 return l
1710 end
1711 fun atoi: Int is intern
1712 fun atof: Float is extern "atof"
1713
1714 redef fun to_s
1715 do
1716 return to_s_with_length(cstring_length)
1717 end
1718
1719 fun to_s_with_length(length: Int): FlatString
1720 do
1721 assert length >= 0
1722 return new FlatString.with_infos(self, length, 0, length - 1)
1723 end
1724
1725 fun to_s_with_copy: FlatString
1726 do
1727 var length = cstring_length
1728 var new_self = calloc_string(length + 1)
1729 copy_to(new_self, length, 0, 0)
1730 return new FlatString.with_infos(new_self, length, 0, length - 1)
1731 end
1732 end
1733
1734 # StringCapable objects can create native strings
1735 interface StringCapable
1736 protected fun calloc_string(size: Int): NativeString is intern
1737 end
1738
1739 redef class Sys
1740 var _args_cache: nullable Sequence[String]
1741
1742 redef fun args: Sequence[String]
1743 do
1744 if _args_cache == null then init_args
1745 return _args_cache.as(not null)
1746 end
1747
1748 # The name of the program as given by the OS
1749 fun program_name: String
1750 do
1751 return native_argv(0).to_s
1752 end
1753
1754 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1755 private fun init_args
1756 do
1757 var argc = native_argc
1758 var args = new Array[String].with_capacity(0)
1759 var i = 1
1760 while i < argc do
1761 args[i-1] = native_argv(i).to_s
1762 i += 1
1763 end
1764 _args_cache = args
1765 end
1766
1767 # First argument of the main C function.
1768 private fun native_argc: Int is intern
1769
1770 # Second argument of the main C function.
1771 private fun native_argv(i: Int): NativeString is intern
1772 end
1773
1774 # Comparator that efficienlty use `to_s` to compare things
1775 #
1776 # The comparaison call `to_s` on object and use the result to order things.
1777 #
1778 # var a = [1, 2, 3, 10, 20]
1779 # (new CachedAlphaComparator).sort(a)
1780 # assert a == [1, 10, 2, 20, 3]
1781 #
1782 # Internally the result of `to_s` is cached in a HashMap to counter
1783 # uneficient implementation of `to_s`.
1784 #
1785 # Note: it caching is not usefull, see `alpha_comparator`
1786 class CachedAlphaComparator
1787 super Comparator[Object]
1788
1789 private var cache = new HashMap[Object, String]
1790
1791 private fun do_to_s(a: Object): String do
1792 if cache.has_key(a) then return cache[a]
1793 var res = a.to_s
1794 cache[a] = res
1795 return res
1796 end
1797
1798 redef fun compare(a, b) do
1799 return do_to_s(a) <=> do_to_s(b)
1800 end
1801 end
1802
1803 # see `alpha_comparator`
1804 private class AlphaComparator
1805 super Comparator[Object]
1806 redef fun compare(a, b) do return a.to_s <=> b.to_s
1807 end
1808
1809 # Stateless comparator that naively use `to_s` to compare things.
1810 #
1811 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1812 # on a single instace. See `CachedAlphaComparator` as an alternative.
1813 #
1814 # var a = [1, 2, 3, 10, 20]
1815 # alpha_comparator.sort(a)
1816 # assert a == [1, 10, 2, 20, 3]
1817 fun alpha_comparator: Comparator[Object] do return once new AlphaComparator