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