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