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