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