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