5a0c03974f95365bc1a8789c7f5053359de18401
[nit.git] / lib / standard / string.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Basic manipulations of strings of characters
15 module string
16
17 import math
18 import collection
19
20 `{
21 #include <stdio.h>
22 #include <string.h>
23 `}
24
25 ###############################################################################
26 # String #
27 ###############################################################################
28
29 # High-level abstraction for all text representations
30 abstract class Text
31 super Comparable
32 super StringCapable
33
34 redef type OTHER: Text
35
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
37 type SELFTYPE: Text
38
39 # Gets a view on the chars of the Text object
40 #
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars: SequenceRead[Char] is abstract
43
44 # Number of characters contained in self.
45 #
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length: Int is abstract
49
50 # Create a substring.
51 #
52 # assert "abcd".substring(1, 2) == "bc"
53 # assert "abcd".substring(-1, 2) == "a"
54 # assert "abcd".substring(1, 0) == ""
55 # assert "abcd".substring(2, 5) == "cd"
56 #
57 # A `from` index < 0 will be replaced by 0.
58 # Unless a `count` value is > 0 at the same time.
59 # In this case, `from += count` and `count -= from`.
60 fun substring(from: Int, count: Int): SELFTYPE is abstract
61
62 # Iterates on the substrings of self if any
63 fun substrings: Iterator[Text] is abstract
64
65 # Is the current Text empty (== "")
66 #
67 # assert "".is_empty
68 # assert not "foo".is_empty
69 fun is_empty: Bool do return self.length == 0
70
71 # Returns an empty Text of the right type
72 #
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty: SELFTYPE is abstract
76
77 # Gets the first char of the Text
78 #
79 # DEPRECATED : Use self.chars.first instead
80 fun first: Char do return self.chars[0]
81
82 # Access a character at `index` in the string.
83 #
84 # assert "abcd"[2] == 'c'
85 #
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index: Int): Char do return self.chars[index]
88
89 # Gets the index of the first occurence of 'c'
90 #
91 # Returns -1 if not found
92 #
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of(c: Char): Int
95 do
96 return index_of_from(c, 0)
97 end
98
99 # Gets the last char of self
100 #
101 # DEPRECATED : Use self.chars.last instead
102 fun last: Char do return self.chars[length-1]
103
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
105 #
106 # Returns -1 if not found
107 #
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from(c: Char, pos: Int): Int
110 do
111 var iter = self.chars.iterator_from(pos)
112 while iter.is_ok do
113 if iter.item == c then return iter.index
114 iter.next
115 end
116 return -1
117 end
118
119 # Gets the last index of char ´c´
120 #
121 # Returns -1 if not found
122 #
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of(c: Char): Int
125 do
126 return last_index_of_from(c, length - 1)
127 end
128
129 # Return a null terminated char *
130 fun to_cstring: NativeString do return flatten.to_cstring
131
132 # The index of the last occurrence of an element starting from pos (in reverse order).
133 #
134 # var s = "/etc/bin/test/test.nit"
135 # assert s.last_index_of_from('/', s.length-1) == 13
136 # assert s.last_index_of_from('/', 12) == 8
137 #
138 # Returns -1 if not found
139 #
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from(item: Char, pos: Int): Int
142 do
143 var iter = self.chars.reverse_iterator_from(pos)
144 while iter.is_ok do
145 if iter.item == item then return iter.index
146 iter.next
147 end
148 return -1
149 end
150
151 # Gets an iterator on the chars of self
152 #
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator: Iterator[Char]
155 do
156 return self.chars.iterator
157 end
158
159 # Is 'c' contained in self ?
160 #
161 # DEPRECATED : Use self.chars.has instead
162 fun has(c: Char): Bool
163 do
164 return self.chars.has(c)
165 end
166
167 # Gets an Array containing the chars of self
168 #
169 # DEPRECATED : Use self.chars.to_a instead
170 fun to_a: Array[Char] do return chars.to_a
171
172 # Create a substring from `self` beginning at the `from` position
173 #
174 # assert "abcd".substring_from(1) == "bcd"
175 # assert "abcd".substring_from(-1) == "abcd"
176 # assert "abcd".substring_from(2) == "cd"
177 #
178 # As with substring, a `from` index < 0 will be replaced by 0
179 fun substring_from(from: Int): SELFTYPE
180 do
181 if from > self.length then return empty
182 if from < 0 then from = 0
183 return substring(from, length - from)
184 end
185
186 # Does self have a substring `str` starting from position `pos`?
187 #
188 # assert "abcd".has_substring("bc",1) == true
189 # assert "abcd".has_substring("bc",2) == false
190 fun has_substring(str: String, pos: Int): Bool
191 do
192 var myiter = self.chars.iterator_from(pos)
193 var itsiter = str.chars.iterator
194 while myiter.is_ok and itsiter.is_ok do
195 if myiter.item != itsiter.item then return false
196 myiter.next
197 itsiter.next
198 end
199 if itsiter.is_ok then return false
200 return true
201 end
202
203 # Is this string prefixed by `prefix`?
204 #
205 # assert "abcd".has_prefix("ab") == true
206 # assert "abcbc".has_prefix("bc") == false
207 # assert "ab".has_prefix("abcd") == false
208 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
209
210 # Is this string suffixed by `suffix`?
211 #
212 # assert "abcd".has_suffix("abc") == false
213 # assert "abcd".has_suffix("bcd") == true
214 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
215
216 # If `self` contains only digits, return the corresponding integer
217 #
218 # assert "123".to_i == 123
219 # assert "-1".to_i == -1
220 fun to_i: Int
221 do
222 # Shortcut
223 return to_s.to_cstring.atoi
224 end
225
226 # If `self` contains a float, return the corresponding float
227 #
228 # assert "123".to_f == 123.0
229 # assert "-1".to_f == -1.0
230 # assert "-1.2e-3".to_f == -0.0012
231 fun to_f: Float
232 do
233 # Shortcut
234 return to_s.to_cstring.atof
235 end
236
237 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
238 #
239 # assert "ff".to_hex == 255
240 fun to_hex: Int do return a_to(16)
241
242 # If `self` contains only digits and letters, return the corresponding integer in a given base
243 #
244 # assert "120".a_to(3) == 15
245 fun a_to(base: Int) : Int
246 do
247 var i = 0
248 var neg = false
249
250 for j in [0..length[ do
251 var c = chars[j]
252 var v = c.to_i
253 if v > base then
254 if neg then
255 return -i
256 else
257 return i
258 end
259 else if v < 0 then
260 neg = true
261 else
262 i = i * base + v
263 end
264 end
265 if neg then
266 return -i
267 else
268 return i
269 end
270 end
271
272 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
273 #
274 # assert "123".is_numeric == true
275 # assert "1.2".is_numeric == true
276 # assert "1,2".is_numeric == true
277 # assert "1..2".is_numeric == false
278 fun is_numeric: Bool
279 do
280 var has_point_or_comma = false
281 for i in [0..length[ do
282 var c = chars[i]
283 if not c.is_numeric then
284 if (c == '.' or c == ',') and not has_point_or_comma then
285 has_point_or_comma = true
286 else
287 return false
288 end
289 end
290 end
291 return true
292 end
293
294 # Returns `true` if the string contains only Hex chars
295 #
296 # assert "048bf".is_hex == true
297 # assert "ABCDEF".is_hex == true
298 # assert "0G".is_hex == false
299 fun is_hex: Bool
300 do
301 for i in [0..length[ do
302 var c = chars[i]
303 if not (c >= 'a' and c <= 'f') and
304 not (c >= 'A' and c <= 'F') and
305 not (c >= '0' and c <= '9') then return false
306 end
307 return true
308 end
309
310 # Are all letters in `self` upper-case ?
311 #
312 # assert "HELLO WORLD".is_upper == true
313 # assert "%$&%!".is_upper == true
314 # assert "hello world".is_upper == false
315 # assert "Hello World".is_upper == false
316 fun is_upper: Bool
317 do
318 for i in [0..length[ do
319 var char = chars[i]
320 if char.is_lower then return false
321 end
322 return true
323 end
324
325 # Are all letters in `self` lower-case ?
326 #
327 # assert "hello world".is_lower == true
328 # assert "%$&%!".is_lower == true
329 # assert "Hello World".is_lower == false
330 fun is_lower: Bool
331 do
332 for i in [0..length[ do
333 var char = chars[i]
334 if char.is_upper then return false
335 end
336 return true
337 end
338
339 # Removes the whitespaces at the beginning of self
340 #
341 # assert " \n\thello \n\t".l_trim == "hello \n\t"
342 #
343 # A whitespace is defined as any character which ascii value is less than or equal to 32
344 fun l_trim: SELFTYPE
345 do
346 var iter = self.chars.iterator
347 while iter.is_ok do
348 if iter.item.ascii > 32 then break
349 iter.next
350 end
351 if iter.index == length then return self.empty
352 return self.substring_from(iter.index)
353 end
354
355 # Removes the whitespaces at the end of self
356 #
357 # assert " \n\thello \n\t".r_trim == " \n\thello"
358 #
359 # A whitespace is defined as any character which ascii value is less than or equal to 32
360 fun r_trim: SELFTYPE
361 do
362 var iter = self.chars.reverse_iterator
363 while iter.is_ok do
364 if iter.item.ascii > 32 then break
365 iter.next
366 end
367 if iter.index == length then return self.empty
368 return self.substring(0, iter.index + 1)
369 end
370
371 # Trims trailing and preceding white spaces
372 # A whitespace is defined as any character which ascii value is less than or equal to 32
373 #
374 # assert " Hello World ! ".trim == "Hello World !"
375 # assert "\na\nb\tc\t".trim == "a\nb\tc"
376 fun trim: SELFTYPE do return (self.l_trim).r_trim
377
378 # Mangle a string to be a unique string only made of alphanumeric characters
379 fun to_cmangle: String
380 do
381 var res = new FlatBuffer
382 var underscore = false
383 for i in [0..length[ do
384 var c = chars[i]
385 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
386 res.add(c)
387 underscore = false
388 continue
389 end
390 if underscore then
391 res.append('_'.ascii.to_s)
392 res.add('d')
393 end
394 if c >= '0' and c <= '9' then
395 res.add(c)
396 underscore = false
397 else if c == '_' then
398 res.add(c)
399 underscore = true
400 else
401 res.add('_')
402 res.append(c.ascii.to_s)
403 res.add('d')
404 underscore = false
405 end
406 end
407 return res.to_s
408 end
409
410 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
411 #
412 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
413 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
414 fun escape_to_c: String
415 do
416 var b = new FlatBuffer
417 for i in [0..length[ do
418 var c = chars[i]
419 if c == '\n' then
420 b.append("\\n")
421 else if c == '\0' then
422 b.append("\\0")
423 else if c == '"' then
424 b.append("\\\"")
425 else if c == '\'' then
426 b.append("\\\'")
427 else if c == '\\' then
428 b.append("\\\\")
429 else if c.ascii < 32 then
430 b.append("\\{c.ascii.to_base(8, false)}")
431 else
432 b.add(c)
433 end
434 end
435 return b.to_s
436 end
437
438 # Escape additionnal characters
439 # The result might no be legal in C but be used in other languages
440 #
441 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
442 fun escape_more_to_c(chars: String): String
443 do
444 var b = new FlatBuffer
445 for c in escape_to_c.chars do
446 if chars.chars.has(c) then
447 b.add('\\')
448 end
449 b.add(c)
450 end
451 return b.to_s
452 end
453
454 # Escape to C plus braces
455 #
456 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
457 fun escape_to_nit: String do return escape_more_to_c("\{\}")
458
459 # Return a string where Nit escape sequences are transformed.
460 #
461 # var s = "\\n"
462 # assert s.length == 2
463 # var u = s.unescape_nit
464 # assert u.length == 1
465 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
466 fun unescape_nit: String
467 do
468 var res = new FlatBuffer.with_capacity(self.length)
469 var was_slash = false
470 for i in [0..length[ do
471 var c = chars[i]
472 if not was_slash then
473 if c == '\\' then
474 was_slash = true
475 else
476 res.add(c)
477 end
478 continue
479 end
480 was_slash = false
481 if c == 'n' then
482 res.add('\n')
483 else if c == 'r' then
484 res.add('\r')
485 else if c == 't' then
486 res.add('\t')
487 else if c == '0' then
488 res.add('\0')
489 else
490 res.add(c)
491 end
492 end
493 return res.to_s
494 end
495
496 # Encode `self` to percent (or URL) encoding
497 #
498 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
499 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
500 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
501 fun to_percent_encoding: String
502 do
503 var buf = new FlatBuffer
504
505 for i in [0..length[ do
506 var c = chars[i]
507 if (c >= '0' and c <= '9') or
508 (c >= 'a' and c <= 'z') or
509 (c >= 'A' and c <= 'Z') or
510 c == '-' or c == '.' or
511 c == '_' or c == '~'
512 then
513 buf.add c
514 else buf.append "%{c.ascii.to_hex}"
515 end
516
517 return buf.to_s
518 end
519
520 # Decode `self` from percent (or URL) encoding to a clear string
521 #
522 # Replace invalid use of '%' with '?'.
523 #
524 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
525 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
526 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
527 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
528 # assert "incomplete %".from_percent_encoding == "incomplete ?"
529 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
530 fun from_percent_encoding: String
531 do
532 var buf = new FlatBuffer
533
534 var i = 0
535 while i < length do
536 var c = chars[i]
537 if c == '%' then
538 if i + 2 >= length then
539 # What follows % has been cut off
540 buf.add '?'
541 else
542 i += 1
543 var hex_s = substring(i, 2)
544 if hex_s.is_hex then
545 var hex_i = hex_s.to_hex
546 buf.add hex_i.ascii
547 i += 1
548 else
549 # What follows a % is not Hex
550 buf.add '?'
551 i -= 1
552 end
553 end
554 else buf.add c
555
556 i += 1
557 end
558
559 return buf.to_s
560 end
561
562 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
563 #
564 # assert "a&b->\"x\"".html_escape == "a&amp;b-&gt;&quot;x&quot;"
565 fun html_escape: SELFTYPE
566 do
567 var buf = new FlatBuffer
568
569 for i in [0..length[ do
570 var c = chars[i]
571 if c == '&' then
572 buf.append "&amp;"
573 else if c == '<' then
574 buf.append "&lt;"
575 else if c == '>' then
576 buf.append "&gt;"
577 else if c == '"' then
578 buf.append "&quot;"
579 else buf.add c
580 end
581
582 return buf.to_s
583 end
584
585 # Equality of text
586 # Two pieces of text are equals if thez have the same characters in the same order.
587 #
588 # assert "hello" == "hello"
589 # assert "hello" != "HELLO"
590 # assert "hello" == "hel"+"lo"
591 #
592 # Things that are not Text are not equal.
593 #
594 # assert "9" != '9'
595 # assert "9" != ['9']
596 # assert "9" != 9
597 #
598 # assert "9".chars.first == '9' # equality of Char
599 # assert "9".chars == ['9'] # equality of Sequence
600 # assert "9".to_i == 9 # equality of Int
601 redef fun ==(o)
602 do
603 if o == null then return false
604 if not o isa Text then return false
605 if self.is_same_instance(o) then return true
606 if self.length != o.length then return false
607 return self.chars == o.chars
608 end
609
610 # Lexicographical comparaison
611 #
612 # assert "abc" < "xy"
613 # assert "ABC" < "abc"
614 redef fun <(other)
615 do
616 var self_chars = self.chars.iterator
617 var other_chars = other.chars.iterator
618
619 while self_chars.is_ok and other_chars.is_ok do
620 if self_chars.item < other_chars.item then return true
621 if self_chars.item > other_chars.item then return false
622 self_chars.next
623 other_chars.next
624 end
625
626 if self_chars.is_ok then
627 return false
628 else
629 return true
630 end
631 end
632
633 # Flat representation of self
634 fun flatten: FlatText is abstract
635
636 private var hash_cache: nullable Int = null
637
638 redef fun hash
639 do
640 if hash_cache == null then
641 # djb2 hash algorithm
642 var h = 5381
643
644 for i in [0..length[ do
645 var char = chars[i]
646 h = h.lshift(5) + h + char.ascii
647 end
648
649 hash_cache = h
650 end
651 return hash_cache.as(not null)
652 end
653
654 end
655
656 # All kinds of array-based text representations.
657 abstract class FlatText
658 super Text
659
660 private var items: NativeString
661
662 # Real items, used as cache for to_cstring is called
663 private var real_items: nullable NativeString = null
664
665 redef var length: Int = 0
666
667 init do end
668
669 redef fun output
670 do
671 var i = 0
672 while i < length do
673 items[i].output
674 i += 1
675 end
676 end
677
678 redef fun flatten do return self
679 end
680
681 # Abstract class for the SequenceRead compatible
682 # views on String and Buffer objects
683 private abstract class StringCharView
684 super SequenceRead[Char]
685
686 type SELFTYPE: Text
687
688 private var target: SELFTYPE
689
690 private init(tgt: SELFTYPE)
691 do
692 target = tgt
693 end
694
695 redef fun is_empty do return target.is_empty
696
697 redef fun length do return target.length
698
699 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
700
701 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
702 end
703
704 # View on Buffer objects, extends Sequence
705 # for mutation operations
706 private abstract class BufferCharView
707 super StringCharView
708 super Sequence[Char]
709
710 redef type SELFTYPE: Buffer
711
712 end
713
714 abstract class String
715 super Text
716
717 redef type SELFTYPE: String
718
719 redef fun to_s do return self
720
721 # Concatenates `o` to `self`
722 #
723 # assert "hello" + "world" == "helloworld"
724 # assert "" + "hello" + "" == "hello"
725 fun +(o: Text): SELFTYPE is abstract
726
727 # Concatenates self `i` times
728 #
729 # assert "abc" * 4 == "abcabcabcabc"
730 # assert "abc" * 1 == "abc"
731 # assert "abc" * 0 == ""
732 fun *(i: Int): SELFTYPE is abstract
733
734 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
735
736 # Returns a reversed version of self
737 #
738 # assert "hello".reversed == "olleh"
739 # assert "bob".reversed == "bob"
740 # assert "".reversed == ""
741 fun reversed: SELFTYPE is abstract
742
743 # A upper case version of `self`
744 #
745 # assert "Hello World!".to_upper == "HELLO WORLD!"
746 fun to_upper: SELFTYPE is abstract
747
748 # A lower case version of `self`
749 #
750 # assert "Hello World!".to_lower == "hello world!"
751 fun to_lower : SELFTYPE is abstract
752
753 # Takes a camel case `self` and converts it to snake case
754 #
755 # assert "randomMethodId".to_snake_case == "random_method_id"
756 #
757 # If `self` is upper, it is returned unchanged
758 #
759 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
760 #
761 # If the identifier is prefixed by an underscore, the underscore is ignored
762 #
763 # assert "_privateField".to_snake_case == "_private_field"
764 fun to_snake_case: SELFTYPE
765 do
766 if self.is_upper then return self
767
768 var new_str = new FlatBuffer.with_capacity(self.length)
769 var is_first_char = true
770
771 for i in [0..length[ do
772 var char = chars[i]
773 if is_first_char then
774 new_str.add(char.to_lower)
775 is_first_char = false
776 else if char.is_upper then
777 new_str.add('_')
778 new_str.add(char.to_lower)
779 else
780 new_str.add(char)
781 end
782 end
783
784 return new_str.to_s
785 end
786
787 # Takes a snake case `self` and converts it to camel case
788 #
789 # assert "random_method_id".to_camel_case == "randomMethodId"
790 #
791 # If the identifier is prefixed by an underscore, the underscore is ignored
792 #
793 # assert "_private_field".to_camel_case == "_privateField"
794 #
795 # If `self` is upper, it is returned unchanged
796 #
797 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
798 #
799 # If there are several consecutive underscores, they are considered as a single one
800 #
801 # assert "random__method_id".to_camel_case == "randomMethodId"
802 fun to_camel_case: SELFTYPE
803 do
804 if self.is_upper then return self
805
806 var new_str = new FlatBuffer
807 var is_first_char = true
808 var follows_us = false
809
810 for i in [0..length[ do
811 var char = chars[i]
812 if is_first_char then
813 new_str.add(char)
814 is_first_char = false
815 else if char == '_' then
816 follows_us = true
817 else if follows_us then
818 new_str.add(char.to_upper)
819 follows_us = false
820 else
821 new_str.add(char)
822 end
823 end
824
825 return new_str.to_s
826 end
827 end
828
829 private class FlatSubstringsIter
830 super Iterator[FlatText]
831
832 var tgt: nullable FlatText
833
834 init(tgt: FlatText) do self.tgt = tgt
835
836 redef fun item do
837 assert is_ok
838 return tgt.as(not null)
839 end
840
841 redef fun is_ok do return tgt != null
842
843 redef fun next do tgt = null
844 end
845
846 # Immutable strings of characters.
847 class FlatString
848 super FlatText
849 super String
850
851 # Index in _items of the start of the string
852 private var index_from: Int
853
854 # Indes in _items of the last item of the string
855 private var index_to: Int
856
857 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
858
859 ################################################
860 # AbstractString specific methods #
861 ################################################
862
863 redef fun reversed
864 do
865 var native = calloc_string(self.length + 1)
866 var length = self.length
867 var items = self.items
868 var pos = 0
869 var ipos = length-1
870 while pos < length do
871 native[pos] = items[ipos]
872 pos += 1
873 ipos -= 1
874 end
875 return native.to_s_with_length(self.length)
876 end
877
878 redef fun substring(from, count)
879 do
880 assert count >= 0
881
882 if from < 0 then
883 count += from
884 if count < 0 then count = 0
885 from = 0
886 end
887
888 var realFrom = index_from + from
889
890 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
891
892 if count == 0 then return empty
893
894 var to = realFrom + count - 1
895
896 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
897 end
898
899 redef fun empty do return "".as(FlatString)
900
901 redef fun to_upper
902 do
903 var outstr = calloc_string(self.length + 1)
904 var out_index = 0
905
906 var myitems = self.items
907 var index_from = self.index_from
908 var max = self.index_to
909
910 while index_from <= max do
911 outstr[out_index] = myitems[index_from].to_upper
912 out_index += 1
913 index_from += 1
914 end
915
916 outstr[self.length] = '\0'
917
918 return outstr.to_s_with_length(self.length)
919 end
920
921 redef fun to_lower
922 do
923 var outstr = calloc_string(self.length + 1)
924 var out_index = 0
925
926 var myitems = self.items
927 var index_from = self.index_from
928 var max = self.index_to
929
930 while index_from <= max do
931 outstr[out_index] = myitems[index_from].to_lower
932 out_index += 1
933 index_from += 1
934 end
935
936 outstr[self.length] = '\0'
937
938 return outstr.to_s_with_length(self.length)
939 end
940
941 redef fun output
942 do
943 var i = self.index_from
944 var imax = self.index_to
945 while i <= imax do
946 items[i].output
947 i += 1
948 end
949 end
950
951 ##################################################
952 # String Specific Methods #
953 ##################################################
954
955 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
956 do
957 self.items = items
958 length = len
959 index_from = from
960 index_to = to
961 end
962
963 redef fun to_cstring: NativeString
964 do
965 if real_items != null then return real_items.as(not null)
966 if index_from > 0 or index_to != items.cstring_length - 1 then
967 var newItems = calloc_string(length + 1)
968 self.items.copy_to(newItems, length, index_from, 0)
969 newItems[length] = '\0'
970 self.real_items = newItems
971 return newItems
972 end
973 return items
974 end
975
976 redef fun ==(other)
977 do
978 if not other isa FlatString then return super
979
980 if self.object_id == other.object_id then return true
981
982 var my_length = length
983
984 if other.length != my_length then return false
985
986 var my_index = index_from
987 var its_index = other.index_from
988
989 var last_iteration = my_index + my_length
990
991 var itsitems = other.items
992 var myitems = self.items
993
994 while my_index < last_iteration do
995 if myitems[my_index] != itsitems[its_index] then return false
996 my_index += 1
997 its_index += 1
998 end
999
1000 return true
1001 end
1002
1003 redef fun <(other)
1004 do
1005 if not other isa FlatString then return super
1006
1007 if self.object_id == other.object_id then return false
1008
1009 var my_curr_char : Char
1010 var its_curr_char : Char
1011
1012 var curr_id_self = self.index_from
1013 var curr_id_other = other.index_from
1014
1015 var my_items = self.items
1016 var its_items = other.items
1017
1018 var my_length = self.length
1019 var its_length = other.length
1020
1021 var max_iterations = curr_id_self + my_length
1022
1023 while curr_id_self < max_iterations do
1024 my_curr_char = my_items[curr_id_self]
1025 its_curr_char = its_items[curr_id_other]
1026
1027 if my_curr_char != its_curr_char then
1028 if my_curr_char < its_curr_char then return true
1029 return false
1030 end
1031
1032 curr_id_self += 1
1033 curr_id_other += 1
1034 end
1035
1036 return my_length < its_length
1037 end
1038
1039 redef fun +(s)
1040 do
1041 var my_length = self.length
1042 var its_length = s.length
1043
1044 var total_length = my_length + its_length
1045
1046 var target_string = calloc_string(my_length + its_length + 1)
1047
1048 self.items.copy_to(target_string, my_length, index_from, 0)
1049 if s isa FlatString then
1050 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1051 else if s isa FlatBuffer then
1052 s.items.copy_to(target_string, its_length, 0, my_length)
1053 else
1054 var curr_pos = my_length
1055 for i in [0..s.length[ do
1056 var c = s.chars[i]
1057 target_string[curr_pos] = c
1058 curr_pos += 1
1059 end
1060 end
1061
1062 target_string[total_length] = '\0'
1063
1064 return target_string.to_s_with_length(total_length)
1065 end
1066
1067 redef fun *(i)
1068 do
1069 assert i >= 0
1070
1071 var my_length = self.length
1072
1073 var final_length = my_length * i
1074
1075 var my_items = self.items
1076
1077 var target_string = calloc_string((final_length) + 1)
1078
1079 target_string[final_length] = '\0'
1080
1081 var current_last = 0
1082
1083 for iteration in [1 .. i] do
1084 my_items.copy_to(target_string, my_length, 0, current_last)
1085 current_last += my_length
1086 end
1087
1088 return target_string.to_s_with_length(final_length)
1089 end
1090
1091 redef fun hash
1092 do
1093 if hash_cache == null then
1094 # djb2 hash algorithm
1095 var h = 5381
1096 var i = index_from
1097
1098 var myitems = items
1099
1100 while i <= index_to do
1101 h = h.lshift(5) + h + myitems[i].ascii
1102 i += 1
1103 end
1104
1105 hash_cache = h
1106 end
1107
1108 return hash_cache.as(not null)
1109 end
1110
1111 redef fun substrings do return new FlatSubstringsIter(self)
1112 end
1113
1114 private class FlatStringReverseIterator
1115 super IndexedIterator[Char]
1116
1117 var target: FlatString
1118
1119 var target_items: NativeString
1120
1121 var curr_pos: Int
1122
1123 init with_pos(tgt: FlatString, pos: Int)
1124 do
1125 target = tgt
1126 target_items = tgt.items
1127 curr_pos = pos + tgt.index_from
1128 end
1129
1130 redef fun is_ok do return curr_pos >= 0
1131
1132 redef fun item do return target_items[curr_pos]
1133
1134 redef fun next do curr_pos -= 1
1135
1136 redef fun index do return curr_pos - target.index_from
1137
1138 end
1139
1140 private class FlatStringIterator
1141 super IndexedIterator[Char]
1142
1143 var target: FlatString
1144
1145 var target_items: NativeString
1146
1147 var curr_pos: Int
1148
1149 init with_pos(tgt: FlatString, pos: Int)
1150 do
1151 target = tgt
1152 target_items = tgt.items
1153 curr_pos = pos + target.index_from
1154 end
1155
1156 redef fun is_ok do return curr_pos <= target.index_to
1157
1158 redef fun item do return target_items[curr_pos]
1159
1160 redef fun next do curr_pos += 1
1161
1162 redef fun index do return curr_pos - target.index_from
1163
1164 end
1165
1166 private class FlatStringCharView
1167 super StringCharView
1168
1169 redef type SELFTYPE: FlatString
1170
1171 redef fun [](index)
1172 do
1173 # Check that the index (+ index_from) is not larger than indexTo
1174 # In other terms, if the index is valid
1175 assert index >= 0
1176 var target = self.target
1177 assert (index + target.index_from) <= target.index_to
1178 return target.items[index + target.index_from]
1179 end
1180
1181 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1182
1183 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1184
1185 end
1186
1187 abstract class Buffer
1188 super Text
1189
1190 redef type SELFTYPE: Buffer
1191
1192 # Specific implementations MUST set this to `true` in order to invalidate caches
1193 protected var is_dirty = true
1194
1195 # Modifies the char contained at pos `index`
1196 #
1197 # DEPRECATED : Use self.chars.[]= instead
1198 fun []=(index: Int, item: Char) is abstract
1199
1200 # Adds a char `c` at the end of self
1201 #
1202 # DEPRECATED : Use self.chars.add instead
1203 fun add(c: Char) is abstract
1204
1205 # Clears the buffer
1206 #
1207 # var b = new FlatBuffer
1208 # b.append "hello"
1209 # assert not b.is_empty
1210 # b.clear
1211 # assert b.is_empty
1212 fun clear is abstract
1213
1214 # Enlarges the subsequent array containing the chars of self
1215 fun enlarge(cap: Int) is abstract
1216
1217 # Adds the content of text `s` at the end of self
1218 #
1219 # var b = new FlatBuffer
1220 # b.append "hello"
1221 # b.append "world"
1222 # assert b == "helloworld"
1223 fun append(s: Text) is abstract
1224
1225 # `self` is appended in such a way that `self` is repeated `r` times
1226 #
1227 # var b = new FlatBuffer
1228 # b.append "hello"
1229 # b.times 3
1230 # assert b == "hellohellohello"
1231 fun times(r: Int) is abstract
1232
1233 # Reverses itself in-place
1234 #
1235 # var b = new FlatBuffer
1236 # b.append("hello")
1237 # b.reverse
1238 # assert b == "olleh"
1239 fun reverse is abstract
1240
1241 # Changes each lower-case char in `self` by its upper-case variant
1242 #
1243 # var b = new FlatBuffer
1244 # b.append("Hello World!")
1245 # b.upper
1246 # assert b == "HELLO WORLD!"
1247 fun upper is abstract
1248
1249 # Changes each upper-case char in `self` by its lower-case variant
1250 #
1251 # var b = new FlatBuffer
1252 # b.append("Hello World!")
1253 # b.lower
1254 # assert b == "hello world!"
1255 fun lower is abstract
1256
1257 redef fun hash
1258 do
1259 if is_dirty then hash_cache = null
1260 return super
1261 end
1262
1263 # In Buffers, the internal sequence of character is mutable
1264 # Thus, `chars` can be used to modify the buffer.
1265 redef fun chars: Sequence[Char] is abstract
1266 end
1267
1268 # Mutable strings of characters.
1269 class FlatBuffer
1270 super FlatText
1271 super Buffer
1272
1273 redef type SELFTYPE: FlatBuffer
1274
1275 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1276
1277 private var capacity: Int = 0
1278
1279 redef fun substrings do return new FlatSubstringsIter(self)
1280
1281 redef fun []=(index, item)
1282 do
1283 is_dirty = true
1284 if index == length then
1285 add(item)
1286 return
1287 end
1288 assert index >= 0 and index < length
1289 items[index] = item
1290 end
1291
1292 redef fun add(c)
1293 do
1294 is_dirty = true
1295 if capacity <= length then enlarge(length + 5)
1296 items[length] = c
1297 length += 1
1298 end
1299
1300 redef fun clear do
1301 is_dirty = true
1302 length = 0
1303 end
1304
1305 redef fun empty do return new FlatBuffer
1306
1307 redef fun enlarge(cap)
1308 do
1309 var c = capacity
1310 if cap <= c then return
1311 while c <= cap do c = c * 2 + 2
1312 var a = calloc_string(c+1)
1313 if length > 0 then items.copy_to(a, length, 0, 0)
1314 items = a
1315 capacity = c
1316 end
1317
1318 redef fun to_s: String
1319 do
1320 return to_cstring.to_s_with_length(length)
1321 end
1322
1323 redef fun to_cstring
1324 do
1325 if is_dirty then
1326 var new_native = calloc_string(length + 1)
1327 new_native[length] = '\0'
1328 if length > 0 then items.copy_to(new_native, length, 0, 0)
1329 real_items = new_native
1330 is_dirty = false
1331 end
1332 return real_items.as(not null)
1333 end
1334
1335 # Create a new empty string.
1336 init do end
1337
1338 init from(s: Text)
1339 do
1340 capacity = s.length + 1
1341 length = s.length
1342 items = calloc_string(capacity)
1343 if s isa FlatString then
1344 s.items.copy_to(items, length, s.index_from, 0)
1345 else if s isa FlatBuffer then
1346 s.items.copy_to(items, length, 0, 0)
1347 else
1348 var curr_pos = 0
1349 for i in [0..s.length[ do
1350 var c = s.chars[i]
1351 items[curr_pos] = c
1352 curr_pos += 1
1353 end
1354 end
1355 end
1356
1357 # Create a new empty string with a given capacity.
1358 init with_capacity(cap: Int)
1359 do
1360 assert cap >= 0
1361 # _items = new NativeString.calloc(cap)
1362 items = calloc_string(cap+1)
1363 capacity = cap
1364 length = 0
1365 end
1366
1367 redef fun append(s)
1368 do
1369 if s.is_empty then return
1370 is_dirty = true
1371 var sl = s.length
1372 if capacity < length + sl then enlarge(length + sl)
1373 if s isa FlatString then
1374 s.items.copy_to(items, sl, s.index_from, length)
1375 else if s isa FlatBuffer then
1376 s.items.copy_to(items, sl, 0, length)
1377 else
1378 var curr_pos = self.length
1379 for i in [0..s.length[ do
1380 var c = s.chars[i]
1381 items[curr_pos] = c
1382 curr_pos += 1
1383 end
1384 end
1385 length += sl
1386 end
1387
1388 # Copies the content of self in `dest`
1389 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1390 do
1391 var self_chars = self.chars
1392 var dest_chars = dest.chars
1393 for i in [0..len-1] do
1394 dest_chars[new_start+i] = self_chars[start+i]
1395 end
1396 end
1397
1398 redef fun substring(from, count)
1399 do
1400 assert count >= 0
1401 count += from
1402 if from < 0 then from = 0
1403 if count > length then count = length
1404 if from < count then
1405 var r = new FlatBuffer.with_capacity(count - from)
1406 while from < count do
1407 r.chars.push(items[from])
1408 from += 1
1409 end
1410 return r
1411 else
1412 return new FlatBuffer
1413 end
1414 end
1415
1416 redef fun reverse
1417 do
1418 var ns = calloc_string(capacity)
1419 var si = length - 1
1420 var ni = 0
1421 var it = items
1422 while si >= 0 do
1423 ns[ni] = it[si]
1424 ni += 1
1425 si -= 1
1426 end
1427 items = ns
1428 end
1429
1430 redef fun times(repeats)
1431 do
1432 var x = new FlatString.with_infos(items, length, 0, length - 1)
1433 for i in [1..repeats[ do
1434 append(x)
1435 end
1436 end
1437
1438 redef fun upper
1439 do
1440 var it = items
1441 var id = length - 1
1442 while id >= 0 do
1443 it[id] = it[id].to_upper
1444 id -= 1
1445 end
1446 end
1447
1448 redef fun lower
1449 do
1450 var it = items
1451 var id = length - 1
1452 while id >= 0 do
1453 it[id] = it[id].to_lower
1454 id -= 1
1455 end
1456 end
1457 end
1458
1459 private class FlatBufferReverseIterator
1460 super IndexedIterator[Char]
1461
1462 var target: FlatBuffer
1463
1464 var target_items: NativeString
1465
1466 var curr_pos: Int
1467
1468 init with_pos(tgt: FlatBuffer, pos: Int)
1469 do
1470 target = tgt
1471 if tgt.length > 0 then target_items = tgt.items
1472 curr_pos = pos
1473 end
1474
1475 redef fun index do return curr_pos
1476
1477 redef fun is_ok do return curr_pos >= 0
1478
1479 redef fun item do return target_items[curr_pos]
1480
1481 redef fun next do curr_pos -= 1
1482
1483 end
1484
1485 private class FlatBufferCharView
1486 super BufferCharView
1487 super StringCapable
1488
1489 redef type SELFTYPE: FlatBuffer
1490
1491 redef fun [](index) do return target.items[index]
1492
1493 redef fun []=(index, item)
1494 do
1495 assert index >= 0 and index <= length
1496 if index == length then
1497 add(item)
1498 return
1499 end
1500 target.items[index] = item
1501 end
1502
1503 redef fun push(c)
1504 do
1505 target.add(c)
1506 end
1507
1508 redef fun add(c)
1509 do
1510 target.add(c)
1511 end
1512
1513 fun enlarge(cap: Int)
1514 do
1515 target.enlarge(cap)
1516 end
1517
1518 redef fun append(s)
1519 do
1520 var my_items = target.items
1521 var s_length = s.length
1522 if target.capacity < s.length then enlarge(s_length + target.length)
1523 end
1524
1525 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1526
1527 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1528
1529 end
1530
1531 private class FlatBufferIterator
1532 super IndexedIterator[Char]
1533
1534 var target: FlatBuffer
1535
1536 var target_items: NativeString
1537
1538 var curr_pos: Int
1539
1540 init with_pos(tgt: FlatBuffer, pos: Int)
1541 do
1542 target = tgt
1543 if tgt.length > 0 then target_items = tgt.items
1544 curr_pos = pos
1545 end
1546
1547 redef fun index do return curr_pos
1548
1549 redef fun is_ok do return curr_pos < target.length
1550
1551 redef fun item do return target_items[curr_pos]
1552
1553 redef fun next do curr_pos += 1
1554
1555 end
1556
1557 ###############################################################################
1558 # Refinement #
1559 ###############################################################################
1560
1561 redef class Object
1562 # User readable representation of `self`.
1563 fun to_s: String do return inspect
1564
1565 # The class name of the object in NativeString format.
1566 private fun native_class_name: NativeString is intern
1567
1568 # The class name of the object.
1569 #
1570 # assert 5.class_name == "Int"
1571 fun class_name: String do return native_class_name.to_s
1572
1573 # Developer readable representation of `self`.
1574 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1575 fun inspect: String
1576 do
1577 return "<{inspect_head}>"
1578 end
1579
1580 # Return "CLASSNAME:#OBJECTID".
1581 # This function is mainly used with the redefinition of the inspect method
1582 protected fun inspect_head: String
1583 do
1584 return "{class_name}:#{object_id.to_hex}"
1585 end
1586 end
1587
1588 redef class Bool
1589 # assert true.to_s == "true"
1590 # assert false.to_s == "false"
1591 redef fun to_s
1592 do
1593 if self then
1594 return once "true"
1595 else
1596 return once "false"
1597 end
1598 end
1599 end
1600
1601 redef class Int
1602
1603 # Wrapper of strerror C function
1604 private fun strerror_ext: NativeString is extern `{
1605 return strerror(recv);
1606 `}
1607
1608 # Returns a string describing error number
1609 fun strerror: String do return strerror_ext.to_s
1610
1611 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1612 # assume < to_c max const of char
1613 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1614 do
1615 var n: Int
1616 # Sign
1617 if self < 0 then
1618 n = - self
1619 s.chars[0] = '-'
1620 else if self == 0 then
1621 s.chars[0] = '0'
1622 return
1623 else
1624 n = self
1625 end
1626 # Fill digits
1627 var pos = digit_count(base) - 1
1628 while pos >= 0 and n > 0 do
1629 s.chars[pos] = (n % base).to_c
1630 n = n / base # /
1631 pos -= 1
1632 end
1633 end
1634
1635 # C function to convert an nit Int to a NativeString (char*)
1636 private fun native_int_to_s: NativeString is extern "native_int_to_s"
1637
1638 # return displayable int in base 10 and signed
1639 #
1640 # assert 1.to_s == "1"
1641 # assert (-123).to_s == "-123"
1642 redef fun to_s do
1643 return native_int_to_s.to_s
1644 end
1645
1646 # return displayable int in hexadecimal
1647 #
1648 # assert 1.to_hex == "1"
1649 # assert (-255).to_hex == "-ff"
1650 fun to_hex: String do return to_base(16,false)
1651
1652 # return displayable int in base base and signed
1653 fun to_base(base: Int, signed: Bool): String
1654 do
1655 var l = digit_count(base)
1656 var s = new FlatBuffer.from(" " * l)
1657 fill_buffer(s, base, signed)
1658 return s.to_s
1659 end
1660 end
1661
1662 redef class Float
1663 # Pretty print self, print needoed decimals up to a max of 3.
1664 #
1665 # assert 12.34.to_s == "12.34"
1666 # assert (-0120.03450).to_s == "-120.035"
1667 #
1668 # see `to_precision` for a different precision.
1669 redef fun to_s do
1670 var str = to_precision( 3 )
1671 if is_inf != 0 or is_nan then return str
1672 var len = str.length
1673 for i in [0..len-1] do
1674 var j = len-1-i
1675 var c = str.chars[j]
1676 if c == '0' then
1677 continue
1678 else if c == '.' then
1679 return str.substring( 0, j+2 )
1680 else
1681 return str.substring( 0, j+1 )
1682 end
1683 end
1684 return str
1685 end
1686
1687 # `self` representation with `nb` digits after the '.'.
1688 #
1689 # assert 12.345.to_precision(1) == "12.3"
1690 # assert 12.345.to_precision(2) == "12.35"
1691 # assert 12.345.to_precision(3) == "12.345"
1692 # assert 12.345.to_precision(4) == "12.3450"
1693 fun to_precision(nb: Int): String
1694 do
1695 if is_nan then return "nan"
1696
1697 var isinf = self.is_inf
1698 if isinf == 1 then
1699 return "inf"
1700 else if isinf == -1 then
1701 return "-inf"
1702 end
1703
1704 if nb == 0 then return self.to_i.to_s
1705 var f = self
1706 for i in [0..nb[ do f = f * 10.0
1707 if self > 0.0 then
1708 f = f + 0.5
1709 else
1710 f = f - 0.5
1711 end
1712 var i = f.to_i
1713 if i == 0 then return "0.0"
1714 var s = i.to_s
1715 var sl = s.length
1716 if sl > nb then
1717 var p1 = s.substring(0, s.length-nb)
1718 var p2 = s.substring(s.length-nb, nb)
1719 return p1 + "." + p2
1720 else
1721 return "0." + ("0"*(nb-sl)) + s
1722 end
1723 end
1724
1725 # `self` representation with `nb` digits after the '.'.
1726 #
1727 # assert 12.345.to_precision_native(1) == "12.3"
1728 # assert 12.345.to_precision_native(2) == "12.35"
1729 # assert 12.345.to_precision_native(3) == "12.345"
1730 # assert 12.345.to_precision_native(4) == "12.3450"
1731 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1732 int size;
1733 char *str;
1734
1735 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1736 str = malloc(size + 1);
1737 sprintf(str, "%.*f", (int)nb, recv );
1738
1739 return NativeString_to_s( str );
1740 `}
1741 end
1742
1743 redef class Char
1744 # assert 'x'.to_s == "x"
1745 redef fun to_s
1746 do
1747 var s = new FlatBuffer.with_capacity(1)
1748 s.chars[0] = self
1749 return s.to_s
1750 end
1751
1752 # Returns true if the char is a numerical digit
1753 #
1754 # assert '0'.is_numeric
1755 # assert '9'.is_numeric
1756 # assert not 'a'.is_numeric
1757 # assert not '?'.is_numeric
1758 fun is_numeric: Bool
1759 do
1760 return self >= '0' and self <= '9'
1761 end
1762
1763 # Returns true if the char is an alpha digit
1764 #
1765 # assert 'a'.is_alpha
1766 # assert 'Z'.is_alpha
1767 # assert not '0'.is_alpha
1768 # assert not '?'.is_alpha
1769 fun is_alpha: Bool
1770 do
1771 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1772 end
1773
1774 # Returns true if the char is an alpha or a numeric digit
1775 #
1776 # assert 'a'.is_alphanumeric
1777 # assert 'Z'.is_alphanumeric
1778 # assert '0'.is_alphanumeric
1779 # assert '9'.is_alphanumeric
1780 # assert not '?'.is_alphanumeric
1781 fun is_alphanumeric: Bool
1782 do
1783 return self.is_numeric or self.is_alpha
1784 end
1785 end
1786
1787 redef class Collection[E]
1788 # Concatenate elements.
1789 redef fun to_s
1790 do
1791 var s = new FlatBuffer
1792 for e in self do if e != null then s.append(e.to_s)
1793 return s.to_s
1794 end
1795
1796 # Concatenate and separate each elements with `sep`.
1797 #
1798 # assert [1, 2, 3].join(":") == "1:2:3"
1799 # assert [1..3].join(":") == "1:2:3"
1800 fun join(sep: Text): String
1801 do
1802 if is_empty then return ""
1803
1804 var s = new FlatBuffer # Result
1805
1806 # Concat first item
1807 var i = iterator
1808 var e = i.item
1809 if e != null then s.append(e.to_s)
1810
1811 # Concat other items
1812 i.next
1813 while i.is_ok do
1814 s.append(sep)
1815 e = i.item
1816 if e != null then s.append(e.to_s)
1817 i.next
1818 end
1819 return s.to_s
1820 end
1821 end
1822
1823 redef class Array[E]
1824 # Fast implementation
1825 redef fun to_s
1826 do
1827 var s = new FlatBuffer
1828 var i = 0
1829 var l = length
1830 while i < l do
1831 var e = self[i]
1832 if e != null then s.append(e.to_s)
1833 i += 1
1834 end
1835 return s.to_s
1836 end
1837 end
1838
1839 redef class Map[K,V]
1840 # Concatenate couple of 'key value'.
1841 # key and value are separated by `couple_sep`.
1842 # each couple is separated each couple with `sep`.
1843 #
1844 # var m = new ArrayMap[Int, String]
1845 # m[1] = "one"
1846 # m[10] = "ten"
1847 # assert m.join("; ", "=") == "1=one; 10=ten"
1848 fun join(sep: String, couple_sep: String): String
1849 do
1850 if is_empty then return ""
1851
1852 var s = new FlatBuffer # Result
1853
1854 # Concat first item
1855 var i = iterator
1856 var k = i.key
1857 var e = i.item
1858 s.append("{k}{couple_sep}{e or else "<null>"}")
1859
1860 # Concat other items
1861 i.next
1862 while i.is_ok do
1863 s.append(sep)
1864 k = i.key
1865 e = i.item
1866 s.append("{k}{couple_sep}{e or else "<null>"}")
1867 i.next
1868 end
1869 return s.to_s
1870 end
1871 end
1872
1873 ###############################################################################
1874 # Native classes #
1875 ###############################################################################
1876
1877 # Native strings are simple C char *
1878 extern class NativeString `{ char* `}
1879 super StringCapable
1880
1881 fun [](index: Int): Char is intern
1882 fun []=(index: Int, item: Char) is intern
1883 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1884
1885 # Position of the first nul character.
1886 fun cstring_length: Int
1887 do
1888 var l = 0
1889 while self[l] != '\0' do l += 1
1890 return l
1891 end
1892 fun atoi: Int is intern
1893 fun atof: Float is extern "atof"
1894
1895 redef fun to_s
1896 do
1897 return to_s_with_length(cstring_length)
1898 end
1899
1900 fun to_s_with_length(length: Int): FlatString
1901 do
1902 assert length >= 0
1903 return new FlatString.with_infos(self, length, 0, length - 1)
1904 end
1905
1906 fun to_s_with_copy: FlatString
1907 do
1908 var length = cstring_length
1909 var new_self = calloc_string(length + 1)
1910 copy_to(new_self, length, 0, 0)
1911 return new FlatString.with_infos(new_self, length, 0, length - 1)
1912 end
1913 end
1914
1915 # StringCapable objects can create native strings
1916 interface StringCapable
1917 protected fun calloc_string(size: Int): NativeString is intern
1918 end
1919
1920 redef class Sys
1921 var _args_cache: nullable Sequence[String]
1922
1923 # The arguments of the program as given by the OS
1924 fun program_args: Sequence[String]
1925 do
1926 if _args_cache == null then init_args
1927 return _args_cache.as(not null)
1928 end
1929
1930 # The name of the program as given by the OS
1931 fun program_name: String
1932 do
1933 return native_argv(0).to_s
1934 end
1935
1936 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1937 private fun init_args
1938 do
1939 var argc = native_argc
1940 var args = new Array[String].with_capacity(0)
1941 var i = 1
1942 while i < argc do
1943 args[i-1] = native_argv(i).to_s
1944 i += 1
1945 end
1946 _args_cache = args
1947 end
1948
1949 # First argument of the main C function.
1950 private fun native_argc: Int is intern
1951
1952 # Second argument of the main C function.
1953 private fun native_argv(i: Int): NativeString is intern
1954 end
1955
1956 # Comparator that efficienlty use `to_s` to compare things
1957 #
1958 # The comparaison call `to_s` on object and use the result to order things.
1959 #
1960 # var a = [1, 2, 3, 10, 20]
1961 # (new CachedAlphaComparator).sort(a)
1962 # assert a == [1, 10, 2, 20, 3]
1963 #
1964 # Internally the result of `to_s` is cached in a HashMap to counter
1965 # uneficient implementation of `to_s`.
1966 #
1967 # Note: it caching is not usefull, see `alpha_comparator`
1968 class CachedAlphaComparator
1969 super Comparator[Object]
1970
1971 private var cache = new HashMap[Object, String]
1972
1973 private fun do_to_s(a: Object): String do
1974 if cache.has_key(a) then return cache[a]
1975 var res = a.to_s
1976 cache[a] = res
1977 return res
1978 end
1979
1980 redef fun compare(a, b) do
1981 return do_to_s(a) <=> do_to_s(b)
1982 end
1983 end
1984
1985 # see `alpha_comparator`
1986 private class AlphaComparator
1987 super Comparator[Object]
1988 redef fun compare(a, b) do return a.to_s <=> b.to_s
1989 end
1990
1991 # Stateless comparator that naively use `to_s` to compare things.
1992 #
1993 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1994 # on a single instace. See `CachedAlphaComparator` as an alternative.
1995 #
1996 # var a = [1, 2, 3, 10, 20]
1997 # alpha_comparator.sort(a)
1998 # assert a == [1, 10, 2, 20, 3]
1999 fun alpha_comparator: Comparator[Object] do return once new AlphaComparator
2000
2001 # The arguments of the program as given by the OS
2002 fun args: Sequence[String]
2003 do
2004 return sys.program_args
2005 end