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