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