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