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