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