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