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