lib: fixed infinity on floats
[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 has(c: Char): Bool
382 do
383 for i in self do
384 if i == c then return true
385 end
386 return false
387 end
388
389 end
390
391 # View on Buffer objects, extends Sequence
392 # for mutation operations
393 abstract class BufferCharView
394 super StringCharView
395 super Sequence[Char]
396
397 redef type SELFTYPE: Buffer
398
399 end
400
401 # Immutable strings of characters.
402 class String
403 super Comparable
404 super AbstractString
405 super StringCapable
406
407 redef type OTHER: String
408
409 # Index in _items of the start of the string
410 readable var _index_from: Int
411
412 # Indes in _items of the last item of the string
413 readable var _index_to: Int
414
415 redef var chars: StringCharView = new FlatStringCharView(self)
416
417 ################################################
418 # AbstractString specific methods #
419 ################################################
420
421 redef fun [](index) do
422 assert index >= 0
423 # Check that the index (+ index_from) is not larger than indexTo
424 # In other terms, if the index is valid
425 assert (index + _index_from) <= _index_to
426 return _items[index + _index_from]
427 end
428
429 redef fun substring(from: Int, count: Int): String
430 do
431 assert count >= 0
432
433 if from < 0 then
434 count += from
435 if count < 0 then count = 0
436 from = 0
437 end
438
439 var realFrom = _index_from + from
440
441 if (realFrom + count) > _index_to then return new String.with_infos(_items, _index_to - realFrom + 1, realFrom, _index_to)
442
443 if count == 0 then return ""
444
445 var to = realFrom + count - 1
446
447 return new String.with_infos(_items, to - realFrom + 1, realFrom, to)
448 end
449
450 redef fun substring_from(from: Int): String
451 do
452 if from > _length then return ""
453 if from < 0 then from = 0
454 return substring(from, _length)
455 end
456
457 redef fun has_substring(str: String, pos: Int): Bool
458 do
459 var itsindex = str._length - 1
460
461 var myindex = pos + itsindex
462 var myitems = _items
463
464 var itsitems = str._items
465
466 if myindex > _length or itsindex > myindex then return false
467
468 var itsindexfrom = str.index_from
469 itsindex += itsindexfrom
470 myindex += index_from
471
472 while itsindex >= itsindexfrom do
473 if myitems[myindex] != itsitems[itsindex] then return false
474 myindex -= 1
475 itsindex -= 1
476 end
477
478 return true
479 end
480
481 redef fun to_upper: String
482 do
483 var outstr = calloc_string(self._length + 1)
484 var out_index = 0
485
486 var myitems = self._items
487 var index_from = self._index_from
488 var max = self._index_to
489
490 while index_from <= max do
491 outstr[out_index] = myitems[index_from].to_upper
492 out_index += 1
493 index_from += 1
494 end
495
496 outstr[self.length] = '\0'
497
498 return outstr.to_s_with_length(self._length)
499 end
500
501 redef fun to_lower : String
502 do
503 var outstr = calloc_string(self._length + 1)
504 var out_index = 0
505
506 var myitems = self._items
507 var index_from = self._index_from
508 var max = self._index_to
509
510 while index_from <= max do
511 outstr[out_index] = myitems[index_from].to_lower
512 out_index += 1
513 index_from += 1
514 end
515
516 outstr[self.length] = '\0'
517
518 return outstr.to_s_with_length(self._length)
519 end
520
521 redef fun trim: String
522 do
523 if self._length == 0 then return self
524 # find position of the first non white space char (ascii < 32) from the start of the string
525 var start_pos = self._index_from
526 while _items[start_pos].ascii <= 32 do
527 start_pos += 1
528 if start_pos == _index_to + 1 then return ""
529 end
530 # find position of the first non white space char from the end of the string
531 var end_pos = _index_to
532 while _items[end_pos].ascii <= 32 do
533 end_pos -= 1
534 if end_pos == start_pos then return _items[start_pos].to_s
535 end
536 start_pos -= index_from
537 end_pos -= index_from
538 return self.substring(start_pos, end_pos - start_pos + 1)
539 end
540
541 redef fun output
542 do
543 var i = self._index_from
544 var imax = self._index_to
545 while i <= imax do
546 _items[i].output
547 i += 1
548 end
549 end
550
551 ##################################################
552 # String Specific Methods #
553 ##################################################
554
555 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
556 do
557 self._items = items
558 _length = len
559 _index_from = from
560 _index_to = to
561 end
562
563 # Return a null terminated char *
564 fun to_cstring: NativeString
565 do
566 if _index_from > 0 or _index_to != items.cstring_length - 1 then
567 var newItems = calloc_string(_length + 1)
568 self.items.copy_to(newItems, _length, _index_from, 0)
569 newItems[length] = '\0'
570 return newItems
571 end
572 return _items
573 end
574
575 redef fun ==(other)
576 do
577 if not other isa String then return false
578
579 if self.object_id == other.object_id then return true
580
581 var my_length = _length
582
583 if other._length != my_length then return false
584
585 var my_index = _index_from
586 var its_index = other._index_from
587
588 var last_iteration = my_index + my_length
589
590 var itsitems = other._items
591 var myitems = self._items
592
593 while my_index < last_iteration do
594 if myitems[my_index] != itsitems[its_index] then return false
595 my_index += 1
596 its_index += 1
597 end
598
599 return true
600 end
601
602 # The comparison between two strings is done on a lexicographical basis
603 #
604 # assert ("aa" < "b") == true
605 redef fun <(other)
606 do
607 if self.object_id == other.object_id then return false
608
609 var my_curr_char : Char
610 var its_curr_char : Char
611
612 var curr_id_self = self._index_from
613 var curr_id_other = other._index_from
614
615 var my_items = self._items
616 var its_items = other._items
617
618 var my_length = self._length
619 var its_length = other._length
620
621 var max_iterations = curr_id_self + my_length
622
623 while curr_id_self < max_iterations do
624 my_curr_char = my_items[curr_id_self]
625 its_curr_char = its_items[curr_id_other]
626
627 if my_curr_char != its_curr_char then
628 if my_curr_char < its_curr_char then return true
629 return false
630 end
631
632 curr_id_self += 1
633 curr_id_other += 1
634 end
635
636 return my_length < its_length
637 end
638
639 # The concatenation of `self` with `s`
640 #
641 # assert "hello " + "world!" == "hello world!"
642 fun +(s: String): String
643 do
644 var my_length = self._length
645 var its_length = s._length
646
647 var total_length = my_length + its_length
648
649 var target_string = calloc_string(my_length + its_length + 1)
650
651 self._items.copy_to(target_string, my_length, _index_from, 0)
652 s._items.copy_to(target_string, its_length, s._index_from, my_length)
653
654 target_string[total_length] = '\0'
655
656 return target_string.to_s_with_length(total_length)
657 end
658
659 # `i` repetitions of `self`
660 #
661 # assert "abc"*3 == "abcabcabc"
662 # assert "abc"*1 == "abc"
663 # assert "abc"*0 == ""
664 fun *(i: Int): String
665 do
666 assert i >= 0
667
668 var my_length = self._length
669
670 var final_length = my_length * i
671
672 var my_items = self._items
673
674 var target_string = calloc_string((final_length) + 1)
675
676 target_string[final_length] = '\0'
677
678 var current_last = 0
679
680 for iteration in [1 .. i] do
681 my_items.copy_to(target_string, my_length, 0, current_last)
682 current_last += my_length
683 end
684
685 return target_string.to_s_with_length(final_length)
686 end
687
688 redef fun to_s do return self
689
690 redef fun hash
691 do
692 # djb2 hash algorythm
693 var h = 5381
694 var i = _length - 1
695
696 var myitems = _items
697 var strStart = _index_from
698
699 i += strStart
700
701 while i >= strStart do
702 h = (h * 32) + h + self._items[i].ascii
703 i -= 1
704 end
705
706 return h
707 end
708 end
709
710 private class FlatStringIterator
711 super IndexedIterator[Char]
712
713 var target: String
714
715 var target_items: NativeString
716
717 var curr_pos: Int
718
719 init with_pos(tgt: String, pos: Int)
720 do
721 target = tgt
722 target_items = tgt.items
723 curr_pos = pos + target.index_from
724 end
725
726 redef fun is_ok do return curr_pos <= target.index_to
727
728 redef fun item do return target_items[curr_pos]
729
730 redef fun next do curr_pos += 1
731
732 redef fun index do return curr_pos - target.index_from
733
734 end
735
736 private class FlatStringCharView
737 super StringCharView
738
739 redef type SELFTYPE: String
740
741 redef fun [](index)
742 do
743 # Check that the index (+ index_from) is not larger than indexTo
744 # In other terms, if the index is valid
745 assert index >= 0
746 assert (index + target._index_from) <= target._index_to
747 return target._items[index + target._index_from]
748 end
749
750 redef fun iterator: IndexedIterator[Char] do return new FlatStringIterator.with_pos(target, 0)
751
752 end
753
754 # Mutable strings of characters.
755 class Buffer
756 super AbstractString
757 super Comparable
758 super StringCapable
759 super AbstractArray[Char]
760
761 redef type OTHER: String
762
763 redef var chars: BufferCharView = new FlatBufferCharView(self)
764
765 redef fun []=(index, item)
766 do
767 if index == length then
768 add(item)
769 return
770 end
771 assert index >= 0 and index < length
772 _items[index] = item
773 end
774
775 redef fun add(c)
776 do
777 if _capacity <= length then enlarge(length + 5)
778 _items[length] = c
779 _length += 1
780 end
781
782 redef fun enlarge(cap)
783 do
784 var c = _capacity
785 if cap <= c then return
786 while c <= cap do c = c * 2 + 2
787 var a = calloc_string(c+1)
788 _items.copy_to(a, length, 0, 0)
789 _items = a
790 _capacity = c
791 end
792
793 redef fun append(s)
794 do
795 if s isa String then
796 var sl = s.length
797 if _capacity < _length + sl then enlarge(_length + sl)
798 s.items.copy_to(_items, sl, s._index_from, _length)
799 _length += sl
800 else
801 super
802 end
803 end
804
805 redef fun to_s: String
806 do
807 var l = length
808 var a = calloc_string(l+1)
809 _items.copy_to(a, l, 0, 0)
810
811 # Ensure the afterlast byte is '\0' to nul-terminated char *
812 a[length] = '\0'
813
814 return a.to_s_with_length(length)
815 end
816
817 redef fun <(s)
818 do
819 var i = 0
820 var l1 = length
821 var l2 = s.length
822 while i < l1 and i < l2 do
823 var c1 = self.chars[i].ascii
824 var c2 = s.chars[i].ascii
825 if c1 < c2 then
826 return true
827 else if c2 < c1 then
828 return false
829 end
830 i += 1
831 end
832 if l1 < l2 then
833 return true
834 else
835 return false
836 end
837 end
838
839 # Create a new empty string.
840 init
841 do
842 with_capacity(5)
843 end
844
845 init from(s: String)
846 do
847 _capacity = s.length + 1
848 _length = s.length
849 _items = calloc_string(_capacity)
850 s.items.copy_to(_items, _length, s._index_from, 0)
851 end
852
853 # Create a new empty string with a given capacity.
854 init with_capacity(cap: Int)
855 do
856 assert cap >= 0
857 # _items = new NativeString.calloc(cap)
858 _items = calloc_string(cap+1)
859 _capacity = cap
860 _length = 0
861 end
862
863 redef fun ==(o)
864 do
865 if not o isa Buffer then return false
866 var l = length
867 if o.length != l then return false
868 var i = 0
869 var it = _items
870 var oit = o._items
871 while i < l do
872 if it[i] != oit[i] then return false
873 i += 1
874 end
875 return true
876 end
877
878 readable private var _capacity: Int
879 end
880
881 private class FlatBufferCharView
882 super BufferCharView
883 super StringCapable
884
885 redef type SELFTYPE: Buffer
886
887 redef fun [](index) do return target._items[index]
888
889 redef fun []=(index, item)
890 do
891 assert index >= 0 and index <= length
892 if index == length then
893 add(item)
894 return
895 end
896 target._items[index] = item
897 end
898
899 redef fun push(c)
900 do
901 target.add(c)
902 end
903
904 redef fun add(c)
905 do
906 target.add(c)
907 end
908
909 fun enlarge(cap: Int)
910 do
911 target.enlarge(cap)
912 end
913
914 redef fun append(s)
915 do
916 var my_items = target.items
917 var s_length = s.length
918 if target.capacity < s.length then enlarge(s_length + target.length)
919 end
920
921 redef fun iterator: IndexedIterator[Char] do return new FlatBufferIterator.with_pos(target, 0)
922
923 end
924
925 private class FlatBufferIterator
926 super IndexedIterator[Char]
927
928 var target: Buffer
929
930 var target_items: NativeString
931
932 var curr_pos: Int
933
934 init with_pos(tgt: Buffer, pos: Int)
935 do
936 target = tgt
937 target_items = tgt.items
938 curr_pos = pos
939 end
940
941 redef fun index do return curr_pos
942
943 redef fun is_ok do return curr_pos < target.length
944
945 redef fun item do return target_items[curr_pos]
946
947 redef fun next do curr_pos += 1
948
949 end
950
951 ###############################################################################
952 # Refinement #
953 ###############################################################################
954
955 redef class Object
956 # User readable representation of `self`.
957 fun to_s: String do return inspect
958
959 # The class name of the object in NativeString format.
960 private fun native_class_name: NativeString is intern
961
962 # The class name of the object.
963 #
964 # assert 5.class_name == "Int"
965 fun class_name: String do return native_class_name.to_s
966
967 # Developer readable representation of `self`.
968 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
969 fun inspect: String
970 do
971 return "<{inspect_head}>"
972 end
973
974 # Return "CLASSNAME:#OBJECTID".
975 # This function is mainly used with the redefinition of the inspect method
976 protected fun inspect_head: String
977 do
978 return "{class_name}:#{object_id.to_hex}"
979 end
980
981 protected fun args: Sequence[String]
982 do
983 return sys.args
984 end
985 end
986
987 redef class Bool
988 # assert true.to_s == "true"
989 # assert false.to_s == "false"
990 redef fun to_s
991 do
992 if self then
993 return once "true"
994 else
995 return once "false"
996 end
997 end
998 end
999
1000 redef class Int
1001 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1002 # assume < to_c max const of char
1003 fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1004 do
1005 var n: Int
1006 # Sign
1007 if self < 0 then
1008 n = - self
1009 s.chars[0] = '-'
1010 else if self == 0 then
1011 s.chars[0] = '0'
1012 return
1013 else
1014 n = self
1015 end
1016 # Fill digits
1017 var pos = digit_count(base) - 1
1018 while pos >= 0 and n > 0 do
1019 s.chars[pos] = (n % base).to_c
1020 n = n / base # /
1021 pos -= 1
1022 end
1023 end
1024
1025 # C function to convert an nit Int to a NativeString (char*)
1026 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1027
1028 # return displayable int in base 10 and signed
1029 #
1030 # assert 1.to_s == "1"
1031 # assert (-123).to_s == "-123"
1032 redef fun to_s do
1033 var len = digit_count(10)
1034 return native_int_to_s(len).to_s_with_length(len)
1035 end
1036
1037 # return displayable int in hexadecimal (unsigned (not now))
1038 fun to_hex: String do return to_base(16,false)
1039
1040 # return displayable int in base base and signed
1041 fun to_base(base: Int, signed: Bool): String
1042 do
1043 var l = digit_count(base)
1044 var s = new Buffer.from(" " * l)
1045 fill_buffer(s, base, signed)
1046 return s.to_s
1047 end
1048 end
1049
1050 redef class Float
1051 # Pretty print self, print needoed decimals up to a max of 3.
1052 redef fun to_s do
1053 var str = to_precision( 3 )
1054 var len = str.length
1055 for i in [0..len-1] do
1056 var j = len-1-i
1057 var c = str.chars[j]
1058 if c == '0' then
1059 continue
1060 else if c == '.' then
1061 return str.substring( 0, j+2 )
1062 else
1063 return str.substring( 0, j+1 )
1064 end
1065 end
1066 return str
1067 end
1068
1069 # `self` representation with `nb` digits after the '.'.
1070 fun to_precision(nb: Int): String
1071 do
1072 var isinf = self.is_inf
1073 if isinf == 1 then
1074 return "inf"
1075 else if isinf == -1 then
1076 return "-inf"
1077 end
1078
1079 if nb == 0 then return self.to_i.to_s
1080 var f = self
1081 for i in [0..nb[ do f = f * 10.0
1082 if self > 0.0 then
1083 f = f + 0.5
1084 else
1085 f = f - 0.5
1086 end
1087 var i = f.to_i
1088 if i == 0 then return "0.0"
1089 var s = i.to_s
1090 var sl = s.length
1091 if sl > nb then
1092 var p1 = s.substring(0, s.length-nb)
1093 var p2 = s.substring(s.length-nb, nb)
1094 return p1 + "." + p2
1095 else
1096 return "0." + ("0"*(nb-sl)) + s
1097 end
1098 end
1099
1100 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1101 int size;
1102 char *str;
1103
1104 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1105 str = malloc(size + 1);
1106 sprintf(str, "%.*f", (int)nb, recv );
1107
1108 return NativeString_to_s( str );
1109 `}
1110 end
1111
1112 redef class Char
1113 # assert 'x'.to_s == "x"
1114 redef fun to_s
1115 do
1116 var s = new Buffer.with_capacity(1)
1117 s.chars[0] = self
1118 return s.to_s
1119 end
1120
1121 # Returns true if the char is a numerical digit
1122 fun is_numeric: Bool
1123 do
1124 if self >= '0' and self <= '9'
1125 then
1126 return true
1127 end
1128 return false
1129 end
1130
1131 # Returns true if the char is an alpha digit
1132 fun is_alpha: Bool
1133 do
1134 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1135 return false
1136 end
1137
1138 # Returns true if the char is an alpha or a numeric digit
1139 fun is_alphanumeric: Bool
1140 do
1141 if self.is_numeric or self.is_alpha then return true
1142 return false
1143 end
1144 end
1145
1146 redef class Collection[E]
1147 # Concatenate elements.
1148 redef fun to_s
1149 do
1150 var s = new Buffer
1151 for e in self do if e != null then s.append(e.to_s)
1152 return s.to_s
1153 end
1154
1155 # Concatenate and separate each elements with `sep`.
1156 #
1157 # assert [1, 2, 3].join(":") == "1:2:3"
1158 # assert [1..3].join(":") == "1:2:3"
1159 fun join(sep: String): String
1160 do
1161 if is_empty then return ""
1162
1163 var s = new Buffer # Result
1164
1165 # Concat first item
1166 var i = iterator
1167 var e = i.item
1168 if e != null then s.append(e.to_s)
1169
1170 # Concat other items
1171 i.next
1172 while i.is_ok do
1173 s.append(sep)
1174 e = i.item
1175 if e != null then s.append(e.to_s)
1176 i.next
1177 end
1178 return s.to_s
1179 end
1180 end
1181
1182 redef class Array[E]
1183 # Fast implementation
1184 redef fun to_s
1185 do
1186 var s = new Buffer
1187 var i = 0
1188 var l = length
1189 while i < l do
1190 var e = self[i]
1191 if e != null then s.append(e.to_s)
1192 i += 1
1193 end
1194 return s.to_s
1195 end
1196 end
1197
1198 redef class Map[K,V]
1199 # Concatenate couple of 'key value'.
1200 # key and value are separated by `couple_sep`.
1201 # each couple is separated each couple with `sep`.
1202 #
1203 # var m = new ArrayMap[Int, String]
1204 # m[1] = "one"
1205 # m[10] = "ten"
1206 # assert m.join("; ", "=") == "1=one; 10=ten"
1207 fun join(sep: String, couple_sep: String): String
1208 do
1209 if is_empty then return ""
1210
1211 var s = new Buffer # Result
1212
1213 # Concat first item
1214 var i = iterator
1215 var k = i.key
1216 var e = i.item
1217 s.append("{k}{couple_sep}{e or else "<null>"}")
1218
1219 # Concat other items
1220 i.next
1221 while i.is_ok do
1222 s.append(sep)
1223 k = i.key
1224 e = i.item
1225 s.append("{k}{couple_sep}{e or else "<null>"}")
1226 i.next
1227 end
1228 return s.to_s
1229 end
1230 end
1231
1232 ###############################################################################
1233 # Native classes #
1234 ###############################################################################
1235
1236 # Native strings are simple C char *
1237 class NativeString
1238 super StringCapable
1239
1240 fun [](index: Int): Char is intern
1241 fun []=(index: Int, item: Char) is intern
1242 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1243
1244 # Position of the first nul character.
1245 fun cstring_length: Int
1246 do
1247 var l = 0
1248 while self[l] != '\0' do l += 1
1249 return l
1250 end
1251 fun atoi: Int is intern
1252 fun atof: Float is extern "atof"
1253
1254 redef fun to_s
1255 do
1256 return to_s_with_length(cstring_length)
1257 end
1258
1259 fun to_s_with_length(length: Int): String
1260 do
1261 assert length >= 0
1262 return new String.with_infos(self, length, 0, length - 1)
1263 end
1264
1265 fun to_s_with_copy: String
1266 do
1267 var length = cstring_length
1268 var new_self = calloc_string(length + 1)
1269 copy_to(new_self, length, 0, 0)
1270 return new String.with_infos(new_self, length, 0, length - 1)
1271 end
1272
1273 end
1274
1275 # StringCapable objects can create native strings
1276 interface StringCapable
1277 protected fun calloc_string(size: Int): NativeString is intern
1278 end
1279
1280 redef class Sys
1281 var _args_cache: nullable Sequence[String]
1282
1283 redef fun args: Sequence[String]
1284 do
1285 if _args_cache == null then init_args
1286 return _args_cache.as(not null)
1287 end
1288
1289 # The name of the program as given by the OS
1290 fun program_name: String
1291 do
1292 return native_argv(0).to_s
1293 end
1294
1295 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1296 private fun init_args
1297 do
1298 var argc = native_argc
1299 var args = new Array[String].with_capacity(0)
1300 var i = 1
1301 while i < argc do
1302 args[i-1] = native_argv(i).to_s
1303 i += 1
1304 end
1305 _args_cache = args
1306 end
1307
1308 # First argument of the main C function.
1309 private fun native_argc: Int is intern
1310
1311 # Second argument of the main C function.
1312 private fun native_argv(i: Int): NativeString is intern
1313 end
1314