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