Merge: example: add 24 game task of Rosetta code
[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[FlatText] 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 is abstract
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 <= '7', return the corresponding integer.
253 #
254 # assert "714".to_oct == 460
255 fun to_oct: Int do return a_to(8)
256
257 # If `self` contains only '0' et '1', return the corresponding integer.
258 #
259 # assert "101101".to_bin == 45
260 fun to_bin: Int do return a_to(2)
261
262 # If `self` contains only digits and letters, return the corresponding integer in a given base
263 #
264 # assert "120".a_to(3) == 15
265 fun a_to(base: Int) : Int
266 do
267 var i = 0
268 var neg = false
269
270 for j in [0..length[ do
271 var c = chars[j]
272 var v = c.to_i
273 if v > base then
274 if neg then
275 return -i
276 else
277 return i
278 end
279 else if v < 0 then
280 neg = true
281 else
282 i = i * base + v
283 end
284 end
285 if neg then
286 return -i
287 else
288 return i
289 end
290 end
291
292 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
293 #
294 # assert "123".is_numeric == true
295 # assert "1.2".is_numeric == true
296 # assert "1,2".is_numeric == true
297 # assert "1..2".is_numeric == false
298 fun is_numeric: Bool
299 do
300 var has_point_or_comma = false
301 for i in [0..length[ do
302 var c = chars[i]
303 if not c.is_numeric then
304 if (c == '.' or c == ',') and not has_point_or_comma then
305 has_point_or_comma = true
306 else
307 return false
308 end
309 end
310 end
311 return true
312 end
313
314 # Returns `true` if the string contains only Hex chars
315 #
316 # assert "048bf".is_hex == true
317 # assert "ABCDEF".is_hex == true
318 # assert "0G".is_hex == false
319 fun is_hex: Bool
320 do
321 for i in [0..length[ do
322 var c = chars[i]
323 if not (c >= 'a' and c <= 'f') and
324 not (c >= 'A' and c <= 'F') and
325 not (c >= '0' and c <= '9') then return false
326 end
327 return true
328 end
329
330 # Are all letters in `self` upper-case ?
331 #
332 # assert "HELLO WORLD".is_upper == true
333 # assert "%$&%!".is_upper == true
334 # assert "hello world".is_upper == false
335 # assert "Hello World".is_upper == false
336 fun is_upper: Bool
337 do
338 for i in [0..length[ do
339 var char = chars[i]
340 if char.is_lower then return false
341 end
342 return true
343 end
344
345 # Are all letters in `self` lower-case ?
346 #
347 # assert "hello world".is_lower == true
348 # assert "%$&%!".is_lower == true
349 # assert "Hello World".is_lower == false
350 fun is_lower: Bool
351 do
352 for i in [0..length[ do
353 var char = chars[i]
354 if char.is_upper then return false
355 end
356 return true
357 end
358
359 # Removes the whitespaces at the beginning of self
360 #
361 # assert " \n\thello \n\t".l_trim == "hello \n\t"
362 #
363 # `Char::is_whitespace` determines what is a whitespace.
364 fun l_trim: SELFTYPE
365 do
366 var iter = self.chars.iterator
367 while iter.is_ok do
368 if not iter.item.is_whitespace then break
369 iter.next
370 end
371 if iter.index == length then return self.empty
372 return self.substring_from(iter.index)
373 end
374
375 # Removes the whitespaces at the end of self
376 #
377 # assert " \n\thello \n\t".r_trim == " \n\thello"
378 #
379 # `Char::is_whitespace` determines what is a whitespace.
380 fun r_trim: SELFTYPE
381 do
382 var iter = self.chars.reverse_iterator
383 while iter.is_ok do
384 if not iter.item.is_whitespace then break
385 iter.next
386 end
387 if iter.index < 0 then return self.empty
388 return self.substring(0, iter.index + 1)
389 end
390
391 # Trims trailing and preceding white spaces
392 #
393 # assert " Hello World ! ".trim == "Hello World !"
394 # assert "\na\nb\tc\t".trim == "a\nb\tc"
395 #
396 # `Char::is_whitespace` determines what is a whitespace.
397 fun trim: SELFTYPE do return (self.l_trim).r_trim
398
399 # Is the string non-empty but only made of whitespaces?
400 #
401 # assert " \n\t ".is_whitespace == true
402 # assert " hello ".is_whitespace == false
403 # assert "".is_whitespace == false
404 #
405 # `Char::is_whitespace` determines what is a whitespace.
406 fun is_whitespace: Bool
407 do
408 if is_empty then return false
409 for c in self.chars do
410 if not c.is_whitespace then return false
411 end
412 return true
413 end
414
415 # Returns `self` removed from its last line terminator (if any).
416 #
417 # assert "Hello\n".chomp == "Hello"
418 # assert "Hello".chomp == "Hello"
419 #
420 # assert "\n".chomp == ""
421 # assert "".chomp == ""
422 #
423 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
424 # A single line terminator, the last one, is removed.
425 #
426 # assert "\r\n".chomp == ""
427 # assert "\r\n\n".chomp == "\r\n"
428 # assert "\r\n\r\n".chomp == "\r\n"
429 # assert "\r\n\r".chomp == "\r\n"
430 #
431 # Note: unlike with most IO methods like `Reader::read_line`,
432 # a single `\r` is considered here to be a line terminator and will be removed.
433 fun chomp: SELFTYPE
434 do
435 var len = length
436 if len == 0 then return self
437 var l = self.chars.last
438 if l == '\r' then
439 return substring(0, len-1)
440 else if l != '\n' then
441 return self
442 else if len > 1 and self.chars[len-2] == '\r' then
443 return substring(0, len-2)
444 else
445 return substring(0, len-1)
446 end
447 end
448
449 # Justify a self in a space of `length`
450 #
451 # `left` is the space ratio on the left side.
452 # * 0.0 for left-justified (no space at the left)
453 # * 1.0 for right-justified (all spaces at the left)
454 # * 0.5 for centered (half the spaces at the left)
455 #
456 # Examples
457 #
458 # assert "hello".justify(10, 0.0) == "hello "
459 # assert "hello".justify(10, 1.0) == " hello"
460 # assert "hello".justify(10, 0.5) == " hello "
461 #
462 # If `length` is not enough, `self` is returned as is.
463 #
464 # assert "hello".justify(2, 0.0) == "hello"
465 #
466 # REQUIRE: `left >= 0.0 and left <= 1.0`
467 # ENSURE: `self.length <= length implies result.length == length`
468 # ENSURE: `self.length >= length implies result == self`
469 fun justify(length: Int, left: Float): String
470 do
471 var diff = length - self.length
472 if diff <= 0 then return to_s
473 assert left >= 0.0 and left <= 1.0
474 var before = (diff.to_f * left).to_i
475 return " " * before + self + " " * (diff-before)
476 end
477
478 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
479 #
480 # This method is injective (two different inputs never produce the same
481 # output) and the returned string always respect the following rules:
482 #
483 # * Contains only US-ASCII letters, digits and underscores.
484 # * Never starts with a digit.
485 # * Never ends with an underscore.
486 # * Never contains two contiguous underscores.
487 #
488 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
489 # assert "__".to_cmangle == "_95d_95d"
490 # assert "__d".to_cmangle == "_95d_d"
491 # assert "_d_".to_cmangle == "_d_95d"
492 # assert "_42".to_cmangle == "_95d42"
493 # assert "foo".to_cmangle == "foo"
494 # assert "".to_cmangle == ""
495 fun to_cmangle: String
496 do
497 if is_empty then return ""
498 var res = new Buffer
499 var underscore = false
500 var start = 0
501 var c = chars[0]
502
503 if c >= '0' and c <= '9' then
504 res.add('_')
505 res.append(c.ascii.to_s)
506 res.add('d')
507 start = 1
508 end
509 for i in [start..length[ do
510 c = chars[i]
511 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
512 res.add(c)
513 underscore = false
514 continue
515 end
516 if underscore then
517 res.append('_'.ascii.to_s)
518 res.add('d')
519 end
520 if c >= '0' and c <= '9' then
521 res.add(c)
522 underscore = false
523 else if c == '_' then
524 res.add(c)
525 underscore = true
526 else
527 res.add('_')
528 res.append(c.ascii.to_s)
529 res.add('d')
530 underscore = false
531 end
532 end
533 if underscore then
534 res.append('_'.ascii.to_s)
535 res.add('d')
536 end
537 return res.to_s
538 end
539
540 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
541 #
542 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
543 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
544 #
545 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
546 # Three digits are always used to avoid following digits to be interpreted as an element
547 # of the octal sequence.
548 #
549 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
550 #
551 # The exceptions are the common `\t` and `\n`.
552 fun escape_to_c: String
553 do
554 var b = new Buffer
555 for i in [0..length[ do
556 var c = chars[i]
557 if c == '\n' then
558 b.append("\\n")
559 else if c == '\t' then
560 b.append("\\t")
561 else if c == '\0' then
562 b.append("\\000")
563 else if c == '"' then
564 b.append("\\\"")
565 else if c == '\'' then
566 b.append("\\\'")
567 else if c == '\\' then
568 b.append("\\\\")
569 else if c.ascii < 32 then
570 b.add('\\')
571 var oct = c.ascii.to_base(8, false)
572 # Force 3 octal digits since it is the
573 # maximum allowed in the C specification
574 if oct.length == 1 then
575 b.add('0')
576 b.add('0')
577 else if oct.length == 2 then
578 b.add('0')
579 end
580 b.append(oct)
581 else
582 b.add(c)
583 end
584 end
585 return b.to_s
586 end
587
588 # Escape additionnal characters
589 # The result might no be legal in C but be used in other languages
590 #
591 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
592 fun escape_more_to_c(chars: String): String
593 do
594 var b = new Buffer
595 for c in escape_to_c.chars do
596 if chars.chars.has(c) then
597 b.add('\\')
598 end
599 b.add(c)
600 end
601 return b.to_s
602 end
603
604 # Escape to C plus braces
605 #
606 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
607 fun escape_to_nit: String do return escape_more_to_c("\{\}")
608
609 # Escape to POSIX Shell (sh).
610 #
611 # Abort if the text contains a null byte.
612 #
613 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
614 fun escape_to_sh: String do
615 var b = new Buffer
616 b.chars.add '\''
617 for i in [0..length[ do
618 var c = chars[i]
619 if c == '\'' then
620 b.append("'\\''")
621 else
622 assert without_null_byte: c != '\0'
623 b.add(c)
624 end
625 end
626 b.chars.add '\''
627 return b.to_s
628 end
629
630 # Escape to include in a Makefile
631 #
632 # Unfortunately, some characters are not escapable in Makefile.
633 # These characters are `;`, `|`, `\`, and the non-printable ones.
634 # They will be rendered as `"?{hex}"`.
635 fun escape_to_mk: String do
636 var b = new Buffer
637 for i in [0..length[ do
638 var c = chars[i]
639 if c == '$' then
640 b.append("$$")
641 else if c == ':' or c == ' ' or c == '#' then
642 b.add('\\')
643 b.add(c)
644 else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
645 b.append("?{c.ascii.to_base(16, false)}")
646 else
647 b.add(c)
648 end
649 end
650 return b.to_s
651 end
652
653 # Return a string where Nit escape sequences are transformed.
654 #
655 # var s = "\\n"
656 # assert s.length == 2
657 # var u = s.unescape_nit
658 # assert u.length == 1
659 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
660 fun unescape_nit: String
661 do
662 var res = new Buffer.with_cap(self.length)
663 var was_slash = false
664 for i in [0..length[ do
665 var c = chars[i]
666 if not was_slash then
667 if c == '\\' then
668 was_slash = true
669 else
670 res.add(c)
671 end
672 continue
673 end
674 was_slash = false
675 if c == 'n' then
676 res.add('\n')
677 else if c == 'r' then
678 res.add('\r')
679 else if c == 't' then
680 res.add('\t')
681 else if c == '0' then
682 res.add('\0')
683 else
684 res.add(c)
685 end
686 end
687 return res.to_s
688 end
689
690 # Encode `self` to percent (or URL) encoding
691 #
692 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
693 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
694 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
695 fun to_percent_encoding: String
696 do
697 var buf = new Buffer
698
699 for i in [0..length[ do
700 var c = chars[i]
701 if (c >= '0' and c <= '9') or
702 (c >= 'a' and c <= 'z') or
703 (c >= 'A' and c <= 'Z') or
704 c == '-' or c == '.' or
705 c == '_' or c == '~'
706 then
707 buf.add c
708 else buf.append "%{c.ascii.to_hex}"
709 end
710
711 return buf.to_s
712 end
713
714 # Decode `self` from percent (or URL) encoding to a clear string
715 #
716 # Replace invalid use of '%' with '?'.
717 #
718 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
719 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
720 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
721 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
722 # assert "incomplete %".from_percent_encoding == "incomplete ?"
723 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
724 fun from_percent_encoding: String
725 do
726 var buf = new Buffer
727
728 var i = 0
729 while i < length do
730 var c = chars[i]
731 if c == '%' then
732 if i + 2 >= length then
733 # What follows % has been cut off
734 buf.add '?'
735 else
736 i += 1
737 var hex_s = substring(i, 2)
738 if hex_s.is_hex then
739 var hex_i = hex_s.to_hex
740 buf.add hex_i.ascii
741 i += 1
742 else
743 # What follows a % is not Hex
744 buf.add '?'
745 i -= 1
746 end
747 end
748 else buf.add c
749
750 i += 1
751 end
752
753 return buf.to_s
754 end
755
756 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
757 #
758 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
759 #
760 # SEE: <https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content>
761 fun html_escape: String
762 do
763 var buf = new Buffer
764
765 for i in [0..length[ do
766 var c = chars[i]
767 if c == '&' then
768 buf.append "&amp;"
769 else if c == '<' then
770 buf.append "&lt;"
771 else if c == '>' then
772 buf.append "&gt;"
773 else if c == '"' then
774 buf.append "&#34;"
775 else if c == '\'' then
776 buf.append "&#39;"
777 else if c == '/' then
778 buf.append "&#47;"
779 else buf.add c
780 end
781
782 return buf.to_s
783 end
784
785 # Equality of text
786 # Two pieces of text are equals if thez have the same characters in the same order.
787 #
788 # assert "hello" == "hello"
789 # assert "hello" != "HELLO"
790 # assert "hello" == "hel"+"lo"
791 #
792 # Things that are not Text are not equal.
793 #
794 # assert "9" != '9'
795 # assert "9" != ['9']
796 # assert "9" != 9
797 #
798 # assert "9".chars.first == '9' # equality of Char
799 # assert "9".chars == ['9'] # equality of Sequence
800 # assert "9".to_i == 9 # equality of Int
801 redef fun ==(o)
802 do
803 if o == null then return false
804 if not o isa Text then return false
805 if self.is_same_instance(o) then return true
806 if self.length != o.length then return false
807 return self.chars == o.chars
808 end
809
810 # Lexicographical comparaison
811 #
812 # assert "abc" < "xy"
813 # assert "ABC" < "abc"
814 redef fun <(other)
815 do
816 var self_chars = self.chars.iterator
817 var other_chars = other.chars.iterator
818
819 while self_chars.is_ok and other_chars.is_ok do
820 if self_chars.item < other_chars.item then return true
821 if self_chars.item > other_chars.item then return false
822 self_chars.next
823 other_chars.next
824 end
825
826 if self_chars.is_ok then
827 return false
828 else
829 return true
830 end
831 end
832
833 # Escape string used in labels for graphviz
834 #
835 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
836 fun escape_to_dot: String
837 do
838 return escape_more_to_c("|\{\}<>")
839 end
840
841 private var hash_cache: nullable Int = null
842
843 redef fun hash
844 do
845 if hash_cache == null then
846 # djb2 hash algorithm
847 var h = 5381
848
849 for i in [0..length[ do
850 var char = chars[i]
851 h = h.lshift(5) + h + char.ascii
852 end
853
854 hash_cache = h
855 end
856 return hash_cache.as(not null)
857 end
858
859 # Gives the formatted string back as a Nit string with `args` in place
860 #
861 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
862 # assert "\\%1 This string".format("String") == "\\%1 This string"
863 fun format(args: Object...): String do
864 var s = new Array[Text]
865 var curr_st = 0
866 var i = 0
867 while i < length do
868 # Skip escaped characters
869 if self[i] == '\\' then
870 i += 1
871 # In case of format
872 else if self[i] == '%' then
873 var fmt_st = i
874 i += 1
875 var ciph_st = i
876 while i < length and self[i].is_numeric do
877 i += 1
878 end
879 i -= 1
880 var fmt_end = i
881 var ciph_len = fmt_end - ciph_st + 1
882 s.push substring(curr_st, fmt_st - curr_st)
883 s.push args[substring(ciph_st, ciph_len).to_i - 1].to_s
884 curr_st = i + 1
885 end
886 i += 1
887 end
888 s.push substring(curr_st, length - curr_st)
889 return s.to_s
890 end
891
892 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
893 #
894 # Basically a high-level synonym of NativeString::copy_to
895 #
896 # REQUIRE: `n` must be large enough to contain `len` bytes
897 #
898 # var ns = new NativeString(8)
899 # "Text is String".copy_to_native(ns, 8, 2, 0)
900 # assert ns.to_s_with_length(8) == "xt is St"
901 #
902 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
903 var mypos = src_offset
904 var itspos = dest_offset
905 while n > 0 do
906 dest[itspos] = self.chars[mypos]
907 itspos += 1
908 mypos += 1
909 n -= 1
910 end
911 end
912
913 end
914
915 # All kinds of array-based text representations.
916 abstract class FlatText
917 super Text
918
919 # Underlying C-String (`char*`)
920 #
921 # Warning : Might be void in some subclasses, be sure to check
922 # if set before using it.
923 private var items: NativeString is noinit
924
925 # Real items, used as cache for to_cstring is called
926 private var real_items: nullable NativeString = null
927
928 # Returns a char* starting at position `index_from`
929 #
930 # WARNING: If you choose to use this service, be careful of the following.
931 #
932 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
933 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
934 # deallocated at any moment, rendering the pointer returned by this function invalid.
935 # Any access to freed memory may very likely cause undefined behaviour or a crash.
936 # (Failure to do so will most certainly result in long and painful debugging hours)
937 #
938 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
939 # then immediately return).
940 #
941 # As always, do not modify the content of the String in C code, if this is what you want
942 # copy locally the char* as Nit Strings are immutable.
943 private fun fast_cstring: NativeString is abstract
944
945 redef var length = 0
946
947 redef fun output
948 do
949 var i = 0
950 while i < length do
951 items[i].output
952 i += 1
953 end
954 end
955
956 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
957 items.copy_to(dest, n, src_offset, dest_offset)
958 end
959 end
960
961 # Abstract class for the SequenceRead compatible
962 # views on String and Buffer objects
963 private abstract class StringCharView
964 super SequenceRead[Char]
965
966 type SELFTYPE: Text
967
968 var target: SELFTYPE
969
970 redef fun is_empty do return target.is_empty
971
972 redef fun length do return target.length
973
974 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
975
976 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
977 end
978
979 # View on Buffer objects, extends Sequence
980 # for mutation operations
981 private abstract class BufferCharView
982 super StringCharView
983 super Sequence[Char]
984
985 redef type SELFTYPE: Buffer
986
987 end
988
989 # A `String` holds and manipulates an arbitrary sequence of characters.
990 #
991 # String objects may be created using literals.
992 #
993 # assert "Hello World!" isa String
994 abstract class String
995 super Text
996
997 redef type SELFTYPE: String is fixed
998
999 redef fun to_s do return self
1000
1001 # Concatenates `o` to `self`
1002 #
1003 # assert "hello" + "world" == "helloworld"
1004 # assert "" + "hello" + "" == "hello"
1005 fun +(o: Text): SELFTYPE is abstract
1006
1007 # Concatenates self `i` times
1008 #
1009 # assert "abc" * 4 == "abcabcabcabc"
1010 # assert "abc" * 1 == "abc"
1011 # assert "abc" * 0 == ""
1012 fun *(i: Int): SELFTYPE is abstract
1013
1014 # Insert `s` at `pos`.
1015 #
1016 # assert "helloworld".insert_at(" ", 5) == "hello world"
1017 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1018
1019 redef fun substrings is abstract
1020
1021 # Returns a reversed version of self
1022 #
1023 # assert "hello".reversed == "olleh"
1024 # assert "bob".reversed == "bob"
1025 # assert "".reversed == ""
1026 fun reversed: SELFTYPE is abstract
1027
1028 # A upper case version of `self`
1029 #
1030 # assert "Hello World!".to_upper == "HELLO WORLD!"
1031 fun to_upper: SELFTYPE is abstract
1032
1033 # A lower case version of `self`
1034 #
1035 # assert "Hello World!".to_lower == "hello world!"
1036 fun to_lower : SELFTYPE is abstract
1037
1038 # Takes a camel case `self` and converts it to snake case
1039 #
1040 # assert "randomMethodId".to_snake_case == "random_method_id"
1041 #
1042 # The rules are the following:
1043 #
1044 # An uppercase is always converted to a lowercase
1045 #
1046 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1047 #
1048 # An uppercase that follows a lowercase is prefixed with an underscore
1049 #
1050 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1051 #
1052 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1053 #
1054 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1055 #
1056 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1057 #
1058 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1059 fun to_snake_case: SELFTYPE
1060 do
1061 if self.is_lower then return self
1062
1063 var new_str = new Buffer.with_cap(self.length)
1064 var prev_is_lower = false
1065 var prev_is_upper = false
1066
1067 for i in [0..length[ do
1068 var char = chars[i]
1069 if char.is_lower then
1070 new_str.add(char)
1071 prev_is_lower = true
1072 prev_is_upper = false
1073 else if char.is_upper then
1074 if prev_is_lower then
1075 new_str.add('_')
1076 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1077 new_str.add('_')
1078 end
1079 new_str.add(char.to_lower)
1080 prev_is_lower = false
1081 prev_is_upper = true
1082 else
1083 new_str.add(char)
1084 prev_is_lower = false
1085 prev_is_upper = false
1086 end
1087 end
1088
1089 return new_str.to_s
1090 end
1091
1092 # Takes a snake case `self` and converts it to camel case
1093 #
1094 # assert "random_method_id".to_camel_case == "randomMethodId"
1095 #
1096 # If the identifier is prefixed by an underscore, the underscore is ignored
1097 #
1098 # assert "_private_field".to_camel_case == "_privateField"
1099 #
1100 # If `self` is upper, it is returned unchanged
1101 #
1102 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1103 #
1104 # If there are several consecutive underscores, they are considered as a single one
1105 #
1106 # assert "random__method_id".to_camel_case == "randomMethodId"
1107 fun to_camel_case: SELFTYPE
1108 do
1109 if self.is_upper then return self
1110
1111 var new_str = new Buffer
1112 var is_first_char = true
1113 var follows_us = false
1114
1115 for i in [0..length[ do
1116 var char = chars[i]
1117 if is_first_char then
1118 new_str.add(char)
1119 is_first_char = false
1120 else if char == '_' then
1121 follows_us = true
1122 else if follows_us then
1123 new_str.add(char.to_upper)
1124 follows_us = false
1125 else
1126 new_str.add(char)
1127 end
1128 end
1129
1130 return new_str.to_s
1131 end
1132
1133 # Returns a capitalized `self`
1134 #
1135 # Letters that follow a letter are lowercased
1136 # Letters that follow a non-letter are upcased.
1137 #
1138 # SEE : `Char::is_letter` for the definition of letter.
1139 #
1140 # assert "jAVASCRIPT".capitalized == "Javascript"
1141 # assert "i am root".capitalized == "I Am Root"
1142 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1143 fun capitalized: SELFTYPE do
1144 if length == 0 then return self
1145
1146 var buf = new Buffer.with_cap(length)
1147
1148 var curr = chars[0].to_upper
1149 var prev = curr
1150 buf[0] = curr
1151
1152 for i in [1 .. length[ do
1153 prev = curr
1154 curr = self[i]
1155 if prev.is_letter then
1156 buf[i] = curr.to_lower
1157 else
1158 buf[i] = curr.to_upper
1159 end
1160 end
1161
1162 return buf.to_s
1163 end
1164 end
1165
1166 private class FlatSubstringsIter
1167 super Iterator[FlatText]
1168
1169 var tgt: nullable FlatText
1170
1171 redef fun item do
1172 assert is_ok
1173 return tgt.as(not null)
1174 end
1175
1176 redef fun is_ok do return tgt != null
1177
1178 redef fun next do tgt = null
1179 end
1180
1181 # Immutable strings of characters.
1182 class FlatString
1183 super FlatText
1184 super String
1185
1186 # Index in _items of the start of the string
1187 private var index_from: Int is noinit
1188
1189 # Indes in _items of the last item of the string
1190 private var index_to: Int is noinit
1191
1192 redef var chars = new FlatStringCharView(self) is lazy
1193
1194 redef fun [](index)
1195 do
1196 # Check that the index (+ index_from) is not larger than indexTo
1197 # In other terms, if the index is valid
1198 assert index >= 0
1199 assert (index + index_from) <= index_to
1200 return items[index + index_from]
1201 end
1202
1203 ################################################
1204 # AbstractString specific methods #
1205 ################################################
1206
1207 redef fun reversed
1208 do
1209 var native = new NativeString(self.length + 1)
1210 var length = self.length
1211 var items = self.items
1212 var pos = 0
1213 var ipos = length-1
1214 while pos < length do
1215 native[pos] = items[ipos]
1216 pos += 1
1217 ipos -= 1
1218 end
1219 return native.to_s_with_length(self.length)
1220 end
1221
1222 redef fun fast_cstring do return items.fast_cstring(index_from)
1223
1224 redef fun substring(from, count)
1225 do
1226 assert count >= 0
1227
1228 if from < 0 then
1229 count += from
1230 if count < 0 then count = 0
1231 from = 0
1232 end
1233
1234 var new_from = index_from + from
1235
1236 if (new_from + count) > index_to then
1237 var new_len = index_to - new_from + 1
1238 if new_len <= 0 then return empty
1239 return new FlatString.with_infos(items, new_len, new_from, index_to)
1240 end
1241
1242 if count <= 0 then return empty
1243
1244 var to = new_from + count - 1
1245
1246 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1247 end
1248
1249 redef fun empty do return "".as(FlatString)
1250
1251 redef fun to_upper
1252 do
1253 var outstr = new NativeString(self.length + 1)
1254 var out_index = 0
1255
1256 var myitems = self.items
1257 var index_from = self.index_from
1258 var max = self.index_to
1259
1260 while index_from <= max do
1261 outstr[out_index] = myitems[index_from].to_upper
1262 out_index += 1
1263 index_from += 1
1264 end
1265
1266 outstr[self.length] = '\0'
1267
1268 return outstr.to_s_with_length(self.length)
1269 end
1270
1271 redef fun to_lower
1272 do
1273 var outstr = new NativeString(self.length + 1)
1274 var out_index = 0
1275
1276 var myitems = self.items
1277 var index_from = self.index_from
1278 var max = self.index_to
1279
1280 while index_from <= max do
1281 outstr[out_index] = myitems[index_from].to_lower
1282 out_index += 1
1283 index_from += 1
1284 end
1285
1286 outstr[self.length] = '\0'
1287
1288 return outstr.to_s_with_length(self.length)
1289 end
1290
1291 redef fun output
1292 do
1293 var i = self.index_from
1294 var imax = self.index_to
1295 while i <= imax do
1296 items[i].output
1297 i += 1
1298 end
1299 end
1300
1301 ##################################################
1302 # String Specific Methods #
1303 ##################################################
1304
1305 # Low-level creation of a new string with given data.
1306 #
1307 # `items` will be used as is, without copy, to retrieve the characters of the string.
1308 # Aliasing issues is the responsibility of the caller.
1309 private init with_infos(items: NativeString, length: Int, from: Int, to: Int)
1310 do
1311 self.items = items
1312 self.length = length
1313 index_from = from
1314 index_to = to
1315 end
1316
1317 redef fun to_cstring do
1318 if real_items != null then
1319 return real_items.as(not null)
1320 else
1321 var newItems = new NativeString(length + 1)
1322 self.items.copy_to(newItems, length, index_from, 0)
1323 newItems[length] = '\0'
1324 self.real_items = newItems
1325 return newItems
1326 end
1327 end
1328
1329 redef fun ==(other)
1330 do
1331 if not other isa FlatString then return super
1332
1333 if self.object_id == other.object_id then return true
1334
1335 var my_length = length
1336
1337 if other.length != my_length then return false
1338
1339 var my_index = index_from
1340 var its_index = other.index_from
1341
1342 var last_iteration = my_index + my_length
1343
1344 var itsitems = other.items
1345 var myitems = self.items
1346
1347 while my_index < last_iteration do
1348 if myitems[my_index] != itsitems[its_index] then return false
1349 my_index += 1
1350 its_index += 1
1351 end
1352
1353 return true
1354 end
1355
1356 redef fun <(other)
1357 do
1358 if not other isa FlatString then return super
1359
1360 if self.object_id == other.object_id then return false
1361
1362 var my_curr_char : Char
1363 var its_curr_char : Char
1364
1365 var curr_id_self = self.index_from
1366 var curr_id_other = other.index_from
1367
1368 var my_items = self.items
1369 var its_items = other.items
1370
1371 var my_length = self.length
1372 var its_length = other.length
1373
1374 var max_iterations = curr_id_self + my_length
1375
1376 while curr_id_self < max_iterations do
1377 my_curr_char = my_items[curr_id_self]
1378 its_curr_char = its_items[curr_id_other]
1379
1380 if my_curr_char != its_curr_char then
1381 if my_curr_char < its_curr_char then return true
1382 return false
1383 end
1384
1385 curr_id_self += 1
1386 curr_id_other += 1
1387 end
1388
1389 return my_length < its_length
1390 end
1391
1392 redef fun +(s)
1393 do
1394 var my_length = self.length
1395 var its_length = s.length
1396
1397 var total_length = my_length + its_length
1398
1399 var target_string = new NativeString(my_length + its_length + 1)
1400
1401 self.items.copy_to(target_string, my_length, index_from, 0)
1402 if s isa FlatString then
1403 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1404 else if s isa FlatBuffer then
1405 s.items.copy_to(target_string, its_length, 0, my_length)
1406 else
1407 var curr_pos = my_length
1408 for i in [0..s.length[ do
1409 var c = s.chars[i]
1410 target_string[curr_pos] = c
1411 curr_pos += 1
1412 end
1413 end
1414
1415 target_string[total_length] = '\0'
1416
1417 return target_string.to_s_with_length(total_length)
1418 end
1419
1420 redef fun *(i)
1421 do
1422 assert i >= 0
1423
1424 var my_length = self.length
1425
1426 var final_length = my_length * i
1427
1428 var my_items = self.items
1429
1430 var target_string = new NativeString(final_length + 1)
1431
1432 target_string[final_length] = '\0'
1433
1434 var current_last = 0
1435
1436 for iteration in [1 .. i] do
1437 my_items.copy_to(target_string, my_length, 0, current_last)
1438 current_last += my_length
1439 end
1440
1441 return target_string.to_s_with_length(final_length)
1442 end
1443
1444 redef fun hash
1445 do
1446 if hash_cache == null then
1447 # djb2 hash algorithm
1448 var h = 5381
1449 var i = index_from
1450
1451 var myitems = items
1452
1453 while i <= index_to do
1454 h = h.lshift(5) + h + myitems[i].ascii
1455 i += 1
1456 end
1457
1458 hash_cache = h
1459 end
1460
1461 return hash_cache.as(not null)
1462 end
1463
1464 redef fun substrings do return new FlatSubstringsIter(self)
1465 end
1466
1467 private class FlatStringReverseIterator
1468 super IndexedIterator[Char]
1469
1470 var target: FlatString
1471
1472 var target_items: NativeString
1473
1474 var curr_pos: Int
1475
1476 init with_pos(tgt: FlatString, pos: Int)
1477 do
1478 target = tgt
1479 target_items = tgt.items
1480 curr_pos = pos + tgt.index_from
1481 end
1482
1483 redef fun is_ok do return curr_pos >= target.index_from
1484
1485 redef fun item do return target_items[curr_pos]
1486
1487 redef fun next do curr_pos -= 1
1488
1489 redef fun index do return curr_pos - target.index_from
1490
1491 end
1492
1493 private class FlatStringIterator
1494 super IndexedIterator[Char]
1495
1496 var target: FlatString
1497
1498 var target_items: NativeString
1499
1500 var curr_pos: Int
1501
1502 init with_pos(tgt: FlatString, pos: Int)
1503 do
1504 target = tgt
1505 target_items = tgt.items
1506 curr_pos = pos + target.index_from
1507 end
1508
1509 redef fun is_ok do return curr_pos <= target.index_to
1510
1511 redef fun item do return target_items[curr_pos]
1512
1513 redef fun next do curr_pos += 1
1514
1515 redef fun index do return curr_pos - target.index_from
1516
1517 end
1518
1519 private class FlatStringCharView
1520 super StringCharView
1521
1522 redef type SELFTYPE: FlatString
1523
1524 redef fun [](index)
1525 do
1526 # Check that the index (+ index_from) is not larger than indexTo
1527 # In other terms, if the index is valid
1528 assert index >= 0
1529 var target = self.target
1530 assert (index + target.index_from) <= target.index_to
1531 return target.items[index + target.index_from]
1532 end
1533
1534 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1535
1536 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1537
1538 end
1539
1540 # A mutable sequence of characters.
1541 abstract class Buffer
1542 super Text
1543
1544 # New `Buffer` factory, will return a concrete `Buffer` type with default capacity
1545 new do return new FlatBuffer
1546
1547 # New `Buffer` factory, returns a concrete `Buffer` with a capacity of `i`
1548 new with_cap(i: Int) do return new FlatBuffer.with_capacity(i)
1549
1550 redef type SELFTYPE: Buffer is fixed
1551
1552 # Specific implementations MUST set this to `true` in order to invalidate caches
1553 protected var is_dirty = true
1554
1555 # Copy-On-Write flag
1556 #
1557 # If the `Buffer` was to_s'd, the next in-place altering
1558 # operation will cause the current `Buffer` to be re-allocated.
1559 #
1560 # The flag will then be set at `false`.
1561 protected var written = false
1562
1563 # Modifies the char contained at pos `index`
1564 #
1565 # DEPRECATED : Use self.chars.[]= instead
1566 fun []=(index: Int, item: Char) is abstract
1567
1568 # Adds a char `c` at the end of self
1569 #
1570 # DEPRECATED : Use self.chars.add instead
1571 fun add(c: Char) is abstract
1572
1573 # Clears the buffer
1574 #
1575 # var b = new Buffer
1576 # b.append "hello"
1577 # assert not b.is_empty
1578 # b.clear
1579 # assert b.is_empty
1580 fun clear is abstract
1581
1582 # Enlarges the subsequent array containing the chars of self
1583 fun enlarge(cap: Int) is abstract
1584
1585 # Adds the content of text `s` at the end of self
1586 #
1587 # var b = new Buffer
1588 # b.append "hello"
1589 # b.append "world"
1590 # assert b == "helloworld"
1591 fun append(s: Text) is abstract
1592
1593 # `self` is appended in such a way that `self` is repeated `r` times
1594 #
1595 # var b = new Buffer
1596 # b.append "hello"
1597 # b.times 3
1598 # assert b == "hellohellohello"
1599 fun times(r: Int) is abstract
1600
1601 # Reverses itself in-place
1602 #
1603 # var b = new Buffer
1604 # b.append("hello")
1605 # b.reverse
1606 # assert b == "olleh"
1607 fun reverse is abstract
1608
1609 # Changes each lower-case char in `self` by its upper-case variant
1610 #
1611 # var b = new Buffer
1612 # b.append("Hello World!")
1613 # b.upper
1614 # assert b == "HELLO WORLD!"
1615 fun upper is abstract
1616
1617 # Changes each upper-case char in `self` by its lower-case variant
1618 #
1619 # var b = new Buffer
1620 # b.append("Hello World!")
1621 # b.lower
1622 # assert b == "hello world!"
1623 fun lower is abstract
1624
1625 # Capitalizes each word in `self`
1626 #
1627 # Letters that follow a letter are lowercased
1628 # Letters that follow a non-letter are upcased.
1629 #
1630 # SEE: `Char::is_letter` for the definition of a letter.
1631 #
1632 # var b = new FlatBuffer.from("jAVAsCriPt")
1633 # b.capitalize
1634 # assert b == "Javascript"
1635 # b = new FlatBuffer.from("i am root")
1636 # b.capitalize
1637 # assert b == "I Am Root"
1638 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1639 # b.capitalize
1640 # assert b == "Ab_C -Ab0C Ab\nC"
1641 fun capitalize do
1642 if length == 0 then return
1643 var c = self[0].to_upper
1644 self[0] = c
1645 var prev = c
1646 for i in [1 .. length[ do
1647 prev = c
1648 c = self[i]
1649 if prev.is_letter then
1650 self[i] = c.to_lower
1651 else
1652 self[i] = c.to_upper
1653 end
1654 end
1655 end
1656
1657 redef fun hash
1658 do
1659 if is_dirty then hash_cache = null
1660 return super
1661 end
1662
1663 # In Buffers, the internal sequence of character is mutable
1664 # Thus, `chars` can be used to modify the buffer.
1665 redef fun chars: Sequence[Char] is abstract
1666 end
1667
1668 # Mutable strings of characters.
1669 class FlatBuffer
1670 super FlatText
1671 super Buffer
1672
1673 redef var chars: Sequence[Char] = new FlatBufferCharView(self) is lazy
1674
1675 private var capacity: Int = 0
1676
1677 redef fun fast_cstring do return items.fast_cstring(0)
1678
1679 redef fun substrings do return new FlatSubstringsIter(self)
1680
1681 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1682 #
1683 # This happens when an operation modifies the current `Buffer` and
1684 # the Copy-On-Write flag `written` is set at true.
1685 private fun reset do
1686 var nns = new NativeString(capacity)
1687 items.copy_to(nns, length, 0, 0)
1688 items = nns
1689 written = false
1690 end
1691
1692 redef fun [](index)
1693 do
1694 assert index >= 0
1695 assert index < length
1696 return items[index]
1697 end
1698
1699 redef fun []=(index, item)
1700 do
1701 is_dirty = true
1702 if index == length then
1703 add(item)
1704 return
1705 end
1706 if written then reset
1707 assert index >= 0 and index < length
1708 items[index] = item
1709 end
1710
1711 redef fun add(c)
1712 do
1713 is_dirty = true
1714 if capacity <= length then enlarge(length + 5)
1715 items[length] = c
1716 length += 1
1717 end
1718
1719 redef fun clear do
1720 is_dirty = true
1721 if written then reset
1722 length = 0
1723 end
1724
1725 redef fun empty do return new Buffer
1726
1727 redef fun enlarge(cap)
1728 do
1729 var c = capacity
1730 if cap <= c then return
1731 while c <= cap do c = c * 2 + 2
1732 # The COW flag can be set at false here, since
1733 # it does a copy of the current `Buffer`
1734 written = false
1735 var a = new NativeString(c+1)
1736 if length > 0 then items.copy_to(a, length, 0, 0)
1737 items = a
1738 capacity = c
1739 end
1740
1741 redef fun to_s do
1742 written = true
1743 if length == 0 then items = new NativeString(1)
1744 return new FlatString.with_infos(items, length, 0, length - 1)
1745 end
1746
1747 redef fun to_cstring
1748 do
1749 if is_dirty then
1750 var new_native = new NativeString(length + 1)
1751 new_native[length] = '\0'
1752 if length > 0 then items.copy_to(new_native, length, 0, 0)
1753 real_items = new_native
1754 is_dirty = false
1755 end
1756 return real_items.as(not null)
1757 end
1758
1759 # Create a new empty string.
1760 init do end
1761
1762 # Low-level creation a new buffer with given data.
1763 #
1764 # `items` will be used as is, without copy, to store the characters of the buffer.
1765 # Aliasing issues is the responsibility of the caller.
1766 #
1767 # If `items` is shared, `written` should be set to true after the creation
1768 # so that a modification will do a copy-on-write.
1769 private init with_infos(items: NativeString, capacity, length: Int)
1770 do
1771 self.items = items
1772 self.length = length
1773 self.capacity = capacity
1774 end
1775
1776 # Create a new string copied from `s`.
1777 init from(s: Text)
1778 do
1779 capacity = s.length + 1
1780 length = s.length
1781 items = new NativeString(capacity)
1782 if s isa FlatString then
1783 s.items.copy_to(items, length, s.index_from, 0)
1784 else if s isa FlatBuffer then
1785 s.items.copy_to(items, length, 0, 0)
1786 else
1787 var curr_pos = 0
1788 for i in [0..s.length[ do
1789 var c = s.chars[i]
1790 items[curr_pos] = c
1791 curr_pos += 1
1792 end
1793 end
1794 end
1795
1796 # Create a new empty string with a given capacity.
1797 init with_capacity(cap: Int)
1798 do
1799 assert cap >= 0
1800 items = new NativeString(cap+1)
1801 capacity = cap
1802 length = 0
1803 end
1804
1805 redef fun append(s)
1806 do
1807 if s.is_empty then return
1808 is_dirty = true
1809 var sl = s.length
1810 if capacity < length + sl then enlarge(length + sl)
1811 if s isa FlatString then
1812 s.items.copy_to(items, sl, s.index_from, length)
1813 else if s isa FlatBuffer then
1814 s.items.copy_to(items, sl, 0, length)
1815 else
1816 var curr_pos = self.length
1817 for i in [0..s.length[ do
1818 var c = s.chars[i]
1819 items[curr_pos] = c
1820 curr_pos += 1
1821 end
1822 end
1823 length += sl
1824 end
1825
1826 # Copies the content of self in `dest`
1827 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1828 do
1829 var self_chars = self.chars
1830 var dest_chars = dest.chars
1831 for i in [0..len-1] do
1832 dest_chars[new_start+i] = self_chars[start+i]
1833 end
1834 end
1835
1836 redef fun substring(from, count)
1837 do
1838 assert count >= 0
1839 count += from
1840 if from < 0 then from = 0
1841 if count > length then count = length
1842 if from < count then
1843 var len = count - from
1844 var r_items = new NativeString(len)
1845 items.copy_to(r_items, len, from, 0)
1846 var r = new FlatBuffer.with_infos(r_items, len, len)
1847 return r
1848 else
1849 return new Buffer
1850 end
1851 end
1852
1853 redef fun reverse
1854 do
1855 written = false
1856 var ns = new NativeString(capacity)
1857 var si = length - 1
1858 var ni = 0
1859 var it = items
1860 while si >= 0 do
1861 ns[ni] = it[si]
1862 ni += 1
1863 si -= 1
1864 end
1865 items = ns
1866 end
1867
1868 redef fun times(repeats)
1869 do
1870 var x = new FlatString.with_infos(items, length, 0, length - 1)
1871 for i in [1..repeats[ do
1872 append(x)
1873 end
1874 end
1875
1876 redef fun upper
1877 do
1878 if written then reset
1879 var it = items
1880 var id = length - 1
1881 while id >= 0 do
1882 it[id] = it[id].to_upper
1883 id -= 1
1884 end
1885 end
1886
1887 redef fun lower
1888 do
1889 if written then reset
1890 var it = items
1891 var id = length - 1
1892 while id >= 0 do
1893 it[id] = it[id].to_lower
1894 id -= 1
1895 end
1896 end
1897 end
1898
1899 private class FlatBufferReverseIterator
1900 super IndexedIterator[Char]
1901
1902 var target: FlatBuffer
1903
1904 var target_items: NativeString
1905
1906 var curr_pos: Int
1907
1908 init with_pos(tgt: FlatBuffer, pos: Int)
1909 do
1910 target = tgt
1911 if tgt.length > 0 then target_items = tgt.items
1912 curr_pos = pos
1913 end
1914
1915 redef fun index do return curr_pos
1916
1917 redef fun is_ok do return curr_pos >= 0
1918
1919 redef fun item do return target_items[curr_pos]
1920
1921 redef fun next do curr_pos -= 1
1922
1923 end
1924
1925 private class FlatBufferCharView
1926 super BufferCharView
1927
1928 redef type SELFTYPE: FlatBuffer
1929
1930 redef fun [](index) do return target.items[index]
1931
1932 redef fun []=(index, item)
1933 do
1934 assert index >= 0 and index <= length
1935 if index == length then
1936 add(item)
1937 return
1938 end
1939 target.items[index] = item
1940 end
1941
1942 redef fun push(c)
1943 do
1944 target.add(c)
1945 end
1946
1947 redef fun add(c)
1948 do
1949 target.add(c)
1950 end
1951
1952 fun enlarge(cap: Int)
1953 do
1954 target.enlarge(cap)
1955 end
1956
1957 redef fun append(s)
1958 do
1959 var s_length = s.length
1960 if target.capacity < s.length then enlarge(s_length + target.length)
1961 end
1962
1963 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1964
1965 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1966
1967 end
1968
1969 private class FlatBufferIterator
1970 super IndexedIterator[Char]
1971
1972 var target: FlatBuffer
1973
1974 var target_items: NativeString
1975
1976 var curr_pos: Int
1977
1978 init with_pos(tgt: FlatBuffer, pos: Int)
1979 do
1980 target = tgt
1981 if tgt.length > 0 then target_items = tgt.items
1982 curr_pos = pos
1983 end
1984
1985 redef fun index do return curr_pos
1986
1987 redef fun is_ok do return curr_pos < target.length
1988
1989 redef fun item do return target_items[curr_pos]
1990
1991 redef fun next do curr_pos += 1
1992
1993 end
1994
1995 ###############################################################################
1996 # Refinement #
1997 ###############################################################################
1998
1999 redef class Object
2000 # User readable representation of `self`.
2001 fun to_s: String do return inspect
2002
2003 # The class name of the object in NativeString format.
2004 private fun native_class_name: NativeString is intern
2005
2006 # The class name of the object.
2007 #
2008 # assert 5.class_name == "Int"
2009 fun class_name: String do return native_class_name.to_s
2010
2011 # Developer readable representation of `self`.
2012 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
2013 fun inspect: String
2014 do
2015 return "<{inspect_head}>"
2016 end
2017
2018 # Return "CLASSNAME:#OBJECTID".
2019 # This function is mainly used with the redefinition of the inspect method
2020 protected fun inspect_head: String
2021 do
2022 return "{class_name}:#{object_id.to_hex}"
2023 end
2024 end
2025
2026 redef class Bool
2027 # assert true.to_s == "true"
2028 # assert false.to_s == "false"
2029 redef fun to_s
2030 do
2031 if self then
2032 return once "true"
2033 else
2034 return once "false"
2035 end
2036 end
2037 end
2038
2039 redef class Byte
2040 # C function to calculate the length of the `NativeString` to receive `self`
2041 private fun byte_to_s_len: Int is extern "native_byte_length_str"
2042
2043 # C function to convert an nit Int to a NativeString (char*)
2044 private fun native_byte_to_s(nstr: NativeString, strlen: Int) is extern "native_byte_to_s"
2045
2046 # Displayable byte in its hexadecimal form (0x..)
2047 #
2048 # assert 1.to_b.to_s == "0x01"
2049 # assert (-123).to_b.to_s == "0x85"
2050 redef fun to_s do
2051 var nslen = byte_to_s_len
2052 var ns = new NativeString(nslen + 1)
2053 ns[nslen] = '\0'
2054 native_byte_to_s(ns, nslen + 1)
2055 return ns.to_s_with_length(nslen)
2056 end
2057 end
2058
2059 redef class Int
2060
2061 # Wrapper of strerror C function
2062 private fun strerror_ext: NativeString is extern "strerror"
2063
2064 # Returns a string describing error number
2065 fun strerror: String do return strerror_ext.to_s
2066
2067 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
2068 # assume < to_c max const of char
2069 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
2070 do
2071 var n: Int
2072 # Sign
2073 if self < 0 then
2074 n = - self
2075 s.chars[0] = '-'
2076 else if self == 0 then
2077 s.chars[0] = '0'
2078 return
2079 else
2080 n = self
2081 end
2082 # Fill digits
2083 var pos = digit_count(base) - 1
2084 while pos >= 0 and n > 0 do
2085 s.chars[pos] = (n % base).to_c
2086 n = n / base # /
2087 pos -= 1
2088 end
2089 end
2090
2091 # C function to calculate the length of the `NativeString` to receive `self`
2092 private fun int_to_s_len: Int is extern "native_int_length_str"
2093
2094 # C function to convert an nit Int to a NativeString (char*)
2095 private fun native_int_to_s(nstr: NativeString, strlen: Int) is extern "native_int_to_s"
2096
2097 # return displayable int in base 10 and signed
2098 #
2099 # assert 1.to_s == "1"
2100 # assert (-123).to_s == "-123"
2101 redef fun to_s do
2102 # Fast case for common numbers
2103 if self == 0 then return "0"
2104 if self == 1 then return "1"
2105
2106 var nslen = int_to_s_len
2107 var ns = new NativeString(nslen + 1)
2108 ns[nslen] = '\0'
2109 native_int_to_s(ns, nslen + 1)
2110 return ns.to_s_with_length(nslen)
2111 end
2112
2113 # return displayable int in hexadecimal
2114 #
2115 # assert 1.to_hex == "1"
2116 # assert (-255).to_hex == "-ff"
2117 fun to_hex: String do return to_base(16,false)
2118
2119 # return displayable int in base base and signed
2120 fun to_base(base: Int, signed: Bool): String
2121 do
2122 var l = digit_count(base)
2123 var s = new FlatBuffer.from(" " * l)
2124 fill_buffer(s, base, signed)
2125 return s.to_s
2126 end
2127 end
2128
2129 redef class Float
2130 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
2131 #
2132 # assert 12.34.to_s == "12.34"
2133 # assert (-0120.030).to_s == "-120.03"
2134 #
2135 # see `to_precision` for a custom precision.
2136 redef fun to_s do
2137 var str = to_precision( 3 )
2138 if is_inf != 0 or is_nan then return str
2139 var len = str.length
2140 for i in [0..len-1] do
2141 var j = len-1-i
2142 var c = str.chars[j]
2143 if c == '0' then
2144 continue
2145 else if c == '.' then
2146 return str.substring( 0, j+2 )
2147 else
2148 return str.substring( 0, j+1 )
2149 end
2150 end
2151 return str
2152 end
2153
2154 # `String` representation of `self` with the given number of `decimals`
2155 #
2156 # assert 12.345.to_precision(0) == "12"
2157 # assert 12.345.to_precision(3) == "12.345"
2158 # assert (-12.345).to_precision(3) == "-12.345"
2159 # assert (-0.123).to_precision(3) == "-0.123"
2160 # assert 0.999.to_precision(2) == "1.00"
2161 # assert 0.999.to_precision(4) == "0.9990"
2162 fun to_precision(decimals: Int): String
2163 do
2164 if is_nan then return "nan"
2165
2166 var isinf = self.is_inf
2167 if isinf == 1 then
2168 return "inf"
2169 else if isinf == -1 then
2170 return "-inf"
2171 end
2172
2173 if decimals == 0 then return self.to_i.to_s
2174 var f = self
2175 for i in [0..decimals[ do f = f * 10.0
2176 if self > 0.0 then
2177 f = f + 0.5
2178 else
2179 f = f - 0.5
2180 end
2181 var i = f.to_i
2182 if i == 0 then return "0." + "0"*decimals
2183
2184 # Prepare both parts of the float, before and after the "."
2185 var s = i.abs.to_s
2186 var sl = s.length
2187 var p1
2188 var p2
2189 if sl > decimals then
2190 # Has something before the "."
2191 p1 = s.substring(0, sl-decimals)
2192 p2 = s.substring(sl-decimals, decimals)
2193 else
2194 p1 = "0"
2195 p2 = "0"*(decimals-sl) + s
2196 end
2197
2198 if i < 0 then p1 = "-" + p1
2199
2200 return p1 + "." + p2
2201 end
2202 end
2203
2204 redef class Char
2205 # assert 'x'.to_s == "x"
2206 redef fun to_s
2207 do
2208 var s = new Buffer.with_cap(1)
2209 s.chars[0] = self
2210 return s.to_s
2211 end
2212
2213 # Returns true if the char is a numerical digit
2214 #
2215 # assert '0'.is_numeric
2216 # assert '9'.is_numeric
2217 # assert not 'a'.is_numeric
2218 # assert not '?'.is_numeric
2219 fun is_numeric: Bool
2220 do
2221 return self >= '0' and self <= '9'
2222 end
2223
2224 # Returns true if the char is an alpha digit
2225 #
2226 # assert 'a'.is_alpha
2227 # assert 'Z'.is_alpha
2228 # assert not '0'.is_alpha
2229 # assert not '?'.is_alpha
2230 fun is_alpha: Bool
2231 do
2232 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2233 end
2234
2235 # Returns true if the char is an alpha or a numeric digit
2236 #
2237 # assert 'a'.is_alphanumeric
2238 # assert 'Z'.is_alphanumeric
2239 # assert '0'.is_alphanumeric
2240 # assert '9'.is_alphanumeric
2241 # assert not '?'.is_alphanumeric
2242 fun is_alphanumeric: Bool
2243 do
2244 return self.is_numeric or self.is_alpha
2245 end
2246 end
2247
2248 redef class Collection[E]
2249 # Concatenate elements.
2250 redef fun to_s
2251 do
2252 return plain_to_s
2253 end
2254
2255 # Concatenate element without separators
2256 fun plain_to_s: String
2257 do
2258 var s = new Buffer
2259 for e in self do if e != null then s.append(e.to_s)
2260 return s.to_s
2261 end
2262
2263 # Concatenate and separate each elements with `sep`.
2264 #
2265 # assert [1, 2, 3].join(":") == "1:2:3"
2266 # assert [1..3].join(":") == "1:2:3"
2267 fun join(sep: Text): String
2268 do
2269 if is_empty then return ""
2270
2271 var s = new Buffer # Result
2272
2273 # Concat first item
2274 var i = iterator
2275 var e = i.item
2276 if e != null then s.append(e.to_s)
2277
2278 # Concat other items
2279 i.next
2280 while i.is_ok do
2281 s.append(sep)
2282 e = i.item
2283 if e != null then s.append(e.to_s)
2284 i.next
2285 end
2286 return s.to_s
2287 end
2288 end
2289
2290 redef class Array[E]
2291
2292 # Fast implementation
2293 redef fun plain_to_s
2294 do
2295 var l = length
2296 if l == 0 then return ""
2297 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2298 var its = _items
2299 var na = new NativeArray[String](l)
2300 var i = 0
2301 var sl = 0
2302 var mypos = 0
2303 while i < l do
2304 var itsi = its[i]
2305 if itsi == null then
2306 i += 1
2307 continue
2308 end
2309 var tmp = itsi.to_s
2310 sl += tmp.length
2311 na[mypos] = tmp
2312 i += 1
2313 mypos += 1
2314 end
2315 var ns = new NativeString(sl + 1)
2316 ns[sl] = '\0'
2317 i = 0
2318 var off = 0
2319 while i < mypos do
2320 var tmp = na[i]
2321 var tpl = tmp.length
2322 if tmp isa FlatString then
2323 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2324 off += tpl
2325 else
2326 for j in tmp.substrings do
2327 var s = j.as(FlatString)
2328 var slen = s.length
2329 s.items.copy_to(ns, slen, s.index_from, off)
2330 off += slen
2331 end
2332 end
2333 i += 1
2334 end
2335 return ns.to_s_with_length(sl)
2336 end
2337 end
2338
2339 redef class NativeArray[E]
2340 # Join all the elements using `to_s`
2341 #
2342 # REQUIRE: `self isa NativeArray[String]`
2343 # REQUIRE: all elements are initialized
2344 fun native_to_s: String
2345 do
2346 assert self isa NativeArray[String]
2347 var l = length
2348 var na = self
2349 var i = 0
2350 var sl = 0
2351 var mypos = 0
2352 while i < l do
2353 sl += na[i].length
2354 i += 1
2355 mypos += 1
2356 end
2357 var ns = new NativeString(sl + 1)
2358 ns[sl] = '\0'
2359 i = 0
2360 var off = 0
2361 while i < mypos do
2362 var tmp = na[i]
2363 var tpl = tmp.length
2364 if tmp isa FlatString then
2365 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2366 off += tpl
2367 else
2368 for j in tmp.substrings do
2369 var s = j.as(FlatString)
2370 var slen = s.length
2371 s.items.copy_to(ns, slen, s.index_from, off)
2372 off += slen
2373 end
2374 end
2375 i += 1
2376 end
2377 return ns.to_s_with_length(sl)
2378 end
2379 end
2380
2381 redef class Map[K,V]
2382 # Concatenate couple of 'key value'.
2383 # key and value are separated by `couple_sep`.
2384 # each couple is separated each couple with `sep`.
2385 #
2386 # var m = new ArrayMap[Int, String]
2387 # m[1] = "one"
2388 # m[10] = "ten"
2389 # assert m.join("; ", "=") == "1=one; 10=ten"
2390 fun join(sep: String, couple_sep: String): String
2391 do
2392 if is_empty then return ""
2393
2394 var s = new Buffer # Result
2395
2396 # Concat first item
2397 var i = iterator
2398 var k = i.key
2399 var e = i.item
2400 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2401
2402 # Concat other items
2403 i.next
2404 while i.is_ok do
2405 s.append(sep)
2406 k = i.key
2407 e = i.item
2408 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2409 i.next
2410 end
2411 return s.to_s
2412 end
2413 end
2414
2415 ###############################################################################
2416 # Native classes #
2417 ###############################################################################
2418
2419 # Native strings are simple C char *
2420 extern class NativeString `{ char* `}
2421 # Creates a new NativeString with a capacity of `length`
2422 new(length: Int) is intern
2423
2424 # Returns a char* starting at `index`.
2425 #
2426 # WARNING: Unsafe for extern code, use only for temporary
2427 # pointer manipulation purposes (e.g. write to file or such)
2428 fun fast_cstring(index: Int): NativeString is intern
2429
2430 # Get char at `index`.
2431 fun [](index: Int): Char is intern
2432
2433 # Set char `item` at index.
2434 fun []=(index: Int, item: Char) is intern
2435
2436 # Copy `self` to `dest`.
2437 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2438
2439 # Position of the first nul character.
2440 fun cstring_length: Int
2441 do
2442 var l = 0
2443 while self[l] != '\0' do l += 1
2444 return l
2445 end
2446
2447 # Parse `self` as an Int.
2448 fun atoi: Int is intern
2449
2450 # Parse `self` as a Float.
2451 fun atof: Float is extern "atof"
2452
2453 redef fun to_s
2454 do
2455 return to_s_with_length(cstring_length)
2456 end
2457
2458 # Returns `self` as a String of `length`.
2459 fun to_s_with_length(length: Int): FlatString
2460 do
2461 assert length >= 0
2462 var str = new FlatString.with_infos(self, length, 0, length - 1)
2463 return str
2464 end
2465
2466 # Returns `self` as a new String.
2467 fun to_s_with_copy: FlatString
2468 do
2469 var length = cstring_length
2470 var new_self = new NativeString(length + 1)
2471 copy_to(new_self, length, 0, 0)
2472 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2473 new_self[length] = '\0'
2474 str.real_items = new_self
2475 return str
2476 end
2477 end
2478
2479 redef class Sys
2480 private var args_cache: nullable Sequence[String] = null
2481
2482 # The arguments of the program as given by the OS
2483 fun program_args: Sequence[String]
2484 do
2485 if _args_cache == null then init_args
2486 return _args_cache.as(not null)
2487 end
2488
2489 # The name of the program as given by the OS
2490 fun program_name: String
2491 do
2492 return native_argv(0).to_s
2493 end
2494
2495 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2496 private fun init_args
2497 do
2498 var argc = native_argc
2499 var args = new Array[String].with_capacity(0)
2500 var i = 1
2501 while i < argc do
2502 args[i-1] = native_argv(i).to_s
2503 i += 1
2504 end
2505 _args_cache = args
2506 end
2507
2508 # First argument of the main C function.
2509 private fun native_argc: Int is intern
2510
2511 # Second argument of the main C function.
2512 private fun native_argv(i: Int): NativeString is intern
2513 end
2514
2515 # Comparator that efficienlty use `to_s` to compare things
2516 #
2517 # The comparaison call `to_s` on object and use the result to order things.
2518 #
2519 # var a = [1, 2, 3, 10, 20]
2520 # (new CachedAlphaComparator).sort(a)
2521 # assert a == [1, 10, 2, 20, 3]
2522 #
2523 # Internally the result of `to_s` is cached in a HashMap to counter
2524 # uneficient implementation of `to_s`.
2525 #
2526 # Note: it caching is not usefull, see `alpha_comparator`
2527 class CachedAlphaComparator
2528 super Comparator
2529 redef type COMPARED: Object
2530
2531 private var cache = new HashMap[Object, String]
2532
2533 private fun do_to_s(a: Object): String do
2534 if cache.has_key(a) then return cache[a]
2535 var res = a.to_s
2536 cache[a] = res
2537 return res
2538 end
2539
2540 redef fun compare(a, b) do
2541 return do_to_s(a) <=> do_to_s(b)
2542 end
2543 end
2544
2545 # see `alpha_comparator`
2546 private class AlphaComparator
2547 super Comparator
2548 redef fun compare(a, b) do return a.to_s <=> b.to_s
2549 end
2550
2551 # Stateless comparator that naively use `to_s` to compare things.
2552 #
2553 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2554 # on a single instace. See `CachedAlphaComparator` as an alternative.
2555 #
2556 # var a = [1, 2, 3, 10, 20]
2557 # alpha_comparator.sort(a)
2558 # assert a == [1, 10, 2, 20, 3]
2559 fun alpha_comparator: Comparator do return once new AlphaComparator
2560
2561 # The arguments of the program as given by the OS
2562 fun args: Sequence[String]
2563 do
2564 return sys.program_args
2565 end