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