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