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