1176e0401fc7eb20660f1ce5216f78ad672eee5c
[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
32 redef type OTHER: Text
33
34 # Type of the view on self (.chars)
35 type SELFVIEW: StringCharView
36
37 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
38 type SELFTYPE: Text
39
40 # Gets a view on the chars of the Text object
41 fun chars: SELFVIEW is abstract
42
43 # Number of characters contained in self.
44 fun length: Int is abstract
45
46 # Create a substring.
47 #
48 # assert "abcd".substring(1, 2) == "bc"
49 # assert "abcd".substring(-1, 2) == "a"
50 # assert "abcd".substring(1, 0) == ""
51 # assert "abcd".substring(2, 5) == "cd"
52 #
53 # A `from` index < 0 will be replaced by 0.
54 # Unless a `count` value is > 0 at the same time.
55 # In this case, `from += count` and `count -= from`.
56 fun substring(from: Int, count: Int): SELFTYPE is abstract
57
58 # Is the current Text empty (== "")
59 # assert "".is_empty
60 # assert not "foo".is_empty
61 fun is_empty: Bool do return self.length == 0
62
63 # Returns an empty Text of the right type
64 fun empty: SELFTYPE is abstract
65
66 # Gets the first char of the Text
67 #
68 # DEPRECATED : Use self.chars.first instead
69 fun first: Char do return self.chars[0]
70
71 # Access a character at `index` in the string.
72 #
73 # assert "abcd"[2] == 'c'
74 #
75 # DEPRECATED : Use self.chars.[] instead
76 fun [](index: Int): Char do return self.chars[index]
77
78 # Gets the index of the first occurence of 'c'
79 #
80 # Returns -1 if not found
81 #
82 # DEPRECATED : Use self.chars.index_of instead
83 fun index_of(c: Char): Int
84 do
85 return index_of_from(c, 0)
86 end
87
88 # Gets the last char of self
89 #
90 # DEPRECATED : Use self.chars.last instead
91 fun last: Char do return self.chars[length-1]
92
93 # Gets the index of the first occurence of ´c´ starting from ´pos´
94 #
95 # Returns -1 if not found
96 #
97 # DEPRECATED : Use self.chars.index_of_from instead
98 fun index_of_from(c: Char, pos: Int): Int
99 do
100 var iter = self.chars.iterator_from(pos)
101 while iter.is_ok do
102 if iter.item == c then return iter.index
103 end
104 return -1
105 end
106
107 # Gets the last index of char ´c´
108 #
109 # Returns -1 if not found
110 #
111 # DEPRECATED : Use self.chars.last_index_of instead
112 fun last_index_of(c: Char): Int
113 do
114 return last_index_of_from(c, length - 1)
115 end
116
117 # The index of the last occurrence of an element starting from pos (in reverse order).
118 # Example :
119 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
120 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
121 #
122 # Returns -1 if not found
123 #
124 # DEPRECATED : Use self.chars.last_index_of_from instead
125 fun last_index_of_from(item: Char, pos: Int): Int
126 do
127 var iter = self.chars.reverse_iterator_from(pos)
128 while iter.is_ok do
129 if iter.item == item then return iter.index
130 iter.next
131 end
132 return -1
133 end
134
135 # Gets an iterator on the chars of self
136 #
137 # DEPRECATED : Use self.chars.iterator instead
138 fun iterator: Iterator[Char]
139 do
140 return self.chars.iterator
141 end
142
143 # Is 'c' contained in self ?
144 #
145 # DEPRECATED : Use self.chars.has instead
146 fun has(c: Char): Bool
147 do
148 return self.chars.has(c)
149 end
150
151 # Gets an Array containing the chars of self
152 #
153 # DEPRECATED : Use self.chars.to_a instead
154 fun to_a: Array[Char] do return chars.to_a
155
156 # Create a substring from `self` beginning at the `from` position
157 #
158 # assert "abcd".substring_from(1) == "bcd"
159 # assert "abcd".substring_from(-1) == "abcd"
160 # assert "abcd".substring_from(2) == "cd"
161 #
162 # As with substring, a `from` index < 0 will be replaced by 0
163 fun substring_from(from: Int): SELFTYPE
164 do
165 assert from < length
166 return substring(from, length - from)
167 end
168
169 # Does self have a substring `str` starting from position `pos`?
170 #
171 # assert "abcd".has_substring("bc",1) == true
172 # assert "abcd".has_substring("bc",2) == false
173 fun has_substring(str: String, pos: Int): Bool
174 do
175 var myiter = self.chars.iterator_from(pos)
176 var itsiter = str.iterator
177 while myiter.is_ok and itsiter.is_ok do
178 if myiter.item != itsiter.item then return false
179 myiter.next
180 itsiter.next
181 end
182 if itsiter.is_ok then return false
183 return true
184 end
185
186 # Is this string prefixed by `prefix`?
187 #
188 # assert "abcd".has_prefix("ab") == true
189 # assert "abcbc".has_prefix("bc") == false
190 # assert "ab".has_prefix("abcd") == false
191 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
192
193 # Is this string suffixed by `suffix`?
194 #
195 # assert "abcd".has_suffix("abc") == false
196 # assert "abcd".has_suffix("bcd") == true
197 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
198
199 # If `self` contains only digits, return the corresponding integer
200 #
201 # assert "123".to_i == 123
202 # assert "-1".to_i == -1
203 fun to_i: Int
204 do
205 # Shortcut
206 return to_s.to_cstring.atoi
207 end
208
209 # If `self` contains a float, return the corresponding float
210 #
211 # assert "123".to_f == 123.0
212 # assert "-1".to_f == -1.0
213 # assert "-1.2e-3".to_f == -0.0012
214 fun to_f: Float
215 do
216 # Shortcut
217 return to_s.to_cstring.atof
218 end
219
220 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
221 fun to_hex: Int do return a_to(16)
222
223 # If `self` contains only digits and letters, return the corresponding integer in a given base
224 #
225 # assert "120".a_to(3) == 15
226 fun a_to(base: Int) : Int
227 do
228 var i = 0
229 var neg = false
230
231 for c in self.chars
232 do
233 var v = c.to_i
234 if v > base then
235 if neg then
236 return -i
237 else
238 return i
239 end
240 else if v < 0 then
241 neg = true
242 else
243 i = i * base + v
244 end
245 end
246 if neg then
247 return -i
248 else
249 return i
250 end
251 end
252
253 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
254 #
255 # assert "123".is_numeric == true
256 # assert "1.2".is_numeric == true
257 # assert "1,2".is_numeric == true
258 # assert "1..2".is_numeric == false
259 fun is_numeric: Bool
260 do
261 var has_point_or_comma = false
262 for i in self.chars
263 do
264 if not i.is_numeric
265 then
266 if (i == '.' or i == ',') and not has_point_or_comma
267 then
268 has_point_or_comma = true
269 else
270 return false
271 end
272 end
273 end
274 return true
275 end
276
277 # A upper case version of `self`
278 #
279 # assert "Hello World!".to_upper == "HELLO WORLD!"
280 fun to_upper: SELFTYPE is abstract
281
282 # A lower case version of `self`
283 #
284 # assert "Hello World!".to_lower == "hello world!"
285 fun to_lower : SELFTYPE is abstract
286
287 # Removes the whitespaces at the beginning of self
288 fun l_trim: SELFTYPE
289 do
290 var iter = self.chars.iterator
291 while iter.is_ok do
292 if iter.item.ascii > 32 then break
293 iter.next
294 end
295 if iter.index == length then return self.empty
296 return self.substring_from(iter.index)
297 end
298
299 # Removes the whitespaces at the end of self
300 fun r_trim: SELFTYPE
301 do
302 var iter = self.chars.reverse_iterator
303 while iter.is_ok do
304 if iter.item.ascii > 32 then break
305 iter.next
306 end
307 if iter.index == length then return self.empty
308 return self.substring(0, iter.index + 1)
309 end
310
311 # Trims trailing and preceding white spaces
312 # A whitespace is defined as any character which ascii value is less than or equal to 32
313 #
314 # assert " Hello World ! ".trim == "Hello World !"
315 # assert "\na\nb\tc\t".trim == "a\nb\tc"
316 fun trim: SELFTYPE do return (self.l_trim).r_trim
317
318 # Mangle a string to be a unique string only made of alphanumeric characters
319 fun to_cmangle: String
320 do
321 var res = new FlatBuffer
322 var underscore = false
323 for c in self.chars do
324 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
325 res.add(c)
326 underscore = false
327 continue
328 end
329 if underscore then
330 res.append('_'.ascii.to_s)
331 res.add('d')
332 end
333 if c >= '0' and c <= '9' then
334 res.add(c)
335 underscore = false
336 else if c == '_' then
337 res.add(c)
338 underscore = true
339 else
340 res.add('_')
341 res.append(c.ascii.to_s)
342 res.add('d')
343 underscore = false
344 end
345 end
346 return res.to_s
347 end
348
349 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
350 #
351 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
352 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
353 fun escape_to_c: String
354 do
355 var b = new FlatBuffer
356 for c in self.chars do
357 if c == '\n' then
358 b.append("\\n")
359 else if c == '\0' then
360 b.append("\\0")
361 else if c == '"' then
362 b.append("\\\"")
363 else if c == '\'' then
364 b.append("\\\'")
365 else if c == '\\' then
366 b.append("\\\\")
367 else if c.ascii < 32 then
368 b.append("\\{c.ascii.to_base(8, false)}")
369 else
370 b.add(c)
371 end
372 end
373 return b.to_s
374 end
375
376 # Escape additionnal characters
377 # The result might no be legal in C but be used in other languages
378 #
379 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
380 fun escape_more_to_c(chars: String): String
381 do
382 var b = new FlatBuffer
383 for c in escape_to_c do
384 if chars.chars.has(c) then
385 b.add('\\')
386 end
387 b.add(c)
388 end
389 return b.to_s
390 end
391
392 # Escape to c plus braces
393 #
394 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
395 fun escape_to_nit: String do return escape_more_to_c("\{\}")
396
397 # Return a string where Nit escape sequences are transformed.
398 #
399 # Example:
400 # var s = "\\n"
401 # assert s.length == 2
402 # var u = s.unescape_nit
403 # assert u.length == 1
404 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
405 fun unescape_nit: String
406 do
407 var res = new FlatBuffer.with_capacity(self.length)
408 var was_slash = false
409 for c in self do
410 if not was_slash then
411 if c == '\\' then
412 was_slash = true
413 else
414 res.add(c)
415 end
416 continue
417 end
418 was_slash = false
419 if c == 'n' then
420 res.add('\n')
421 else if c == 'r' then
422 res.add('\r')
423 else if c == 't' then
424 res.add('\t')
425 else if c == '0' then
426 res.add('\0')
427 else
428 res.add(c)
429 end
430 end
431 return res.to_s
432 end
433
434 redef fun ==(o)
435 do
436 if o == null then return false
437 if not o isa Text then return false
438 if self.is_same_instance(o) then return true
439 if self.length != o.length then return false
440 return self.chars == o.chars
441 end
442
443 redef fun <(o)
444 do
445 return self.chars < o.chars
446 end
447
448 end
449
450 # All kinds of array-based text representations.
451 abstract class FlatText
452 super Text
453
454 private var items: NativeString
455
456 redef var length: Int
457
458 init do end
459
460 redef fun output
461 do
462 var i = 0
463 while i < length do
464 items[i].output
465 i += 1
466 end
467 end
468 end
469
470 # Abstract class for the SequenceRead compatible
471 # views on String and Buffer objects
472 abstract class StringCharView
473 super SequenceRead[Char]
474 super Comparable
475
476 type SELFTYPE: Text
477
478 redef type OTHER: StringCharView
479
480 private var target: SELFTYPE
481
482 private init(tgt: SELFTYPE)
483 do
484 target = tgt
485 end
486
487 redef fun is_empty do return target.is_empty
488
489 redef fun length do return target.length
490
491 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
492
493 # Gets a new Iterator starting at position `pos`
494 #
495 # Ex :
496 # var iter = "abcd".iterator_from(2)
497 # while iter.is_ok do
498 # printn iter.item
499 # iter.next
500 # end
501 #
502 # Outputs : cd
503 fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
504
505 # Gets an iterator starting at the end and going backwards
506 #
507 # Ex :
508 # var reviter = "now step live...".reverse_iterator
509 # while reviter.is_ok do
510 # printn reviter.item
511 # reviter.next
512 # end
513 #
514 # Outputs : ...evil pets won
515 fun reverse_iterator: IndexedIterator[Char] do return self.reverse_iterator_from(self.length - 1)
516
517 # Gets an iterator on the chars of self starting from `pos`
518 #
519 # Ex :
520 # var iter = "abcd".reverse_iterator_from(1)
521 # while iter.is_ok do
522 # printn iter.item
523 # iter.next
524 # end
525 #
526 # Outputs : ba
527 fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
528
529 redef fun has(c: Char): Bool
530 do
531 for i in self do
532 if i == c then return true
533 end
534 return false
535 end
536
537 redef fun ==(other)
538 do
539 if other == null then return false
540 if not other isa StringCharView then return false
541 var other_chars = other.iterator
542 for i in self do
543 if i != other_chars.item then return false
544 other_chars.next
545 end
546 return true
547 end
548
549 redef fun <(other)
550 do
551 var self_chars = self.iterator
552 var other_chars = other.iterator
553
554 while self_chars.is_ok and other_chars.is_ok do
555 if self_chars.item < other_chars.item then return true
556 if self_chars.item > other_chars.item then return false
557 self_chars.next
558 other_chars.next
559 end
560
561 if self_chars.is_ok then
562 return false
563 else
564 return true
565 end
566 end
567 end
568
569 # View on Buffer objects, extends Sequence
570 # for mutation operations
571 abstract class BufferCharView
572 super StringCharView
573 super Sequence[Char]
574
575 redef type SELFTYPE: Buffer
576
577 end
578
579 # Immutable strings of characters.
580 class String
581 super FlatText
582 super StringCapable
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 StringCapable
944 super Buffer
945
946 redef type SELFVIEW: FlatBufferCharView
947 redef type SELFTYPE: FlatBuffer
948
949 redef var chars: SELFVIEW = new FlatBufferCharView(self)
950
951 var capacity: Int
952
953 redef fun []=(index, item)
954 do
955 if index == length then
956 add(item)
957 return
958 end
959 assert index >= 0 and index < length
960 items[index] = item
961 end
962
963 redef fun add(c)
964 do
965 if capacity <= length then enlarge(length + 5)
966 items[length] = c
967 length += 1
968 end
969
970 redef fun clear do length = 0
971
972 redef fun empty do return new FlatBuffer
973
974 redef fun enlarge(cap)
975 do
976 var c = capacity
977 if cap <= c then return
978 while c <= cap do c = c * 2 + 2
979 var a = calloc_string(c+1)
980 items.copy_to(a, length, 0, 0)
981 items = a
982 capacity = c
983 items.copy_to(a, length, 0, 0)
984 end
985
986 redef fun to_s: String
987 do
988 var l = length
989 var a = calloc_string(l+1)
990 items.copy_to(a, l, 0, 0)
991
992 # Ensure the afterlast byte is '\0' to nul-terminated char *
993 a[length] = '\0'
994
995 return a.to_s_with_length(length)
996 end
997
998 # Create a new empty string.
999 init
1000 do
1001 with_capacity(5)
1002 end
1003
1004 init from(s: String)
1005 do
1006 capacity = s.length + 1
1007 length = s.length
1008 items = calloc_string(capacity)
1009 s.items.copy_to(items, length, s.index_from, 0)
1010 end
1011
1012 # Create a new empty string with a given capacity.
1013 init with_capacity(cap: Int)
1014 do
1015 assert cap >= 0
1016 # _items = new NativeString.calloc(cap)
1017 items = calloc_string(cap+1)
1018 capacity = cap
1019 length = 0
1020 end
1021
1022 redef fun append(s)
1023 do
1024 var sl = s.length
1025 if capacity < length + sl then enlarge(length + sl)
1026 s.items.copy_to(items, sl, s.index_from, length)
1027 length += sl
1028 end
1029
1030 # Copies the content of self in `dest`
1031 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1032 do
1033 var self_chars = self.chars
1034 var dest_chars = dest.chars
1035 for i in [0..len-1] do
1036 dest_chars[new_start+i] = self_chars[start+i]
1037 end
1038 end
1039
1040 redef fun substring(from, count)
1041 do
1042 assert count >= 0
1043 count += from
1044 if from < 0 then from = 0
1045 if count > length then count = length
1046 if from < count then
1047 var r = new FlatBuffer.with_capacity(count - from)
1048 while from < count do
1049 r.chars.push(items[from])
1050 from += 1
1051 end
1052 return r
1053 else
1054 return new FlatBuffer
1055 end
1056 end
1057 end
1058
1059 private class FlatBufferReverseIterator
1060 super IndexedIterator[Char]
1061
1062 var target: FlatBuffer
1063
1064 var target_items: NativeString
1065
1066 var curr_pos: Int
1067
1068 init with_pos(tgt: FlatBuffer, pos: Int)
1069 do
1070 target = tgt
1071 target_items = tgt.items
1072 curr_pos = pos
1073 end
1074
1075 redef fun index do return curr_pos
1076
1077 redef fun is_ok do return curr_pos >= 0
1078
1079 redef fun item do return target_items[curr_pos]
1080
1081 redef fun next do curr_pos -= 1
1082
1083 end
1084
1085 private class FlatBufferCharView
1086 super BufferCharView
1087 super StringCapable
1088
1089 redef type SELFTYPE: FlatBuffer
1090
1091 redef fun [](index) do return target.items[index]
1092
1093 redef fun []=(index, item)
1094 do
1095 assert index >= 0 and index <= length
1096 if index == length then
1097 add(item)
1098 return
1099 end
1100 target.items[index] = item
1101 end
1102
1103 redef fun push(c)
1104 do
1105 target.add(c)
1106 end
1107
1108 redef fun add(c)
1109 do
1110 target.add(c)
1111 end
1112
1113 fun enlarge(cap: Int)
1114 do
1115 target.enlarge(cap)
1116 end
1117
1118 redef fun append(s)
1119 do
1120 var my_items = target.items
1121 var s_length = s.length
1122 if target.capacity < s.length then enlarge(s_length + target.length)
1123 end
1124
1125 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1126
1127 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1128
1129 end
1130
1131 private class FlatBufferIterator
1132 super IndexedIterator[Char]
1133
1134 var target: FlatBuffer
1135
1136 var target_items: NativeString
1137
1138 var curr_pos: Int
1139
1140 init with_pos(tgt: FlatBuffer, pos: Int)
1141 do
1142 target = tgt
1143 target_items = tgt.items
1144 curr_pos = pos
1145 end
1146
1147 redef fun index do return curr_pos
1148
1149 redef fun is_ok do return curr_pos < target.length
1150
1151 redef fun item do return target_items[curr_pos]
1152
1153 redef fun next do curr_pos += 1
1154
1155 end
1156
1157 ###############################################################################
1158 # Refinement #
1159 ###############################################################################
1160
1161 redef class Object
1162 # User readable representation of `self`.
1163 fun to_s: String do return inspect
1164
1165 # The class name of the object in NativeString format.
1166 private fun native_class_name: NativeString is intern
1167
1168 # The class name of the object.
1169 #
1170 # assert 5.class_name == "Int"
1171 fun class_name: String do return native_class_name.to_s
1172
1173 # Developer readable representation of `self`.
1174 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1175 fun inspect: String
1176 do
1177 return "<{inspect_head}>"
1178 end
1179
1180 # Return "CLASSNAME:#OBJECTID".
1181 # This function is mainly used with the redefinition of the inspect method
1182 protected fun inspect_head: String
1183 do
1184 return "{class_name}:#{object_id.to_hex}"
1185 end
1186
1187 protected fun args: Sequence[String]
1188 do
1189 return sys.args
1190 end
1191 end
1192
1193 redef class Bool
1194 # assert true.to_s == "true"
1195 # assert false.to_s == "false"
1196 redef fun to_s
1197 do
1198 if self then
1199 return once "true"
1200 else
1201 return once "false"
1202 end
1203 end
1204 end
1205
1206 redef class Int
1207 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1208 # assume < to_c max const of char
1209 fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1210 do
1211 var n: Int
1212 # Sign
1213 if self < 0 then
1214 n = - self
1215 s.chars[0] = '-'
1216 else if self == 0 then
1217 s.chars[0] = '0'
1218 return
1219 else
1220 n = self
1221 end
1222 # Fill digits
1223 var pos = digit_count(base) - 1
1224 while pos >= 0 and n > 0 do
1225 s.chars[pos] = (n % base).to_c
1226 n = n / base # /
1227 pos -= 1
1228 end
1229 end
1230
1231 # C function to convert an nit Int to a NativeString (char*)
1232 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1233
1234 # return displayable int in base 10 and signed
1235 #
1236 # assert 1.to_s == "1"
1237 # assert (-123).to_s == "-123"
1238 redef fun to_s do
1239 var len = digit_count(10)
1240 return native_int_to_s(len).to_s_with_length(len)
1241 end
1242
1243 # return displayable int in hexadecimal (unsigned (not now))
1244 fun to_hex: String do return to_base(16,false)
1245
1246 # return displayable int in base base and signed
1247 fun to_base(base: Int, signed: Bool): String
1248 do
1249 var l = digit_count(base)
1250 var s = new FlatBuffer.from(" " * l)
1251 fill_buffer(s, base, signed)
1252 return s.to_s
1253 end
1254 end
1255
1256 redef class Float
1257 # Pretty print self, print needoed decimals up to a max of 3.
1258 redef fun to_s do
1259 var str = to_precision( 3 )
1260 if is_inf != 0 or is_nan then return str
1261 var len = str.length
1262 for i in [0..len-1] do
1263 var j = len-1-i
1264 var c = str.chars[j]
1265 if c == '0' then
1266 continue
1267 else if c == '.' then
1268 return str.substring( 0, j+2 )
1269 else
1270 return str.substring( 0, j+1 )
1271 end
1272 end
1273 return str
1274 end
1275
1276 # `self` representation with `nb` digits after the '.'.
1277 fun to_precision(nb: Int): String
1278 do
1279 if is_nan then return "nan"
1280
1281 var isinf = self.is_inf
1282 if isinf == 1 then
1283 return "inf"
1284 else if isinf == -1 then
1285 return "-inf"
1286 end
1287
1288 if nb == 0 then return self.to_i.to_s
1289 var f = self
1290 for i in [0..nb[ do f = f * 10.0
1291 if self > 0.0 then
1292 f = f + 0.5
1293 else
1294 f = f - 0.5
1295 end
1296 var i = f.to_i
1297 if i == 0 then return "0.0"
1298 var s = i.to_s
1299 var sl = s.length
1300 if sl > nb then
1301 var p1 = s.substring(0, s.length-nb)
1302 var p2 = s.substring(s.length-nb, nb)
1303 return p1 + "." + p2
1304 else
1305 return "0." + ("0"*(nb-sl)) + s
1306 end
1307 end
1308
1309 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1310 int size;
1311 char *str;
1312
1313 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1314 str = malloc(size + 1);
1315 sprintf(str, "%.*f", (int)nb, recv );
1316
1317 return NativeString_to_s( str );
1318 `}
1319 end
1320
1321 redef class Char
1322 # assert 'x'.to_s == "x"
1323 redef fun to_s
1324 do
1325 var s = new FlatBuffer.with_capacity(1)
1326 s.chars[0] = self
1327 return s.to_s
1328 end
1329
1330 # Returns true if the char is a numerical digit
1331 fun is_numeric: Bool
1332 do
1333 if self >= '0' and self <= '9'
1334 then
1335 return true
1336 end
1337 return false
1338 end
1339
1340 # Returns true if the char is an alpha digit
1341 fun is_alpha: Bool
1342 do
1343 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1344 return false
1345 end
1346
1347 # Returns true if the char is an alpha or a numeric digit
1348 fun is_alphanumeric: Bool
1349 do
1350 if self.is_numeric or self.is_alpha then return true
1351 return false
1352 end
1353 end
1354
1355 redef class Collection[E]
1356 # Concatenate elements.
1357 redef fun to_s
1358 do
1359 var s = new FlatBuffer
1360 for e in self do if e != null then s.append(e.to_s)
1361 return s.to_s
1362 end
1363
1364 # Concatenate and separate each elements with `sep`.
1365 #
1366 # assert [1, 2, 3].join(":") == "1:2:3"
1367 # assert [1..3].join(":") == "1:2:3"
1368 fun join(sep: String): String
1369 do
1370 if is_empty then return ""
1371
1372 var s = new FlatBuffer # Result
1373
1374 # Concat first item
1375 var i = iterator
1376 var e = i.item
1377 if e != null then s.append(e.to_s)
1378
1379 # Concat other items
1380 i.next
1381 while i.is_ok do
1382 s.append(sep)
1383 e = i.item
1384 if e != null then s.append(e.to_s)
1385 i.next
1386 end
1387 return s.to_s
1388 end
1389 end
1390
1391 redef class Array[E]
1392 # Fast implementation
1393 redef fun to_s
1394 do
1395 var s = new FlatBuffer
1396 var i = 0
1397 var l = length
1398 while i < l do
1399 var e = self[i]
1400 if e != null then s.append(e.to_s)
1401 i += 1
1402 end
1403 return s.to_s
1404 end
1405 end
1406
1407 redef class Map[K,V]
1408 # Concatenate couple of 'key value'.
1409 # key and value are separated by `couple_sep`.
1410 # each couple is separated each couple with `sep`.
1411 #
1412 # var m = new ArrayMap[Int, String]
1413 # m[1] = "one"
1414 # m[10] = "ten"
1415 # assert m.join("; ", "=") == "1=one; 10=ten"
1416 fun join(sep: String, couple_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 k = i.key
1425 var e = i.item
1426 s.append("{k}{couple_sep}{e or else "<null>"}")
1427
1428 # Concat other items
1429 i.next
1430 while i.is_ok do
1431 s.append(sep)
1432 k = i.key
1433 e = i.item
1434 s.append("{k}{couple_sep}{e or else "<null>"}")
1435 i.next
1436 end
1437 return s.to_s
1438 end
1439 end
1440
1441 ###############################################################################
1442 # Native classes #
1443 ###############################################################################
1444
1445 # Native strings are simple C char *
1446 class NativeString
1447 super StringCapable
1448
1449 fun [](index: Int): Char is intern
1450 fun []=(index: Int, item: Char) is intern
1451 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1452
1453 # Position of the first nul character.
1454 fun cstring_length: Int
1455 do
1456 var l = 0
1457 while self[l] != '\0' do l += 1
1458 return l
1459 end
1460 fun atoi: Int is intern
1461 fun atof: Float is extern "atof"
1462
1463 redef fun to_s
1464 do
1465 return to_s_with_length(cstring_length)
1466 end
1467
1468 fun to_s_with_length(length: Int): String
1469 do
1470 assert length >= 0
1471 return new String.with_infos(self, length, 0, length - 1)
1472 end
1473
1474 fun to_s_with_copy: String
1475 do
1476 var length = cstring_length
1477 var new_self = calloc_string(length + 1)
1478 copy_to(new_self, length, 0, 0)
1479 return new String.with_infos(new_self, length, 0, length - 1)
1480 end
1481
1482 end
1483
1484 # StringCapable objects can create native strings
1485 interface StringCapable
1486 protected fun calloc_string(size: Int): NativeString is intern
1487 end
1488
1489 redef class Sys
1490 var _args_cache: nullable Sequence[String]
1491
1492 redef fun args: Sequence[String]
1493 do
1494 if _args_cache == null then init_args
1495 return _args_cache.as(not null)
1496 end
1497
1498 # The name of the program as given by the OS
1499 fun program_name: String
1500 do
1501 return native_argv(0).to_s
1502 end
1503
1504 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1505 private fun init_args
1506 do
1507 var argc = native_argc
1508 var args = new Array[String].with_capacity(0)
1509 var i = 1
1510 while i < argc do
1511 args[i-1] = native_argv(i).to_s
1512 i += 1
1513 end
1514 _args_cache = args
1515 end
1516
1517 # First argument of the main C function.
1518 private fun native_argc: Int is intern
1519
1520 # Second argument of the main C function.
1521 private fun native_argv(i: Int): NativeString is intern
1522 end
1523