all: fix broken docunits
[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 redef fun output
761 do
762 var i = 0
763 while i < length do
764 items[i].output
765 i += 1
766 end
767 end
768
769 redef fun flatten do return self
770 end
771
772 # Abstract class for the SequenceRead compatible
773 # views on String and Buffer objects
774 private abstract class StringCharView
775 super SequenceRead[Char]
776
777 type SELFTYPE: Text
778
779 var target: SELFTYPE
780
781 redef fun is_empty do return target.is_empty
782
783 redef fun length do return target.length
784
785 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
786
787 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
788 end
789
790 # View on Buffer objects, extends Sequence
791 # for mutation operations
792 private abstract class BufferCharView
793 super StringCharView
794 super Sequence[Char]
795
796 redef type SELFTYPE: Buffer
797
798 end
799
800 # A `String` holds and manipulates an arbitrary sequence of characters.
801 #
802 # String objects may be created using literals.
803 #
804 # assert "Hello World!" isa String
805 abstract class String
806 super Text
807
808 redef type SELFTYPE: String
809
810 redef fun to_s do return self
811
812 # Concatenates `o` to `self`
813 #
814 # assert "hello" + "world" == "helloworld"
815 # assert "" + "hello" + "" == "hello"
816 fun +(o: Text): SELFTYPE is abstract
817
818 # Concatenates self `i` times
819 #
820 # assert "abc" * 4 == "abcabcabcabc"
821 # assert "abc" * 1 == "abc"
822 # assert "abc" * 0 == ""
823 fun *(i: Int): SELFTYPE is abstract
824
825 # Insert `s` at `pos`.
826 #
827 # assert "helloworld".insert_at(" ", 5) == "hello world"
828 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
829
830 redef fun substrings: Iterator[String] is abstract
831
832 # Returns a reversed version of self
833 #
834 # assert "hello".reversed == "olleh"
835 # assert "bob".reversed == "bob"
836 # assert "".reversed == ""
837 fun reversed: SELFTYPE is abstract
838
839 # A upper case version of `self`
840 #
841 # assert "Hello World!".to_upper == "HELLO WORLD!"
842 fun to_upper: SELFTYPE is abstract
843
844 # A lower case version of `self`
845 #
846 # assert "Hello World!".to_lower == "hello world!"
847 fun to_lower : SELFTYPE is abstract
848
849 # Takes a camel case `self` and converts it to snake case
850 #
851 # assert "randomMethodId".to_snake_case == "random_method_id"
852 #
853 # If `self` is upper, it is returned unchanged
854 #
855 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
856 #
857 # If the identifier is prefixed by an underscore, the underscore is ignored
858 #
859 # assert "_privateField".to_snake_case == "_private_field"
860 fun to_snake_case: SELFTYPE
861 do
862 if self.is_upper then return self
863
864 var new_str = new FlatBuffer.with_capacity(self.length)
865 var is_first_char = true
866
867 for i in [0..length[ do
868 var char = chars[i]
869 if is_first_char then
870 new_str.add(char.to_lower)
871 is_first_char = false
872 else if char.is_upper then
873 new_str.add('_')
874 new_str.add(char.to_lower)
875 else
876 new_str.add(char)
877 end
878 end
879
880 return new_str.to_s
881 end
882
883 # Takes a snake case `self` and converts it to camel case
884 #
885 # assert "random_method_id".to_camel_case == "randomMethodId"
886 #
887 # If the identifier is prefixed by an underscore, the underscore is ignored
888 #
889 # assert "_private_field".to_camel_case == "_privateField"
890 #
891 # If `self` is upper, it is returned unchanged
892 #
893 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
894 #
895 # If there are several consecutive underscores, they are considered as a single one
896 #
897 # assert "random__method_id".to_camel_case == "randomMethodId"
898 fun to_camel_case: SELFTYPE
899 do
900 if self.is_upper then return self
901
902 var new_str = new FlatBuffer
903 var is_first_char = true
904 var follows_us = false
905
906 for i in [0..length[ do
907 var char = chars[i]
908 if is_first_char then
909 new_str.add(char)
910 is_first_char = false
911 else if char == '_' then
912 follows_us = true
913 else if follows_us then
914 new_str.add(char.to_upper)
915 follows_us = false
916 else
917 new_str.add(char)
918 end
919 end
920
921 return new_str.to_s
922 end
923
924 # Returns a capitalized `self`
925 #
926 # Letters that follow a letter are lowercased
927 # Letters that follow a non-letter are upcased.
928 #
929 # SEE : `Char::is_letter` for the definition of letter.
930 #
931 # assert "jAVASCRIPT".capitalized == "Javascript"
932 # assert "i am root".capitalized == "I Am Root"
933 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
934 fun capitalized: SELFTYPE do
935 if length == 0 then return self
936
937 var buf = new FlatBuffer.with_capacity(length)
938
939 var curr = chars[0].to_upper
940 var prev = curr
941 buf[0] = curr
942
943 for i in [1 .. length[ do
944 prev = curr
945 curr = self[i]
946 if prev.is_letter then
947 buf[i] = curr.to_lower
948 else
949 buf[i] = curr.to_upper
950 end
951 end
952
953 return buf.to_s
954 end
955 end
956
957 private class FlatSubstringsIter
958 super Iterator[FlatText]
959
960 var tgt: nullable FlatText
961
962 redef fun item do
963 assert is_ok
964 return tgt.as(not null)
965 end
966
967 redef fun is_ok do return tgt != null
968
969 redef fun next do tgt = null
970 end
971
972 # Immutable strings of characters.
973 class FlatString
974 super FlatText
975 super String
976
977 # Index in _items of the start of the string
978 private var index_from: Int is noinit
979
980 # Indes in _items of the last item of the string
981 private var index_to: Int is noinit
982
983 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
984
985 redef fun [](index)
986 do
987 # Check that the index (+ index_from) is not larger than indexTo
988 # In other terms, if the index is valid
989 assert index >= 0
990 assert (index + index_from) <= index_to
991 return items[index + index_from]
992 end
993
994 ################################################
995 # AbstractString specific methods #
996 ################################################
997
998 redef fun reversed
999 do
1000 var native = new NativeString(self.length + 1)
1001 var length = self.length
1002 var items = self.items
1003 var pos = 0
1004 var ipos = length-1
1005 while pos < length do
1006 native[pos] = items[ipos]
1007 pos += 1
1008 ipos -= 1
1009 end
1010 return native.to_s_with_length(self.length)
1011 end
1012
1013 redef fun substring(from, count)
1014 do
1015 assert count >= 0
1016
1017 if from < 0 then
1018 count += from
1019 if count < 0 then count = 0
1020 from = 0
1021 end
1022
1023 var realFrom = index_from + from
1024
1025 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
1026
1027 if count == 0 then return empty
1028
1029 var to = realFrom + count - 1
1030
1031 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
1032 end
1033
1034 redef fun empty do return "".as(FlatString)
1035
1036 redef fun to_upper
1037 do
1038 var outstr = new NativeString(self.length + 1)
1039 var out_index = 0
1040
1041 var myitems = self.items
1042 var index_from = self.index_from
1043 var max = self.index_to
1044
1045 while index_from <= max do
1046 outstr[out_index] = myitems[index_from].to_upper
1047 out_index += 1
1048 index_from += 1
1049 end
1050
1051 outstr[self.length] = '\0'
1052
1053 return outstr.to_s_with_length(self.length)
1054 end
1055
1056 redef fun to_lower
1057 do
1058 var outstr = new NativeString(self.length + 1)
1059 var out_index = 0
1060
1061 var myitems = self.items
1062 var index_from = self.index_from
1063 var max = self.index_to
1064
1065 while index_from <= max do
1066 outstr[out_index] = myitems[index_from].to_lower
1067 out_index += 1
1068 index_from += 1
1069 end
1070
1071 outstr[self.length] = '\0'
1072
1073 return outstr.to_s_with_length(self.length)
1074 end
1075
1076 redef fun output
1077 do
1078 var i = self.index_from
1079 var imax = self.index_to
1080 while i <= imax do
1081 items[i].output
1082 i += 1
1083 end
1084 end
1085
1086 ##################################################
1087 # String Specific Methods #
1088 ##################################################
1089
1090 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1091 do
1092 self.items = items
1093 length = len
1094 index_from = from
1095 index_to = to
1096 end
1097
1098 redef fun to_cstring: NativeString
1099 do
1100 if real_items != null then
1101 return real_items.as(not null)
1102 else
1103 var newItems = new NativeString(length + 1)
1104 self.items.copy_to(newItems, length, index_from, 0)
1105 newItems[length] = '\0'
1106 self.real_items = newItems
1107 return newItems
1108 end
1109 end
1110
1111 redef fun ==(other)
1112 do
1113 if not other isa FlatString then return super
1114
1115 if self.object_id == other.object_id then return true
1116
1117 var my_length = length
1118
1119 if other.length != my_length then return false
1120
1121 var my_index = index_from
1122 var its_index = other.index_from
1123
1124 var last_iteration = my_index + my_length
1125
1126 var itsitems = other.items
1127 var myitems = self.items
1128
1129 while my_index < last_iteration do
1130 if myitems[my_index] != itsitems[its_index] then return false
1131 my_index += 1
1132 its_index += 1
1133 end
1134
1135 return true
1136 end
1137
1138 redef fun <(other)
1139 do
1140 if not other isa FlatString then return super
1141
1142 if self.object_id == other.object_id then return false
1143
1144 var my_curr_char : Char
1145 var its_curr_char : Char
1146
1147 var curr_id_self = self.index_from
1148 var curr_id_other = other.index_from
1149
1150 var my_items = self.items
1151 var its_items = other.items
1152
1153 var my_length = self.length
1154 var its_length = other.length
1155
1156 var max_iterations = curr_id_self + my_length
1157
1158 while curr_id_self < max_iterations do
1159 my_curr_char = my_items[curr_id_self]
1160 its_curr_char = its_items[curr_id_other]
1161
1162 if my_curr_char != its_curr_char then
1163 if my_curr_char < its_curr_char then return true
1164 return false
1165 end
1166
1167 curr_id_self += 1
1168 curr_id_other += 1
1169 end
1170
1171 return my_length < its_length
1172 end
1173
1174 redef fun +(s)
1175 do
1176 var my_length = self.length
1177 var its_length = s.length
1178
1179 var total_length = my_length + its_length
1180
1181 var target_string = new NativeString(my_length + its_length + 1)
1182
1183 self.items.copy_to(target_string, my_length, index_from, 0)
1184 if s isa FlatString then
1185 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1186 else if s isa FlatBuffer then
1187 s.items.copy_to(target_string, its_length, 0, my_length)
1188 else
1189 var curr_pos = my_length
1190 for i in [0..s.length[ do
1191 var c = s.chars[i]
1192 target_string[curr_pos] = c
1193 curr_pos += 1
1194 end
1195 end
1196
1197 target_string[total_length] = '\0'
1198
1199 return target_string.to_s_with_length(total_length)
1200 end
1201
1202 redef fun *(i)
1203 do
1204 assert i >= 0
1205
1206 var my_length = self.length
1207
1208 var final_length = my_length * i
1209
1210 var my_items = self.items
1211
1212 var target_string = new NativeString(final_length + 1)
1213
1214 target_string[final_length] = '\0'
1215
1216 var current_last = 0
1217
1218 for iteration in [1 .. i] do
1219 my_items.copy_to(target_string, my_length, 0, current_last)
1220 current_last += my_length
1221 end
1222
1223 return target_string.to_s_with_length(final_length)
1224 end
1225
1226 redef fun hash
1227 do
1228 if hash_cache == null then
1229 # djb2 hash algorithm
1230 var h = 5381
1231 var i = index_from
1232
1233 var myitems = items
1234
1235 while i <= index_to do
1236 h = h.lshift(5) + h + myitems[i].ascii
1237 i += 1
1238 end
1239
1240 hash_cache = h
1241 end
1242
1243 return hash_cache.as(not null)
1244 end
1245
1246 redef fun substrings do return new FlatSubstringsIter(self)
1247 end
1248
1249 private class FlatStringReverseIterator
1250 super IndexedIterator[Char]
1251
1252 var target: FlatString
1253
1254 var target_items: NativeString
1255
1256 var curr_pos: Int
1257
1258 init with_pos(tgt: FlatString, pos: Int)
1259 do
1260 target = tgt
1261 target_items = tgt.items
1262 curr_pos = pos + tgt.index_from
1263 end
1264
1265 redef fun is_ok do return curr_pos >= target.index_from
1266
1267 redef fun item do return target_items[curr_pos]
1268
1269 redef fun next do curr_pos -= 1
1270
1271 redef fun index do return curr_pos - target.index_from
1272
1273 end
1274
1275 private class FlatStringIterator
1276 super IndexedIterator[Char]
1277
1278 var target: FlatString
1279
1280 var target_items: NativeString
1281
1282 var curr_pos: Int
1283
1284 init with_pos(tgt: FlatString, pos: Int)
1285 do
1286 target = tgt
1287 target_items = tgt.items
1288 curr_pos = pos + target.index_from
1289 end
1290
1291 redef fun is_ok do return curr_pos <= target.index_to
1292
1293 redef fun item do return target_items[curr_pos]
1294
1295 redef fun next do curr_pos += 1
1296
1297 redef fun index do return curr_pos - target.index_from
1298
1299 end
1300
1301 private class FlatStringCharView
1302 super StringCharView
1303
1304 redef type SELFTYPE: FlatString
1305
1306 redef fun [](index)
1307 do
1308 # Check that the index (+ index_from) is not larger than indexTo
1309 # In other terms, if the index is valid
1310 assert index >= 0
1311 var target = self.target
1312 assert (index + target.index_from) <= target.index_to
1313 return target.items[index + target.index_from]
1314 end
1315
1316 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1317
1318 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1319
1320 end
1321
1322 # A mutable sequence of characters.
1323 abstract class Buffer
1324 super Text
1325
1326 redef type SELFTYPE: Buffer
1327
1328 # Specific implementations MUST set this to `true` in order to invalidate caches
1329 protected var is_dirty = true
1330
1331 # Copy-On-Write flag
1332 #
1333 # If the `Buffer` was to_s'd, the next in-place altering
1334 # operation will cause the current `Buffer` to be re-allocated.
1335 #
1336 # The flag will then be set at `false`.
1337 protected var written = false
1338
1339 # Modifies the char contained at pos `index`
1340 #
1341 # DEPRECATED : Use self.chars.[]= instead
1342 fun []=(index: Int, item: Char) is abstract
1343
1344 # Adds a char `c` at the end of self
1345 #
1346 # DEPRECATED : Use self.chars.add instead
1347 fun add(c: Char) is abstract
1348
1349 # Clears the buffer
1350 #
1351 # var b = new FlatBuffer
1352 # b.append "hello"
1353 # assert not b.is_empty
1354 # b.clear
1355 # assert b.is_empty
1356 fun clear is abstract
1357
1358 # Enlarges the subsequent array containing the chars of self
1359 fun enlarge(cap: Int) is abstract
1360
1361 # Adds the content of text `s` at the end of self
1362 #
1363 # var b = new FlatBuffer
1364 # b.append "hello"
1365 # b.append "world"
1366 # assert b == "helloworld"
1367 fun append(s: Text) is abstract
1368
1369 # `self` is appended in such a way that `self` is repeated `r` times
1370 #
1371 # var b = new FlatBuffer
1372 # b.append "hello"
1373 # b.times 3
1374 # assert b == "hellohellohello"
1375 fun times(r: Int) is abstract
1376
1377 # Reverses itself in-place
1378 #
1379 # var b = new FlatBuffer
1380 # b.append("hello")
1381 # b.reverse
1382 # assert b == "olleh"
1383 fun reverse is abstract
1384
1385 # Changes each lower-case char in `self` by its upper-case variant
1386 #
1387 # var b = new FlatBuffer
1388 # b.append("Hello World!")
1389 # b.upper
1390 # assert b == "HELLO WORLD!"
1391 fun upper is abstract
1392
1393 # Changes each upper-case char in `self` by its lower-case variant
1394 #
1395 # var b = new FlatBuffer
1396 # b.append("Hello World!")
1397 # b.lower
1398 # assert b == "hello world!"
1399 fun lower is abstract
1400
1401 # Capitalizes each word in `self`
1402 #
1403 # Letters that follow a letter are lowercased
1404 # Letters that follow a non-letter are upcased.
1405 #
1406 # SEE: `Char::is_letter` for the definition of a letter.
1407 #
1408 # var b = new FlatBuffer.from("jAVAsCriPt")
1409 # b.capitalize
1410 # assert b == "Javascript"
1411 # b = new FlatBuffer.from("i am root")
1412 # b.capitalize
1413 # assert b == "I Am Root"
1414 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1415 # b.capitalize
1416 # assert b == "Ab_C -Ab0C Ab\nC"
1417 fun capitalize do
1418 if length == 0 then return
1419 var c = self[0].to_upper
1420 self[0] = c
1421 var prev: Char = c
1422 for i in [1 .. length[ do
1423 prev = c
1424 c = self[i]
1425 if prev.is_letter then
1426 self[i] = c.to_lower
1427 else
1428 self[i] = c.to_upper
1429 end
1430 end
1431 end
1432
1433 redef fun hash
1434 do
1435 if is_dirty then hash_cache = null
1436 return super
1437 end
1438
1439 # In Buffers, the internal sequence of character is mutable
1440 # Thus, `chars` can be used to modify the buffer.
1441 redef fun chars: Sequence[Char] is abstract
1442 end
1443
1444 # Mutable strings of characters.
1445 class FlatBuffer
1446 super FlatText
1447 super Buffer
1448
1449 redef type SELFTYPE: FlatBuffer
1450
1451 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1452
1453 private var capacity: Int = 0
1454
1455 redef fun substrings do return new FlatSubstringsIter(self)
1456
1457 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1458 #
1459 # This happens when an operation modifies the current `Buffer` and
1460 # the Copy-On-Write flag `written` is set at true.
1461 private fun reset do
1462 var nns = new NativeString(capacity)
1463 items.copy_to(nns, length, 0, 0)
1464 items = nns
1465 written = false
1466 end
1467
1468 redef fun [](index)
1469 do
1470 assert index >= 0
1471 assert index < length
1472 return items[index]
1473 end
1474
1475 redef fun []=(index, item)
1476 do
1477 is_dirty = true
1478 if index == length then
1479 add(item)
1480 return
1481 end
1482 if written then reset
1483 assert index >= 0 and index < length
1484 items[index] = item
1485 end
1486
1487 redef fun add(c)
1488 do
1489 is_dirty = true
1490 if capacity <= length then enlarge(length + 5)
1491 items[length] = c
1492 length += 1
1493 end
1494
1495 redef fun clear do
1496 is_dirty = true
1497 if written then reset
1498 length = 0
1499 end
1500
1501 redef fun empty do return new FlatBuffer
1502
1503 redef fun enlarge(cap)
1504 do
1505 var c = capacity
1506 if cap <= c then return
1507 while c <= cap do c = c * 2 + 2
1508 # The COW flag can be set at false here, since
1509 # it does a copy of the current `Buffer`
1510 written = false
1511 var a = new NativeString(c+1)
1512 if length > 0 then items.copy_to(a, length, 0, 0)
1513 items = a
1514 capacity = c
1515 end
1516
1517 redef fun to_s: String
1518 do
1519 written = true
1520 if length == 0 then items = new NativeString(1)
1521 return new FlatString.with_infos(items, length, 0, length - 1)
1522 end
1523
1524 redef fun to_cstring
1525 do
1526 if is_dirty then
1527 var new_native = new NativeString(length + 1)
1528 new_native[length] = '\0'
1529 if length > 0 then items.copy_to(new_native, length, 0, 0)
1530 real_items = new_native
1531 is_dirty = false
1532 end
1533 return real_items.as(not null)
1534 end
1535
1536 # Create a new empty string.
1537 init do end
1538
1539 # Create a new string copied from `s`.
1540 init from(s: Text)
1541 do
1542 capacity = s.length + 1
1543 length = s.length
1544 items = new NativeString(capacity)
1545 if s isa FlatString then
1546 s.items.copy_to(items, length, s.index_from, 0)
1547 else if s isa FlatBuffer then
1548 s.items.copy_to(items, length, 0, 0)
1549 else
1550 var curr_pos = 0
1551 for i in [0..s.length[ do
1552 var c = s.chars[i]
1553 items[curr_pos] = c
1554 curr_pos += 1
1555 end
1556 end
1557 end
1558
1559 # Create a new empty string with a given capacity.
1560 init with_capacity(cap: Int)
1561 do
1562 assert cap >= 0
1563 # _items = new NativeString.calloc(cap)
1564 items = new NativeString(cap+1)
1565 capacity = cap
1566 length = 0
1567 end
1568
1569 redef fun append(s)
1570 do
1571 if s.is_empty then return
1572 is_dirty = true
1573 var sl = s.length
1574 if capacity < length + sl then enlarge(length + sl)
1575 if s isa FlatString then
1576 s.items.copy_to(items, sl, s.index_from, length)
1577 else if s isa FlatBuffer then
1578 s.items.copy_to(items, sl, 0, length)
1579 else
1580 var curr_pos = self.length
1581 for i in [0..s.length[ do
1582 var c = s.chars[i]
1583 items[curr_pos] = c
1584 curr_pos += 1
1585 end
1586 end
1587 length += sl
1588 end
1589
1590 # Copies the content of self in `dest`
1591 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1592 do
1593 var self_chars = self.chars
1594 var dest_chars = dest.chars
1595 for i in [0..len-1] do
1596 dest_chars[new_start+i] = self_chars[start+i]
1597 end
1598 end
1599
1600 redef fun substring(from, count)
1601 do
1602 assert count >= 0
1603 count += from
1604 if from < 0 then from = 0
1605 if count > length then count = length
1606 if from < count then
1607 var r = new FlatBuffer.with_capacity(count - from)
1608 while from < count do
1609 r.chars.push(items[from])
1610 from += 1
1611 end
1612 return r
1613 else
1614 return new FlatBuffer
1615 end
1616 end
1617
1618 redef fun reverse
1619 do
1620 written = false
1621 var ns = new NativeString(capacity)
1622 var si = length - 1
1623 var ni = 0
1624 var it = items
1625 while si >= 0 do
1626 ns[ni] = it[si]
1627 ni += 1
1628 si -= 1
1629 end
1630 items = ns
1631 end
1632
1633 redef fun times(repeats)
1634 do
1635 var x = new FlatString.with_infos(items, length, 0, length - 1)
1636 for i in [1..repeats[ do
1637 append(x)
1638 end
1639 end
1640
1641 redef fun upper
1642 do
1643 if written then reset
1644 var it = items
1645 var id = length - 1
1646 while id >= 0 do
1647 it[id] = it[id].to_upper
1648 id -= 1
1649 end
1650 end
1651
1652 redef fun lower
1653 do
1654 if written then reset
1655 var it = items
1656 var id = length - 1
1657 while id >= 0 do
1658 it[id] = it[id].to_lower
1659 id -= 1
1660 end
1661 end
1662 end
1663
1664 private class FlatBufferReverseIterator
1665 super IndexedIterator[Char]
1666
1667 var target: FlatBuffer
1668
1669 var target_items: NativeString
1670
1671 var curr_pos: Int
1672
1673 init with_pos(tgt: FlatBuffer, pos: Int)
1674 do
1675 target = tgt
1676 if tgt.length > 0 then target_items = tgt.items
1677 curr_pos = pos
1678 end
1679
1680 redef fun index do return curr_pos
1681
1682 redef fun is_ok do return curr_pos >= 0
1683
1684 redef fun item do return target_items[curr_pos]
1685
1686 redef fun next do curr_pos -= 1
1687
1688 end
1689
1690 private class FlatBufferCharView
1691 super BufferCharView
1692
1693 redef type SELFTYPE: FlatBuffer
1694
1695 redef fun [](index) do return target.items[index]
1696
1697 redef fun []=(index, item)
1698 do
1699 assert index >= 0 and index <= length
1700 if index == length then
1701 add(item)
1702 return
1703 end
1704 target.items[index] = item
1705 end
1706
1707 redef fun push(c)
1708 do
1709 target.add(c)
1710 end
1711
1712 redef fun add(c)
1713 do
1714 target.add(c)
1715 end
1716
1717 fun enlarge(cap: Int)
1718 do
1719 target.enlarge(cap)
1720 end
1721
1722 redef fun append(s)
1723 do
1724 var s_length = s.length
1725 if target.capacity < s.length then enlarge(s_length + target.length)
1726 end
1727
1728 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1729
1730 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1731
1732 end
1733
1734 private class FlatBufferIterator
1735 super IndexedIterator[Char]
1736
1737 var target: FlatBuffer
1738
1739 var target_items: NativeString
1740
1741 var curr_pos: Int
1742
1743 init with_pos(tgt: FlatBuffer, pos: Int)
1744 do
1745 target = tgt
1746 if tgt.length > 0 then target_items = tgt.items
1747 curr_pos = pos
1748 end
1749
1750 redef fun index do return curr_pos
1751
1752 redef fun is_ok do return curr_pos < target.length
1753
1754 redef fun item do return target_items[curr_pos]
1755
1756 redef fun next do curr_pos += 1
1757
1758 end
1759
1760 ###############################################################################
1761 # Refinement #
1762 ###############################################################################
1763
1764 redef class Object
1765 # User readable representation of `self`.
1766 fun to_s: String do return inspect
1767
1768 # The class name of the object in NativeString format.
1769 private fun native_class_name: NativeString is intern
1770
1771 # The class name of the object.
1772 #
1773 # assert 5.class_name == "Int"
1774 fun class_name: String do return native_class_name.to_s
1775
1776 # Developer readable representation of `self`.
1777 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1778 fun inspect: String
1779 do
1780 return "<{inspect_head}>"
1781 end
1782
1783 # Return "CLASSNAME:#OBJECTID".
1784 # This function is mainly used with the redefinition of the inspect method
1785 protected fun inspect_head: String
1786 do
1787 return "{class_name}:#{object_id.to_hex}"
1788 end
1789 end
1790
1791 redef class Bool
1792 # assert true.to_s == "true"
1793 # assert false.to_s == "false"
1794 redef fun to_s
1795 do
1796 if self then
1797 return once "true"
1798 else
1799 return once "false"
1800 end
1801 end
1802 end
1803
1804 redef class Int
1805
1806 # Wrapper of strerror C function
1807 private fun strerror_ext: NativeString is extern `{
1808 return strerror(recv);
1809 `}
1810
1811 # Returns a string describing error number
1812 fun strerror: String do return strerror_ext.to_s
1813
1814 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1815 # assume < to_c max const of char
1816 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1817 do
1818 var n: Int
1819 # Sign
1820 if self < 0 then
1821 n = - self
1822 s.chars[0] = '-'
1823 else if self == 0 then
1824 s.chars[0] = '0'
1825 return
1826 else
1827 n = self
1828 end
1829 # Fill digits
1830 var pos = digit_count(base) - 1
1831 while pos >= 0 and n > 0 do
1832 s.chars[pos] = (n % base).to_c
1833 n = n / base # /
1834 pos -= 1
1835 end
1836 end
1837
1838 # C function to convert an nit Int to a NativeString (char*)
1839 private fun native_int_to_s: NativeString is extern "native_int_to_s"
1840
1841 # return displayable int in base 10 and signed
1842 #
1843 # assert 1.to_s == "1"
1844 # assert (-123).to_s == "-123"
1845 redef fun to_s do
1846 return native_int_to_s.to_s
1847 end
1848
1849 # return displayable int in hexadecimal
1850 #
1851 # assert 1.to_hex == "1"
1852 # assert (-255).to_hex == "-ff"
1853 fun to_hex: String do return to_base(16,false)
1854
1855 # return displayable int in base base and signed
1856 fun to_base(base: Int, signed: Bool): String
1857 do
1858 var l = digit_count(base)
1859 var s = new FlatBuffer.from(" " * l)
1860 fill_buffer(s, base, signed)
1861 return s.to_s
1862 end
1863 end
1864
1865 redef class Float
1866 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1867 #
1868 # assert 12.34.to_s == "12.34"
1869 # assert (-0120.030).to_s == "-120.03"
1870 #
1871 # see `to_precision` for a custom precision.
1872 redef fun to_s do
1873 var str = to_precision( 3 )
1874 if is_inf != 0 or is_nan then return str
1875 var len = str.length
1876 for i in [0..len-1] do
1877 var j = len-1-i
1878 var c = str.chars[j]
1879 if c == '0' then
1880 continue
1881 else if c == '.' then
1882 return str.substring( 0, j+2 )
1883 else
1884 return str.substring( 0, j+1 )
1885 end
1886 end
1887 return str
1888 end
1889
1890 # `String` representation of `self` with the given number of `decimals`
1891 #
1892 # assert 12.345.to_precision(0) == "12"
1893 # assert 12.345.to_precision(3) == "12.345"
1894 # assert (-12.345).to_precision(3) == "-12.345"
1895 # assert (-0.123).to_precision(3) == "-0.123"
1896 # assert 0.999.to_precision(2) == "1.00"
1897 # assert 0.999.to_precision(4) == "0.9990"
1898 fun to_precision(decimals: Int): String
1899 do
1900 if is_nan then return "nan"
1901
1902 var isinf = self.is_inf
1903 if isinf == 1 then
1904 return "inf"
1905 else if isinf == -1 then
1906 return "-inf"
1907 end
1908
1909 if decimals == 0 then return self.to_i.to_s
1910 var f = self
1911 for i in [0..decimals[ do f = f * 10.0
1912 if self > 0.0 then
1913 f = f + 0.5
1914 else
1915 f = f - 0.5
1916 end
1917 var i = f.to_i
1918 if i == 0 then return "0." + "0"*decimals
1919
1920 # Prepare both parts of the float, before and after the "."
1921 var s = i.abs.to_s
1922 var sl = s.length
1923 var p1
1924 var p2
1925 if sl > decimals then
1926 # Has something before the "."
1927 p1 = s.substring(0, sl-decimals)
1928 p2 = s.substring(sl-decimals, decimals)
1929 else
1930 p1 = "0"
1931 p2 = "0"*(decimals-sl) + s
1932 end
1933
1934 if i < 0 then p1 = "-" + p1
1935
1936 return p1 + "." + p2
1937 end
1938
1939 # `self` representation with `nb` digits after the '.'.
1940 #
1941 # assert 12.345.to_precision_native(1) == "12.3"
1942 # assert 12.345.to_precision_native(2) == "12.35"
1943 # assert 12.345.to_precision_native(3) == "12.345"
1944 # assert 12.345.to_precision_native(4) == "12.3450"
1945 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1946 int size;
1947 char *str;
1948
1949 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1950 str = malloc(size + 1);
1951 sprintf(str, "%.*f", (int)nb, recv );
1952
1953 return NativeString_to_s( str );
1954 `}
1955 end
1956
1957 redef class Char
1958 # assert 'x'.to_s == "x"
1959 redef fun to_s
1960 do
1961 var s = new FlatBuffer.with_capacity(1)
1962 s.chars[0] = self
1963 return s.to_s
1964 end
1965
1966 # Returns true if the char is a numerical digit
1967 #
1968 # assert '0'.is_numeric
1969 # assert '9'.is_numeric
1970 # assert not 'a'.is_numeric
1971 # assert not '?'.is_numeric
1972 fun is_numeric: Bool
1973 do
1974 return self >= '0' and self <= '9'
1975 end
1976
1977 # Returns true if the char is an alpha digit
1978 #
1979 # assert 'a'.is_alpha
1980 # assert 'Z'.is_alpha
1981 # assert not '0'.is_alpha
1982 # assert not '?'.is_alpha
1983 fun is_alpha: Bool
1984 do
1985 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1986 end
1987
1988 # Returns true if the char is an alpha or a numeric digit
1989 #
1990 # assert 'a'.is_alphanumeric
1991 # assert 'Z'.is_alphanumeric
1992 # assert '0'.is_alphanumeric
1993 # assert '9'.is_alphanumeric
1994 # assert not '?'.is_alphanumeric
1995 fun is_alphanumeric: Bool
1996 do
1997 return self.is_numeric or self.is_alpha
1998 end
1999 end
2000
2001 redef class Collection[E]
2002 # Concatenate elements.
2003 redef fun to_s
2004 do
2005 var s = new FlatBuffer
2006 for e in self do if e != null then s.append(e.to_s)
2007 return s.to_s
2008 end
2009
2010 # Concatenate and separate each elements with `sep`.
2011 #
2012 # assert [1, 2, 3].join(":") == "1:2:3"
2013 # assert [1..3].join(":") == "1:2:3"
2014 fun join(sep: Text): String
2015 do
2016 if is_empty then return ""
2017
2018 var s = new FlatBuffer # Result
2019
2020 # Concat first item
2021 var i = iterator
2022 var e = i.item
2023 if e != null then s.append(e.to_s)
2024
2025 # Concat other items
2026 i.next
2027 while i.is_ok do
2028 s.append(sep)
2029 e = i.item
2030 if e != null then s.append(e.to_s)
2031 i.next
2032 end
2033 return s.to_s
2034 end
2035 end
2036
2037 redef class Array[E]
2038
2039 # Fast implementation
2040 redef fun to_s
2041 do
2042 var l = length
2043 if l == 0 then return ""
2044 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2045 var its = _items
2046 var na = new NativeArray[String](l)
2047 var i = 0
2048 var sl = 0
2049 var mypos = 0
2050 while i < l do
2051 var itsi = its[i]
2052 if itsi == null then
2053 i += 1
2054 continue
2055 end
2056 var tmp = itsi.to_s
2057 sl += tmp.length
2058 na[mypos] = tmp
2059 i += 1
2060 mypos += 1
2061 end
2062 var ns = new NativeString(sl + 1)
2063 ns[sl] = '\0'
2064 i = 0
2065 var off = 0
2066 while i < mypos do
2067 var tmp = na[i]
2068 var tpl = tmp.length
2069 if tmp isa FlatString then
2070 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2071 off += tpl
2072 else
2073 for j in tmp.substrings do
2074 var s = j.as(FlatString)
2075 var slen = s.length
2076 s.items.copy_to(ns, slen, s.index_from, off)
2077 off += slen
2078 end
2079 end
2080 i += 1
2081 end
2082 return ns.to_s_with_length(sl)
2083 end
2084 end
2085
2086 redef class Map[K,V]
2087 # Concatenate couple of 'key value'.
2088 # key and value are separated by `couple_sep`.
2089 # each couple is separated each couple with `sep`.
2090 #
2091 # var m = new ArrayMap[Int, String]
2092 # m[1] = "one"
2093 # m[10] = "ten"
2094 # assert m.join("; ", "=") == "1=one; 10=ten"
2095 fun join(sep: String, couple_sep: String): String
2096 do
2097 if is_empty then return ""
2098
2099 var s = new FlatBuffer # Result
2100
2101 # Concat first item
2102 var i = iterator
2103 var k = i.key
2104 var e = i.item
2105 s.append("{k}{couple_sep}{e or else "<null>"}")
2106
2107 # Concat other items
2108 i.next
2109 while i.is_ok do
2110 s.append(sep)
2111 k = i.key
2112 e = i.item
2113 s.append("{k}{couple_sep}{e or else "<null>"}")
2114 i.next
2115 end
2116 return s.to_s
2117 end
2118 end
2119
2120 ###############################################################################
2121 # Native classes #
2122 ###############################################################################
2123
2124 # Native strings are simple C char *
2125 extern class NativeString `{ char* `}
2126 # Creates a new NativeString with a capacity of `length`
2127 new(length: Int) is intern
2128
2129 # Get char at `index`.
2130 fun [](index: Int): Char is intern
2131
2132 # Set char `item` at index.
2133 fun []=(index: Int, item: Char) is intern
2134
2135 # Copy `self` to `dest`.
2136 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2137
2138 # Position of the first nul character.
2139 fun cstring_length: Int
2140 do
2141 var l = 0
2142 while self[l] != '\0' do l += 1
2143 return l
2144 end
2145
2146 # Parse `self` as an Int.
2147 fun atoi: Int is intern
2148
2149 # Parse `self` as a Float.
2150 fun atof: Float is extern "atof"
2151
2152 redef fun to_s
2153 do
2154 return to_s_with_length(cstring_length)
2155 end
2156
2157 # Returns `self` as a String of `length`.
2158 fun to_s_with_length(length: Int): FlatString
2159 do
2160 assert length >= 0
2161 var str = new FlatString.with_infos(self, length, 0, length - 1)
2162 return str
2163 end
2164
2165 # Returns `self` as a new String.
2166 fun to_s_with_copy: FlatString
2167 do
2168 var length = cstring_length
2169 var new_self = new NativeString(length + 1)
2170 copy_to(new_self, length, 0, 0)
2171 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2172 new_self[length] = '\0'
2173 str.real_items = new_self
2174 return str
2175 end
2176 end
2177
2178 redef class Sys
2179 private var args_cache: nullable Sequence[String]
2180
2181 # The arguments of the program as given by the OS
2182 fun program_args: Sequence[String]
2183 do
2184 if _args_cache == null then init_args
2185 return _args_cache.as(not null)
2186 end
2187
2188 # The name of the program as given by the OS
2189 fun program_name: String
2190 do
2191 return native_argv(0).to_s
2192 end
2193
2194 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2195 private fun init_args
2196 do
2197 var argc = native_argc
2198 var args = new Array[String].with_capacity(0)
2199 var i = 1
2200 while i < argc do
2201 args[i-1] = native_argv(i).to_s
2202 i += 1
2203 end
2204 _args_cache = args
2205 end
2206
2207 # First argument of the main C function.
2208 private fun native_argc: Int is intern
2209
2210 # Second argument of the main C function.
2211 private fun native_argv(i: Int): NativeString is intern
2212 end
2213
2214 # Comparator that efficienlty use `to_s` to compare things
2215 #
2216 # The comparaison call `to_s` on object and use the result to order things.
2217 #
2218 # var a = [1, 2, 3, 10, 20]
2219 # (new CachedAlphaComparator).sort(a)
2220 # assert a == [1, 10, 2, 20, 3]
2221 #
2222 # Internally the result of `to_s` is cached in a HashMap to counter
2223 # uneficient implementation of `to_s`.
2224 #
2225 # Note: it caching is not usefull, see `alpha_comparator`
2226 class CachedAlphaComparator
2227 super Comparator
2228 redef type COMPARED: Object
2229
2230 private var cache = new HashMap[Object, String]
2231
2232 private fun do_to_s(a: Object): String do
2233 if cache.has_key(a) then return cache[a]
2234 var res = a.to_s
2235 cache[a] = res
2236 return res
2237 end
2238
2239 redef fun compare(a, b) do
2240 return do_to_s(a) <=> do_to_s(b)
2241 end
2242 end
2243
2244 # see `alpha_comparator`
2245 private class AlphaComparator
2246 super Comparator
2247 redef fun compare(a, b) do return a.to_s <=> b.to_s
2248 end
2249
2250 # Stateless comparator that naively use `to_s` to compare things.
2251 #
2252 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2253 # on a single instace. See `CachedAlphaComparator` as an alternative.
2254 #
2255 # var a = [1, 2, 3, 10, 20]
2256 # alpha_comparator.sort(a)
2257 # assert a == [1, 10, 2, 20, 3]
2258 fun alpha_comparator: Comparator do return once new AlphaComparator
2259
2260 # The arguments of the program as given by the OS
2261 fun args: Sequence[String]
2262 do
2263 return sys.program_args
2264 end