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