f348b75a600e1d20ba0b4f9d858c24c49f5a3dc1
[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 # Immutable strings of characters.
587 class String
588 super FlatText
589
590 redef type SELFTYPE: String
591 redef type SELFVIEW: FlatStringCharView
592
593 # Index in _items of the start of the string
594 private var index_from: Int
595
596 # Indes in _items of the last item of the string
597 private var index_to: Int
598
599 redef var chars: SELFVIEW = new FlatStringCharView(self)
600
601 ################################################
602 # AbstractString specific methods #
603 ################################################
604
605 redef fun [](index) do
606 assert index >= 0
607 # Check that the index (+ index_from) is not larger than indexTo
608 # In other terms, if the index is valid
609 assert (index + index_from) <= index_to
610 return items[index + index_from]
611 end
612
613 redef fun substring(from, count)
614 do
615 assert count >= 0
616
617 if from < 0 then
618 count += from
619 if count < 0 then count = 0
620 from = 0
621 end
622
623 var realFrom = index_from + from
624
625 if (realFrom + count) > index_to then return new String.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
626
627 if count == 0 then return ""
628
629 var to = realFrom + count - 1
630
631 return new String.with_infos(items, to - realFrom + 1, realFrom, to)
632 end
633
634 redef fun empty do return "".as(String)
635
636 redef fun to_upper
637 do
638 var outstr = calloc_string(self.length + 1)
639 var out_index = 0
640
641 var myitems = self.items
642 var index_from = self.index_from
643 var max = self.index_to
644
645 while index_from <= max do
646 outstr[out_index] = myitems[index_from].to_upper
647 out_index += 1
648 index_from += 1
649 end
650
651 outstr[self.length] = '\0'
652
653 return outstr.to_s_with_length(self.length)
654 end
655
656 redef fun to_lower
657 do
658 var outstr = calloc_string(self.length + 1)
659 var out_index = 0
660
661 var myitems = self.items
662 var index_from = self.index_from
663 var max = self.index_to
664
665 while index_from <= max do
666 outstr[out_index] = myitems[index_from].to_lower
667 out_index += 1
668 index_from += 1
669 end
670
671 outstr[self.length] = '\0'
672
673 return outstr.to_s_with_length(self.length)
674 end
675
676 redef fun output
677 do
678 var i = self.index_from
679 var imax = self.index_to
680 while i <= imax do
681 items[i].output
682 i += 1
683 end
684 end
685
686 ##################################################
687 # String Specific Methods #
688 ##################################################
689
690 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
691 do
692 self.items = items
693 length = len
694 index_from = from
695 index_to = to
696 end
697
698 # Return a null terminated char *
699 fun to_cstring: NativeString
700 do
701 if index_from > 0 or index_to != items.cstring_length - 1 then
702 var newItems = calloc_string(length + 1)
703 self.items.copy_to(newItems, length, index_from, 0)
704 newItems[length] = '\0'
705 return newItems
706 end
707 return items
708 end
709
710 redef fun ==(other)
711 do
712 if not other isa String then return super
713
714 if self.object_id == other.object_id then return true
715
716 var my_length = length
717
718 if other.length != my_length then return false
719
720 var my_index = index_from
721 var its_index = other.index_from
722
723 var last_iteration = my_index + my_length
724
725 var itsitems = other.items
726 var myitems = self.items
727
728 while my_index < last_iteration do
729 if myitems[my_index] != itsitems[its_index] then return false
730 my_index += 1
731 its_index += 1
732 end
733
734 return true
735 end
736
737 # The comparison between two strings is done on a lexicographical basis
738 #
739 # assert ("aa" < "b") == true
740 redef fun <(other)
741 do
742 if not other isa String then return super
743
744 if self.object_id == other.object_id then return false
745
746 var my_curr_char : Char
747 var its_curr_char : Char
748
749 var curr_id_self = self.index_from
750 var curr_id_other = other.index_from
751
752 var my_items = self.items
753 var its_items = other.items
754
755 var my_length = self.length
756 var its_length = other.length
757
758 var max_iterations = curr_id_self + my_length
759
760 while curr_id_self < max_iterations do
761 my_curr_char = my_items[curr_id_self]
762 its_curr_char = its_items[curr_id_other]
763
764 if my_curr_char != its_curr_char then
765 if my_curr_char < its_curr_char then return true
766 return false
767 end
768
769 curr_id_self += 1
770 curr_id_other += 1
771 end
772
773 return my_length < its_length
774 end
775
776 # The concatenation of `self` with `s`
777 #
778 # assert "hello " + "world!" == "hello world!"
779 redef fun +(s)
780 do
781 var my_length = self.length
782 var its_length = s.length
783
784 var total_length = my_length + its_length
785
786 var target_string = calloc_string(my_length + its_length + 1)
787
788 self.items.copy_to(target_string, my_length, index_from, 0)
789 if s isa String then
790 s.items.copy_to(target_string, its_length, s.index_from, my_length)
791 else if s isa FlatBuffer then
792 s.items.copy_to(target_string, its_length, 0, my_length)
793 else
794 var curr_pos = my_length
795 for i in s.chars do
796 target_string[curr_pos] = i
797 curr_pos += 1
798 end
799 end
800
801 target_string[total_length] = '\0'
802
803 return target_string.to_s_with_length(total_length)
804 end
805
806 # assert "abc"*3 == "abcabcabc"
807 # assert "abc"*1 == "abc"
808 # assert "abc"*0 == ""
809 redef fun *(i)
810 do
811 assert i >= 0
812
813 var my_length = self.length
814
815 var final_length = my_length * i
816
817 var my_items = self.items
818
819 var target_string = calloc_string((final_length) + 1)
820
821 target_string[final_length] = '\0'
822
823 var current_last = 0
824
825 for iteration in [1 .. i] do
826 my_items.copy_to(target_string, my_length, 0, current_last)
827 current_last += my_length
828 end
829
830 return target_string.to_s_with_length(final_length)
831 end
832
833 redef fun to_s do return self
834
835 redef fun hash
836 do
837 # djb2 hash algorythm
838 var h = 5381
839 var i = length - 1
840
841 var myitems = items
842 var strStart = index_from
843
844 i += strStart
845
846 while i >= strStart do
847 h = (h * 32) + h + self.items[i].ascii
848 i -= 1
849 end
850
851 return h
852 end
853 end
854
855 private class FlatStringReverseIterator
856 super IndexedIterator[Char]
857
858 var target: String
859
860 var target_items: NativeString
861
862 var curr_pos: Int
863
864 init with_pos(tgt: String, pos: Int)
865 do
866 target = tgt
867 target_items = tgt.items
868 curr_pos = pos + tgt.index_from
869 end
870
871 redef fun is_ok do return curr_pos >= 0
872
873 redef fun item do return target_items[curr_pos]
874
875 redef fun next do curr_pos -= 1
876
877 redef fun index do return curr_pos - target.index_from
878
879 end
880
881 private class FlatStringIterator
882 super IndexedIterator[Char]
883
884 var target: String
885
886 var target_items: NativeString
887
888 var curr_pos: Int
889
890 init with_pos(tgt: String, pos: Int)
891 do
892 target = tgt
893 target_items = tgt.items
894 curr_pos = pos + target.index_from
895 end
896
897 redef fun is_ok do return curr_pos <= target.index_to
898
899 redef fun item do return target_items[curr_pos]
900
901 redef fun next do curr_pos += 1
902
903 redef fun index do return curr_pos - target.index_from
904
905 end
906
907 private class FlatStringCharView
908 super StringCharView
909
910 redef type SELFTYPE: String
911
912 redef fun [](index)
913 do
914 # Check that the index (+ index_from) is not larger than indexTo
915 # In other terms, if the index is valid
916 assert index >= 0
917 assert (index + target.index_from) <= target.index_to
918 return target.items[index + target.index_from]
919 end
920
921 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
922
923 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
924
925 end
926
927 abstract class Buffer
928 super Text
929
930 redef type SELFVIEW: BufferCharView
931 redef type SELFTYPE: Buffer
932
933 # Modifies the char contained at pos `index`
934 #
935 # DEPRECATED : Use self.chars.[]= instead
936 fun []=(index: Int, item: Char) is abstract
937
938 # Adds a char `c` at the end of self
939 #
940 # DEPRECATED : Use self.chars.add instead
941 fun add(c: Char) is abstract
942
943 # Clears the buffer
944 fun clear is abstract
945
946 # Enlarges the subsequent array containing the chars of self
947 fun enlarge(cap: Int) is abstract
948
949 # Adds the content of string `s` at the end of self
950 fun append(s: String) is abstract
951
952 end
953
954 # Mutable strings of characters.
955 class FlatBuffer
956 super FlatText
957 super Buffer
958
959 redef type SELFVIEW: FlatBufferCharView
960 redef type SELFTYPE: FlatBuffer
961
962 redef var chars: SELFVIEW = new FlatBufferCharView(self)
963
964 var capacity: Int
965
966 redef fun []=(index, item)
967 do
968 if index == length then
969 add(item)
970 return
971 end
972 assert index >= 0 and index < length
973 items[index] = item
974 end
975
976 redef fun add(c)
977 do
978 if capacity <= length then enlarge(length + 5)
979 items[length] = c
980 length += 1
981 end
982
983 redef fun clear do length = 0
984
985 redef fun empty do return new FlatBuffer
986
987 redef fun enlarge(cap)
988 do
989 var c = capacity
990 if cap <= c then return
991 while c <= cap do c = c * 2 + 2
992 var a = calloc_string(c+1)
993 items.copy_to(a, length, 0, 0)
994 items = a
995 capacity = c
996 items.copy_to(a, length, 0, 0)
997 end
998
999 redef fun to_s: String
1000 do
1001 var l = length
1002 var a = calloc_string(l+1)
1003 items.copy_to(a, l, 0, 0)
1004
1005 # Ensure the afterlast byte is '\0' to nul-terminated char *
1006 a[length] = '\0'
1007
1008 return a.to_s_with_length(length)
1009 end
1010
1011 # Create a new empty string.
1012 init
1013 do
1014 with_capacity(5)
1015 end
1016
1017 init from(s: String)
1018 do
1019 capacity = s.length + 1
1020 length = s.length
1021 items = calloc_string(capacity)
1022 s.items.copy_to(items, length, s.index_from, 0)
1023 end
1024
1025 # Create a new empty string with a given capacity.
1026 init with_capacity(cap: Int)
1027 do
1028 assert cap >= 0
1029 # _items = new NativeString.calloc(cap)
1030 items = calloc_string(cap+1)
1031 capacity = cap
1032 length = 0
1033 end
1034
1035 redef fun append(s)
1036 do
1037 var sl = s.length
1038 if capacity < length + sl then enlarge(length + sl)
1039 s.items.copy_to(items, sl, s.index_from, length)
1040 length += sl
1041 end
1042
1043 # Copies the content of self in `dest`
1044 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1045 do
1046 var self_chars = self.chars
1047 var dest_chars = dest.chars
1048 for i in [0..len-1] do
1049 dest_chars[new_start+i] = self_chars[start+i]
1050 end
1051 end
1052
1053 redef fun substring(from, count)
1054 do
1055 assert count >= 0
1056 count += from
1057 if from < 0 then from = 0
1058 if count > length then count = length
1059 if from < count then
1060 var r = new FlatBuffer.with_capacity(count - from)
1061 while from < count do
1062 r.chars.push(items[from])
1063 from += 1
1064 end
1065 return r
1066 else
1067 return new FlatBuffer
1068 end
1069 end
1070
1071 redef fun +(other)
1072 do
1073 var new_buf = new FlatBuffer.with_capacity(self.length + other.length)
1074 new_buf.append(self)
1075 new_buf.append(other)
1076 return new_buf
1077 end
1078
1079 redef fun *(repeats)
1080 do
1081 var new_buf = new FlatBuffer.with_capacity(self.length * repeats)
1082 for i in [0..repeats[ do
1083 new_buf.append(self)
1084 end
1085 return new_buf
1086 end
1087 end
1088
1089 private class FlatBufferReverseIterator
1090 super IndexedIterator[Char]
1091
1092 var target: FlatBuffer
1093
1094 var target_items: NativeString
1095
1096 var curr_pos: Int
1097
1098 init with_pos(tgt: FlatBuffer, pos: Int)
1099 do
1100 target = tgt
1101 target_items = tgt.items
1102 curr_pos = pos
1103 end
1104
1105 redef fun index do return curr_pos
1106
1107 redef fun is_ok do return curr_pos >= 0
1108
1109 redef fun item do return target_items[curr_pos]
1110
1111 redef fun next do curr_pos -= 1
1112
1113 end
1114
1115 private class FlatBufferCharView
1116 super BufferCharView
1117 super StringCapable
1118
1119 redef type SELFTYPE: FlatBuffer
1120
1121 redef fun [](index) do return target.items[index]
1122
1123 redef fun []=(index, item)
1124 do
1125 assert index >= 0 and index <= length
1126 if index == length then
1127 add(item)
1128 return
1129 end
1130 target.items[index] = item
1131 end
1132
1133 redef fun push(c)
1134 do
1135 target.add(c)
1136 end
1137
1138 redef fun add(c)
1139 do
1140 target.add(c)
1141 end
1142
1143 fun enlarge(cap: Int)
1144 do
1145 target.enlarge(cap)
1146 end
1147
1148 redef fun append(s)
1149 do
1150 var my_items = target.items
1151 var s_length = s.length
1152 if target.capacity < s.length then enlarge(s_length + target.length)
1153 end
1154
1155 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1156
1157 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1158
1159 end
1160
1161 private class FlatBufferIterator
1162 super IndexedIterator[Char]
1163
1164 var target: FlatBuffer
1165
1166 var target_items: NativeString
1167
1168 var curr_pos: Int
1169
1170 init with_pos(tgt: FlatBuffer, pos: Int)
1171 do
1172 target = tgt
1173 target_items = tgt.items
1174 curr_pos = pos
1175 end
1176
1177 redef fun index do return curr_pos
1178
1179 redef fun is_ok do return curr_pos < target.length
1180
1181 redef fun item do return target_items[curr_pos]
1182
1183 redef fun next do curr_pos += 1
1184
1185 end
1186
1187 ###############################################################################
1188 # Refinement #
1189 ###############################################################################
1190
1191 redef class Object
1192 # User readable representation of `self`.
1193 fun to_s: String do return inspect
1194
1195 # The class name of the object in NativeString format.
1196 private fun native_class_name: NativeString is intern
1197
1198 # The class name of the object.
1199 #
1200 # assert 5.class_name == "Int"
1201 fun class_name: String do return native_class_name.to_s
1202
1203 # Developer readable representation of `self`.
1204 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1205 fun inspect: String
1206 do
1207 return "<{inspect_head}>"
1208 end
1209
1210 # Return "CLASSNAME:#OBJECTID".
1211 # This function is mainly used with the redefinition of the inspect method
1212 protected fun inspect_head: String
1213 do
1214 return "{class_name}:#{object_id.to_hex}"
1215 end
1216
1217 protected fun args: Sequence[String]
1218 do
1219 return sys.args
1220 end
1221 end
1222
1223 redef class Bool
1224 # assert true.to_s == "true"
1225 # assert false.to_s == "false"
1226 redef fun to_s
1227 do
1228 if self then
1229 return once "true"
1230 else
1231 return once "false"
1232 end
1233 end
1234 end
1235
1236 redef class Int
1237 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1238 # assume < to_c max const of char
1239 fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1240 do
1241 var n: Int
1242 # Sign
1243 if self < 0 then
1244 n = - self
1245 s.chars[0] = '-'
1246 else if self == 0 then
1247 s.chars[0] = '0'
1248 return
1249 else
1250 n = self
1251 end
1252 # Fill digits
1253 var pos = digit_count(base) - 1
1254 while pos >= 0 and n > 0 do
1255 s.chars[pos] = (n % base).to_c
1256 n = n / base # /
1257 pos -= 1
1258 end
1259 end
1260
1261 # C function to convert an nit Int to a NativeString (char*)
1262 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1263
1264 # return displayable int in base 10 and signed
1265 #
1266 # assert 1.to_s == "1"
1267 # assert (-123).to_s == "-123"
1268 redef fun to_s do
1269 var len = digit_count(10)
1270 return native_int_to_s(len).to_s_with_length(len)
1271 end
1272
1273 # return displayable int in hexadecimal (unsigned (not now))
1274 fun to_hex: String do return to_base(16,false)
1275
1276 # return displayable int in base base and signed
1277 fun to_base(base: Int, signed: Bool): String
1278 do
1279 var l = digit_count(base)
1280 var s = new FlatBuffer.from(" " * l)
1281 fill_buffer(s, base, signed)
1282 return s.to_s
1283 end
1284 end
1285
1286 redef class Float
1287 # Pretty print self, print needoed decimals up to a max of 3.
1288 redef fun to_s do
1289 var str = to_precision( 3 )
1290 if is_inf != 0 or is_nan then return str
1291 var len = str.length
1292 for i in [0..len-1] do
1293 var j = len-1-i
1294 var c = str.chars[j]
1295 if c == '0' then
1296 continue
1297 else if c == '.' then
1298 return str.substring( 0, j+2 )
1299 else
1300 return str.substring( 0, j+1 )
1301 end
1302 end
1303 return str
1304 end
1305
1306 # `self` representation with `nb` digits after the '.'.
1307 fun to_precision(nb: Int): String
1308 do
1309 if is_nan then return "nan"
1310
1311 var isinf = self.is_inf
1312 if isinf == 1 then
1313 return "inf"
1314 else if isinf == -1 then
1315 return "-inf"
1316 end
1317
1318 if nb == 0 then return self.to_i.to_s
1319 var f = self
1320 for i in [0..nb[ do f = f * 10.0
1321 if self > 0.0 then
1322 f = f + 0.5
1323 else
1324 f = f - 0.5
1325 end
1326 var i = f.to_i
1327 if i == 0 then return "0.0"
1328 var s = i.to_s
1329 var sl = s.length
1330 if sl > nb then
1331 var p1 = s.substring(0, s.length-nb)
1332 var p2 = s.substring(s.length-nb, nb)
1333 return p1 + "." + p2
1334 else
1335 return "0." + ("0"*(nb-sl)) + s
1336 end
1337 end
1338
1339 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1340 int size;
1341 char *str;
1342
1343 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1344 str = malloc(size + 1);
1345 sprintf(str, "%.*f", (int)nb, recv );
1346
1347 return NativeString_to_s( str );
1348 `}
1349 end
1350
1351 redef class Char
1352 # assert 'x'.to_s == "x"
1353 redef fun to_s
1354 do
1355 var s = new FlatBuffer.with_capacity(1)
1356 s.chars[0] = self
1357 return s.to_s
1358 end
1359
1360 # Returns true if the char is a numerical digit
1361 fun is_numeric: Bool
1362 do
1363 if self >= '0' and self <= '9'
1364 then
1365 return true
1366 end
1367 return false
1368 end
1369
1370 # Returns true if the char is an alpha digit
1371 fun is_alpha: Bool
1372 do
1373 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1374 return false
1375 end
1376
1377 # Returns true if the char is an alpha or a numeric digit
1378 fun is_alphanumeric: Bool
1379 do
1380 if self.is_numeric or self.is_alpha then return true
1381 return false
1382 end
1383 end
1384
1385 redef class Collection[E]
1386 # Concatenate elements.
1387 redef fun to_s
1388 do
1389 var s = new FlatBuffer
1390 for e in self do if e != null then s.append(e.to_s)
1391 return s.to_s
1392 end
1393
1394 # Concatenate and separate each elements with `sep`.
1395 #
1396 # assert [1, 2, 3].join(":") == "1:2:3"
1397 # assert [1..3].join(":") == "1:2:3"
1398 fun join(sep: String): String
1399 do
1400 if is_empty then return ""
1401
1402 var s = new FlatBuffer # Result
1403
1404 # Concat first item
1405 var i = iterator
1406 var e = i.item
1407 if e != null then s.append(e.to_s)
1408
1409 # Concat other items
1410 i.next
1411 while i.is_ok do
1412 s.append(sep)
1413 e = i.item
1414 if e != null then s.append(e.to_s)
1415 i.next
1416 end
1417 return s.to_s
1418 end
1419 end
1420
1421 redef class Array[E]
1422 # Fast implementation
1423 redef fun to_s
1424 do
1425 var s = new FlatBuffer
1426 var i = 0
1427 var l = length
1428 while i < l do
1429 var e = self[i]
1430 if e != null then s.append(e.to_s)
1431 i += 1
1432 end
1433 return s.to_s
1434 end
1435 end
1436
1437 redef class Map[K,V]
1438 # Concatenate couple of 'key value'.
1439 # key and value are separated by `couple_sep`.
1440 # each couple is separated each couple with `sep`.
1441 #
1442 # var m = new ArrayMap[Int, String]
1443 # m[1] = "one"
1444 # m[10] = "ten"
1445 # assert m.join("; ", "=") == "1=one; 10=ten"
1446 fun join(sep: String, couple_sep: String): String
1447 do
1448 if is_empty then return ""
1449
1450 var s = new FlatBuffer # Result
1451
1452 # Concat first item
1453 var i = iterator
1454 var k = i.key
1455 var e = i.item
1456 s.append("{k}{couple_sep}{e or else "<null>"}")
1457
1458 # Concat other items
1459 i.next
1460 while i.is_ok do
1461 s.append(sep)
1462 k = i.key
1463 e = i.item
1464 s.append("{k}{couple_sep}{e or else "<null>"}")
1465 i.next
1466 end
1467 return s.to_s
1468 end
1469 end
1470
1471 ###############################################################################
1472 # Native classes #
1473 ###############################################################################
1474
1475 # Native strings are simple C char *
1476 class NativeString
1477 super StringCapable
1478
1479 fun [](index: Int): Char is intern
1480 fun []=(index: Int, item: Char) is intern
1481 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1482
1483 # Position of the first nul character.
1484 fun cstring_length: Int
1485 do
1486 var l = 0
1487 while self[l] != '\0' do l += 1
1488 return l
1489 end
1490 fun atoi: Int is intern
1491 fun atof: Float is extern "atof"
1492
1493 redef fun to_s
1494 do
1495 return to_s_with_length(cstring_length)
1496 end
1497
1498 fun to_s_with_length(length: Int): String
1499 do
1500 assert length >= 0
1501 return new String.with_infos(self, length, 0, length - 1)
1502 end
1503
1504 fun to_s_with_copy: String
1505 do
1506 var length = cstring_length
1507 var new_self = calloc_string(length + 1)
1508 copy_to(new_self, length, 0, 0)
1509 return new String.with_infos(new_self, length, 0, length - 1)
1510 end
1511
1512 end
1513
1514 # StringCapable objects can create native strings
1515 interface StringCapable
1516 protected fun calloc_string(size: Int): NativeString is intern
1517 end
1518
1519 redef class Sys
1520 var _args_cache: nullable Sequence[String]
1521
1522 redef fun args: Sequence[String]
1523 do
1524 if _args_cache == null then init_args
1525 return _args_cache.as(not null)
1526 end
1527
1528 # The name of the program as given by the OS
1529 fun program_name: String
1530 do
1531 return native_argv(0).to_s
1532 end
1533
1534 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1535 private fun init_args
1536 do
1537 var argc = native_argc
1538 var args = new Array[String].with_capacity(0)
1539 var i = 1
1540 while i < argc do
1541 args[i-1] = native_argv(i).to_s
1542 i += 1
1543 end
1544 _args_cache = args
1545 end
1546
1547 # First argument of the main C function.
1548 private fun native_argc: Int is intern
1549
1550 # Second argument of the main C function.
1551 private fun native_argv(i: Int): NativeString is intern
1552 end
1553