Merge: modelize: ask that attributes in refinements are either noautoninit or have...
[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 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 <= '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 FlatBuffer
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 FlatBuffer
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 FlatBuffer
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 FlatBuffer
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 FlatBuffer
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 FlatBuffer.with_capacity(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 FlatBuffer
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 FlatBuffer
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 FlatBuffer
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 # Flat representation of self
842 fun flatten: FlatText is abstract
843
844 private var hash_cache: nullable Int = null
845
846 redef fun hash
847 do
848 if hash_cache == null then
849 # djb2 hash algorithm
850 var h = 5381
851
852 for i in [0..length[ do
853 var char = chars[i]
854 h = h.lshift(5) + h + char.ascii
855 end
856
857 hash_cache = h
858 end
859 return hash_cache.as(not null)
860 end
861
862 # Gives the formatted string back as a Nit string with `args` in place
863 #
864 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
865 # assert "\\%1 This string".format("String") == "\\%1 This string"
866 fun format(args: Object...): String do
867 var s = new Array[Text]
868 var curr_st = 0
869 var i = 0
870 while i < length do
871 # Skip escaped characters
872 if self[i] == '\\' then
873 i += 1
874 # In case of format
875 else if self[i] == '%' then
876 var fmt_st = i
877 i += 1
878 var ciph_st = i
879 while i < length and self[i].is_numeric do
880 i += 1
881 end
882 i -= 1
883 var fmt_end = i
884 var ciph_len = fmt_end - ciph_st + 1
885 s.push substring(curr_st, fmt_st - curr_st)
886 s.push args[substring(ciph_st, ciph_len).to_i - 1].to_s
887 curr_st = i + 1
888 end
889 i += 1
890 end
891 s.push substring(curr_st, length - curr_st)
892 return s.to_s
893 end
894
895 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
896 #
897 # Basically a high-level synonym of NativeString::copy_to
898 #
899 # REQUIRE: `n` must be large enough to contain `len` bytes
900 #
901 # var ns = new NativeString(8)
902 # "Text is String".copy_to_native(ns, 8, 2, 0)
903 # assert ns.to_s_with_length(8) == "xt is St"
904 #
905 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
906 var mypos = src_offset
907 var itspos = dest_offset
908 while n > 0 do
909 dest[itspos] = self.chars[mypos]
910 itspos += 1
911 mypos += 1
912 n -= 1
913 end
914 end
915
916 end
917
918 # All kinds of array-based text representations.
919 abstract class FlatText
920 super Text
921
922 # Underlying C-String (`char*`)
923 #
924 # Warning : Might be void in some subclasses, be sure to check
925 # if set before using it.
926 private var items: NativeString is noinit
927
928 # Real items, used as cache for to_cstring is called
929 private var real_items: nullable NativeString = null
930
931 # Returns a char* starting at position `index_from`
932 #
933 # WARNING: If you choose to use this service, be careful of the following.
934 #
935 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
936 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
937 # deallocated at any moment, rendering the pointer returned by this function invalid.
938 # Any access to freed memory may very likely cause undefined behaviour or a crash.
939 # (Failure to do so will most certainly result in long and painful debugging hours)
940 #
941 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
942 # then immediately return).
943 #
944 # As always, do not modify the content of the String in C code, if this is what you want
945 # copy locally the char* as Nit Strings are immutable.
946 private fun fast_cstring: NativeString is abstract
947
948 redef var length = 0
949
950 redef fun output
951 do
952 var i = 0
953 while i < length do
954 items[i].output
955 i += 1
956 end
957 end
958
959 redef fun flatten do return self
960
961 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
962 items.copy_to(dest, n, src_offset, dest_offset)
963 end
964 end
965
966 # Abstract class for the SequenceRead compatible
967 # views on String and Buffer objects
968 private abstract class StringCharView
969 super SequenceRead[Char]
970
971 type SELFTYPE: Text
972
973 var target: SELFTYPE
974
975 redef fun is_empty do return target.is_empty
976
977 redef fun length do return target.length
978
979 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
980
981 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
982 end
983
984 # View on Buffer objects, extends Sequence
985 # for mutation operations
986 private abstract class BufferCharView
987 super StringCharView
988 super Sequence[Char]
989
990 redef type SELFTYPE: Buffer
991
992 end
993
994 # A `String` holds and manipulates an arbitrary sequence of characters.
995 #
996 # String objects may be created using literals.
997 #
998 # assert "Hello World!" isa String
999 abstract class String
1000 super Text
1001
1002 redef type SELFTYPE: String is fixed
1003
1004 redef fun to_s do return self
1005
1006 # Concatenates `o` to `self`
1007 #
1008 # assert "hello" + "world" == "helloworld"
1009 # assert "" + "hello" + "" == "hello"
1010 fun +(o: Text): SELFTYPE is abstract
1011
1012 # Concatenates self `i` times
1013 #
1014 # assert "abc" * 4 == "abcabcabcabc"
1015 # assert "abc" * 1 == "abc"
1016 # assert "abc" * 0 == ""
1017 fun *(i: Int): SELFTYPE is abstract
1018
1019 # Insert `s` at `pos`.
1020 #
1021 # assert "helloworld".insert_at(" ", 5) == "hello world"
1022 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1023
1024 redef fun substrings is abstract
1025
1026 # Returns a reversed version of self
1027 #
1028 # assert "hello".reversed == "olleh"
1029 # assert "bob".reversed == "bob"
1030 # assert "".reversed == ""
1031 fun reversed: SELFTYPE is abstract
1032
1033 # A upper case version of `self`
1034 #
1035 # assert "Hello World!".to_upper == "HELLO WORLD!"
1036 fun to_upper: SELFTYPE is abstract
1037
1038 # A lower case version of `self`
1039 #
1040 # assert "Hello World!".to_lower == "hello world!"
1041 fun to_lower : SELFTYPE is abstract
1042
1043 # Takes a camel case `self` and converts it to snake case
1044 #
1045 # assert "randomMethodId".to_snake_case == "random_method_id"
1046 #
1047 # The rules are the following:
1048 #
1049 # An uppercase is always converted to a lowercase
1050 #
1051 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1052 #
1053 # An uppercase that follows a lowercase is prefixed with an underscore
1054 #
1055 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1056 #
1057 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1058 #
1059 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1060 #
1061 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1062 #
1063 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1064 fun to_snake_case: SELFTYPE
1065 do
1066 if self.is_lower then return self
1067
1068 var new_str = new FlatBuffer.with_capacity(self.length)
1069 var prev_is_lower = false
1070 var prev_is_upper = false
1071
1072 for i in [0..length[ do
1073 var char = chars[i]
1074 if char.is_lower then
1075 new_str.add(char)
1076 prev_is_lower = true
1077 prev_is_upper = false
1078 else if char.is_upper then
1079 if prev_is_lower then
1080 new_str.add('_')
1081 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1082 new_str.add('_')
1083 end
1084 new_str.add(char.to_lower)
1085 prev_is_lower = false
1086 prev_is_upper = true
1087 else
1088 new_str.add(char)
1089 prev_is_lower = false
1090 prev_is_upper = false
1091 end
1092 end
1093
1094 return new_str.to_s
1095 end
1096
1097 # Takes a snake case `self` and converts it to camel case
1098 #
1099 # assert "random_method_id".to_camel_case == "randomMethodId"
1100 #
1101 # If the identifier is prefixed by an underscore, the underscore is ignored
1102 #
1103 # assert "_private_field".to_camel_case == "_privateField"
1104 #
1105 # If `self` is upper, it is returned unchanged
1106 #
1107 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1108 #
1109 # If there are several consecutive underscores, they are considered as a single one
1110 #
1111 # assert "random__method_id".to_camel_case == "randomMethodId"
1112 fun to_camel_case: SELFTYPE
1113 do
1114 if self.is_upper then return self
1115
1116 var new_str = new FlatBuffer
1117 var is_first_char = true
1118 var follows_us = false
1119
1120 for i in [0..length[ do
1121 var char = chars[i]
1122 if is_first_char then
1123 new_str.add(char)
1124 is_first_char = false
1125 else if char == '_' then
1126 follows_us = true
1127 else if follows_us then
1128 new_str.add(char.to_upper)
1129 follows_us = false
1130 else
1131 new_str.add(char)
1132 end
1133 end
1134
1135 return new_str.to_s
1136 end
1137
1138 # Returns a capitalized `self`
1139 #
1140 # Letters that follow a letter are lowercased
1141 # Letters that follow a non-letter are upcased.
1142 #
1143 # SEE : `Char::is_letter` for the definition of letter.
1144 #
1145 # assert "jAVASCRIPT".capitalized == "Javascript"
1146 # assert "i am root".capitalized == "I Am Root"
1147 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1148 fun capitalized: SELFTYPE do
1149 if length == 0 then return self
1150
1151 var buf = new FlatBuffer.with_capacity(length)
1152
1153 var curr = chars[0].to_upper
1154 var prev = curr
1155 buf[0] = curr
1156
1157 for i in [1 .. length[ do
1158 prev = curr
1159 curr = self[i]
1160 if prev.is_letter then
1161 buf[i] = curr.to_lower
1162 else
1163 buf[i] = curr.to_upper
1164 end
1165 end
1166
1167 return buf.to_s
1168 end
1169 end
1170
1171 private class FlatSubstringsIter
1172 super Iterator[FlatText]
1173
1174 var tgt: nullable FlatText
1175
1176 redef fun item do
1177 assert is_ok
1178 return tgt.as(not null)
1179 end
1180
1181 redef fun is_ok do return tgt != null
1182
1183 redef fun next do tgt = null
1184 end
1185
1186 # Immutable strings of characters.
1187 class FlatString
1188 super FlatText
1189 super String
1190
1191 # Index in _items of the start of the string
1192 private var index_from: Int is noinit
1193
1194 # Indes in _items of the last item of the string
1195 private var index_to: Int is noinit
1196
1197 redef var chars = new FlatStringCharView(self) is lazy
1198
1199 redef fun [](index)
1200 do
1201 # Check that the index (+ index_from) is not larger than indexTo
1202 # In other terms, if the index is valid
1203 assert index >= 0
1204 assert (index + index_from) <= index_to
1205 return items[index + index_from]
1206 end
1207
1208 ################################################
1209 # AbstractString specific methods #
1210 ################################################
1211
1212 redef fun reversed
1213 do
1214 var native = new NativeString(self.length + 1)
1215 var length = self.length
1216 var items = self.items
1217 var pos = 0
1218 var ipos = length-1
1219 while pos < length do
1220 native[pos] = items[ipos]
1221 pos += 1
1222 ipos -= 1
1223 end
1224 return native.to_s_with_length(self.length)
1225 end
1226
1227 redef fun fast_cstring do return items.fast_cstring(index_from)
1228
1229 redef fun substring(from, count)
1230 do
1231 assert count >= 0
1232
1233 if from < 0 then
1234 count += from
1235 if count < 0 then count = 0
1236 from = 0
1237 end
1238
1239 var new_from = index_from + from
1240
1241 if (new_from + count) > index_to then
1242 var new_len = index_to - new_from + 1
1243 if new_len <= 0 then return empty
1244 return new FlatString.with_infos(items, new_len, new_from, index_to)
1245 end
1246
1247 if count <= 0 then return empty
1248
1249 var to = new_from + count - 1
1250
1251 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1252 end
1253
1254 redef fun empty do return "".as(FlatString)
1255
1256 redef fun to_upper
1257 do
1258 var outstr = new NativeString(self.length + 1)
1259 var out_index = 0
1260
1261 var myitems = self.items
1262 var index_from = self.index_from
1263 var max = self.index_to
1264
1265 while index_from <= max do
1266 outstr[out_index] = myitems[index_from].to_upper
1267 out_index += 1
1268 index_from += 1
1269 end
1270
1271 outstr[self.length] = '\0'
1272
1273 return outstr.to_s_with_length(self.length)
1274 end
1275
1276 redef fun to_lower
1277 do
1278 var outstr = new NativeString(self.length + 1)
1279 var out_index = 0
1280
1281 var myitems = self.items
1282 var index_from = self.index_from
1283 var max = self.index_to
1284
1285 while index_from <= max do
1286 outstr[out_index] = myitems[index_from].to_lower
1287 out_index += 1
1288 index_from += 1
1289 end
1290
1291 outstr[self.length] = '\0'
1292
1293 return outstr.to_s_with_length(self.length)
1294 end
1295
1296 redef fun output
1297 do
1298 var i = self.index_from
1299 var imax = self.index_to
1300 while i <= imax do
1301 items[i].output
1302 i += 1
1303 end
1304 end
1305
1306 ##################################################
1307 # String Specific Methods #
1308 ##################################################
1309
1310 # Low-level creation of a new string with given data.
1311 #
1312 # `items` will be used as is, without copy, to retrieve the characters of the string.
1313 # Aliasing issues is the responsibility of the caller.
1314 private init with_infos(items: NativeString, length: Int, from: Int, to: Int)
1315 do
1316 self.items = items
1317 self.length = length
1318 index_from = from
1319 index_to = to
1320 end
1321
1322 redef fun to_cstring do
1323 if real_items != null then
1324 return real_items.as(not null)
1325 else
1326 var newItems = new NativeString(length + 1)
1327 self.items.copy_to(newItems, length, index_from, 0)
1328 newItems[length] = '\0'
1329 self.real_items = newItems
1330 return newItems
1331 end
1332 end
1333
1334 redef fun ==(other)
1335 do
1336 if not other isa FlatString then return super
1337
1338 if self.object_id == other.object_id then return true
1339
1340 var my_length = length
1341
1342 if other.length != my_length then return false
1343
1344 var my_index = index_from
1345 var its_index = other.index_from
1346
1347 var last_iteration = my_index + my_length
1348
1349 var itsitems = other.items
1350 var myitems = self.items
1351
1352 while my_index < last_iteration do
1353 if myitems[my_index] != itsitems[its_index] then return false
1354 my_index += 1
1355 its_index += 1
1356 end
1357
1358 return true
1359 end
1360
1361 redef fun <(other)
1362 do
1363 if not other isa FlatString then return super
1364
1365 if self.object_id == other.object_id then return false
1366
1367 var my_curr_char : Char
1368 var its_curr_char : Char
1369
1370 var curr_id_self = self.index_from
1371 var curr_id_other = other.index_from
1372
1373 var my_items = self.items
1374 var its_items = other.items
1375
1376 var my_length = self.length
1377 var its_length = other.length
1378
1379 var max_iterations = curr_id_self + my_length
1380
1381 while curr_id_self < max_iterations do
1382 my_curr_char = my_items[curr_id_self]
1383 its_curr_char = its_items[curr_id_other]
1384
1385 if my_curr_char != its_curr_char then
1386 if my_curr_char < its_curr_char then return true
1387 return false
1388 end
1389
1390 curr_id_self += 1
1391 curr_id_other += 1
1392 end
1393
1394 return my_length < its_length
1395 end
1396
1397 redef fun +(s)
1398 do
1399 var my_length = self.length
1400 var its_length = s.length
1401
1402 var total_length = my_length + its_length
1403
1404 var target_string = new NativeString(my_length + its_length + 1)
1405
1406 self.items.copy_to(target_string, my_length, index_from, 0)
1407 if s isa FlatString then
1408 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1409 else if s isa FlatBuffer then
1410 s.items.copy_to(target_string, its_length, 0, my_length)
1411 else
1412 var curr_pos = my_length
1413 for i in [0..s.length[ do
1414 var c = s.chars[i]
1415 target_string[curr_pos] = c
1416 curr_pos += 1
1417 end
1418 end
1419
1420 target_string[total_length] = '\0'
1421
1422 return target_string.to_s_with_length(total_length)
1423 end
1424
1425 redef fun *(i)
1426 do
1427 assert i >= 0
1428
1429 var my_length = self.length
1430
1431 var final_length = my_length * i
1432
1433 var my_items = self.items
1434
1435 var target_string = new NativeString(final_length + 1)
1436
1437 target_string[final_length] = '\0'
1438
1439 var current_last = 0
1440
1441 for iteration in [1 .. i] do
1442 my_items.copy_to(target_string, my_length, 0, current_last)
1443 current_last += my_length
1444 end
1445
1446 return target_string.to_s_with_length(final_length)
1447 end
1448
1449 redef fun hash
1450 do
1451 if hash_cache == null then
1452 # djb2 hash algorithm
1453 var h = 5381
1454 var i = index_from
1455
1456 var myitems = items
1457
1458 while i <= index_to do
1459 h = h.lshift(5) + h + myitems[i].ascii
1460 i += 1
1461 end
1462
1463 hash_cache = h
1464 end
1465
1466 return hash_cache.as(not null)
1467 end
1468
1469 redef fun substrings do return new FlatSubstringsIter(self)
1470 end
1471
1472 private class FlatStringReverseIterator
1473 super IndexedIterator[Char]
1474
1475 var target: FlatString
1476
1477 var target_items: NativeString
1478
1479 var curr_pos: Int
1480
1481 init with_pos(tgt: FlatString, pos: Int)
1482 do
1483 target = tgt
1484 target_items = tgt.items
1485 curr_pos = pos + tgt.index_from
1486 end
1487
1488 redef fun is_ok do return curr_pos >= target.index_from
1489
1490 redef fun item do return target_items[curr_pos]
1491
1492 redef fun next do curr_pos -= 1
1493
1494 redef fun index do return curr_pos - target.index_from
1495
1496 end
1497
1498 private class FlatStringIterator
1499 super IndexedIterator[Char]
1500
1501 var target: FlatString
1502
1503 var target_items: NativeString
1504
1505 var curr_pos: Int
1506
1507 init with_pos(tgt: FlatString, pos: Int)
1508 do
1509 target = tgt
1510 target_items = tgt.items
1511 curr_pos = pos + target.index_from
1512 end
1513
1514 redef fun is_ok do return curr_pos <= target.index_to
1515
1516 redef fun item do return target_items[curr_pos]
1517
1518 redef fun next do curr_pos += 1
1519
1520 redef fun index do return curr_pos - target.index_from
1521
1522 end
1523
1524 private class FlatStringCharView
1525 super StringCharView
1526
1527 redef type SELFTYPE: FlatString
1528
1529 redef fun [](index)
1530 do
1531 # Check that the index (+ index_from) is not larger than indexTo
1532 # In other terms, if the index is valid
1533 assert index >= 0
1534 var target = self.target
1535 assert (index + target.index_from) <= target.index_to
1536 return target.items[index + target.index_from]
1537 end
1538
1539 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1540
1541 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1542
1543 end
1544
1545 # A mutable sequence of characters.
1546 abstract class Buffer
1547 super Text
1548
1549 redef type SELFTYPE: Buffer is fixed
1550
1551 # Specific implementations MUST set this to `true` in order to invalidate caches
1552 protected var is_dirty = true
1553
1554 # Copy-On-Write flag
1555 #
1556 # If the `Buffer` was to_s'd, the next in-place altering
1557 # operation will cause the current `Buffer` to be re-allocated.
1558 #
1559 # The flag will then be set at `false`.
1560 protected var written = false
1561
1562 # Modifies the char contained at pos `index`
1563 #
1564 # DEPRECATED : Use self.chars.[]= instead
1565 fun []=(index: Int, item: Char) is abstract
1566
1567 # Adds a char `c` at the end of self
1568 #
1569 # DEPRECATED : Use self.chars.add instead
1570 fun add(c: Char) is abstract
1571
1572 # Clears the buffer
1573 #
1574 # var b = new FlatBuffer
1575 # b.append "hello"
1576 # assert not b.is_empty
1577 # b.clear
1578 # assert b.is_empty
1579 fun clear is abstract
1580
1581 # Enlarges the subsequent array containing the chars of self
1582 fun enlarge(cap: Int) is abstract
1583
1584 # Adds the content of text `s` at the end of self
1585 #
1586 # var b = new FlatBuffer
1587 # b.append "hello"
1588 # b.append "world"
1589 # assert b == "helloworld"
1590 fun append(s: Text) is abstract
1591
1592 # `self` is appended in such a way that `self` is repeated `r` times
1593 #
1594 # var b = new FlatBuffer
1595 # b.append "hello"
1596 # b.times 3
1597 # assert b == "hellohellohello"
1598 fun times(r: Int) is abstract
1599
1600 # Reverses itself in-place
1601 #
1602 # var b = new FlatBuffer
1603 # b.append("hello")
1604 # b.reverse
1605 # assert b == "olleh"
1606 fun reverse is abstract
1607
1608 # Changes each lower-case char in `self` by its upper-case variant
1609 #
1610 # var b = new FlatBuffer
1611 # b.append("Hello World!")
1612 # b.upper
1613 # assert b == "HELLO WORLD!"
1614 fun upper is abstract
1615
1616 # Changes each upper-case char in `self` by its lower-case variant
1617 #
1618 # var b = new FlatBuffer
1619 # b.append("Hello World!")
1620 # b.lower
1621 # assert b == "hello world!"
1622 fun lower is abstract
1623
1624 # Capitalizes each word in `self`
1625 #
1626 # Letters that follow a letter are lowercased
1627 # Letters that follow a non-letter are upcased.
1628 #
1629 # SEE: `Char::is_letter` for the definition of a letter.
1630 #
1631 # var b = new FlatBuffer.from("jAVAsCriPt")
1632 # b.capitalize
1633 # assert b == "Javascript"
1634 # b = new FlatBuffer.from("i am root")
1635 # b.capitalize
1636 # assert b == "I Am Root"
1637 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1638 # b.capitalize
1639 # assert b == "Ab_C -Ab0C Ab\nC"
1640 fun capitalize do
1641 if length == 0 then return
1642 var c = self[0].to_upper
1643 self[0] = c
1644 var prev = c
1645 for i in [1 .. length[ do
1646 prev = c
1647 c = self[i]
1648 if prev.is_letter then
1649 self[i] = c.to_lower
1650 else
1651 self[i] = c.to_upper
1652 end
1653 end
1654 end
1655
1656 redef fun hash
1657 do
1658 if is_dirty then hash_cache = null
1659 return super
1660 end
1661
1662 # In Buffers, the internal sequence of character is mutable
1663 # Thus, `chars` can be used to modify the buffer.
1664 redef fun chars: Sequence[Char] is abstract
1665 end
1666
1667 # Mutable strings of characters.
1668 class FlatBuffer
1669 super FlatText
1670 super Buffer
1671
1672 redef var chars: Sequence[Char] = new FlatBufferCharView(self) is lazy
1673
1674 private var capacity: Int = 0
1675
1676 redef fun fast_cstring do return items.fast_cstring(0)
1677
1678 redef fun substrings do return new FlatSubstringsIter(self)
1679
1680 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1681 #
1682 # This happens when an operation modifies the current `Buffer` and
1683 # the Copy-On-Write flag `written` is set at true.
1684 private fun reset do
1685 var nns = new NativeString(capacity)
1686 items.copy_to(nns, length, 0, 0)
1687 items = nns
1688 written = false
1689 end
1690
1691 redef fun [](index)
1692 do
1693 assert index >= 0
1694 assert index < length
1695 return items[index]
1696 end
1697
1698 redef fun []=(index, item)
1699 do
1700 is_dirty = true
1701 if index == length then
1702 add(item)
1703 return
1704 end
1705 if written then reset
1706 assert index >= 0 and index < length
1707 items[index] = item
1708 end
1709
1710 redef fun add(c)
1711 do
1712 is_dirty = true
1713 if capacity <= length then enlarge(length + 5)
1714 items[length] = c
1715 length += 1
1716 end
1717
1718 redef fun clear do
1719 is_dirty = true
1720 if written then reset
1721 length = 0
1722 end
1723
1724 redef fun empty do return new FlatBuffer
1725
1726 redef fun enlarge(cap)
1727 do
1728 var c = capacity
1729 if cap <= c then return
1730 while c <= cap do c = c * 2 + 2
1731 # The COW flag can be set at false here, since
1732 # it does a copy of the current `Buffer`
1733 written = false
1734 var a = new NativeString(c+1)
1735 if length > 0 then items.copy_to(a, length, 0, 0)
1736 items = a
1737 capacity = c
1738 end
1739
1740 redef fun to_s do
1741 written = true
1742 if length == 0 then items = new NativeString(1)
1743 return new FlatString.with_infos(items, length, 0, length - 1)
1744 end
1745
1746 redef fun to_cstring
1747 do
1748 if is_dirty then
1749 var new_native = new NativeString(length + 1)
1750 new_native[length] = '\0'
1751 if length > 0 then items.copy_to(new_native, length, 0, 0)
1752 real_items = new_native
1753 is_dirty = false
1754 end
1755 return real_items.as(not null)
1756 end
1757
1758 # Create a new empty string.
1759 init do end
1760
1761 # Low-level creation a new buffer with given data.
1762 #
1763 # `items` will be used as is, without copy, to store the characters of the buffer.
1764 # Aliasing issues is the responsibility of the caller.
1765 #
1766 # If `items` is shared, `written` should be set to true after the creation
1767 # so that a modification will do a copy-on-write.
1768 private init with_infos(items: NativeString, capacity, length: Int)
1769 do
1770 self.items = items
1771 self.length = length
1772 self.capacity = capacity
1773 end
1774
1775 # Create a new string copied from `s`.
1776 init from(s: Text)
1777 do
1778 capacity = s.length + 1
1779 length = s.length
1780 items = new NativeString(capacity)
1781 if s isa FlatString then
1782 s.items.copy_to(items, length, s.index_from, 0)
1783 else if s isa FlatBuffer then
1784 s.items.copy_to(items, length, 0, 0)
1785 else
1786 var curr_pos = 0
1787 for i in [0..s.length[ do
1788 var c = s.chars[i]
1789 items[curr_pos] = c
1790 curr_pos += 1
1791 end
1792 end
1793 end
1794
1795 # Create a new empty string with a given capacity.
1796 init with_capacity(cap: Int)
1797 do
1798 assert cap >= 0
1799 items = new NativeString(cap+1)
1800 capacity = cap
1801 length = 0
1802 end
1803
1804 redef fun append(s)
1805 do
1806 if s.is_empty then return
1807 is_dirty = true
1808 var sl = s.length
1809 if capacity < length + sl then enlarge(length + sl)
1810 if s isa FlatString then
1811 s.items.copy_to(items, sl, s.index_from, length)
1812 else if s isa FlatBuffer then
1813 s.items.copy_to(items, sl, 0, length)
1814 else
1815 var curr_pos = self.length
1816 for i in [0..s.length[ do
1817 var c = s.chars[i]
1818 items[curr_pos] = c
1819 curr_pos += 1
1820 end
1821 end
1822 length += sl
1823 end
1824
1825 # Copies the content of self in `dest`
1826 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1827 do
1828 var self_chars = self.chars
1829 var dest_chars = dest.chars
1830 for i in [0..len-1] do
1831 dest_chars[new_start+i] = self_chars[start+i]
1832 end
1833 end
1834
1835 redef fun substring(from, count)
1836 do
1837 assert count >= 0
1838 count += from
1839 if from < 0 then from = 0
1840 if count > length then count = length
1841 if from < count then
1842 var len = count - from
1843 var r_items = new NativeString(len)
1844 items.copy_to(r_items, len, from, 0)
1845 var r = new FlatBuffer.with_infos(r_items, len, len)
1846 return r
1847 else
1848 return new FlatBuffer
1849 end
1850 end
1851
1852 redef fun reverse
1853 do
1854 written = false
1855 var ns = new NativeString(capacity)
1856 var si = length - 1
1857 var ni = 0
1858 var it = items
1859 while si >= 0 do
1860 ns[ni] = it[si]
1861 ni += 1
1862 si -= 1
1863 end
1864 items = ns
1865 end
1866
1867 redef fun times(repeats)
1868 do
1869 var x = new FlatString.with_infos(items, length, 0, length - 1)
1870 for i in [1..repeats[ do
1871 append(x)
1872 end
1873 end
1874
1875 redef fun upper
1876 do
1877 if written then reset
1878 var it = items
1879 var id = length - 1
1880 while id >= 0 do
1881 it[id] = it[id].to_upper
1882 id -= 1
1883 end
1884 end
1885
1886 redef fun lower
1887 do
1888 if written then reset
1889 var it = items
1890 var id = length - 1
1891 while id >= 0 do
1892 it[id] = it[id].to_lower
1893 id -= 1
1894 end
1895 end
1896 end
1897
1898 private class FlatBufferReverseIterator
1899 super IndexedIterator[Char]
1900
1901 var target: FlatBuffer
1902
1903 var target_items: NativeString
1904
1905 var curr_pos: Int
1906
1907 init with_pos(tgt: FlatBuffer, pos: Int)
1908 do
1909 target = tgt
1910 if tgt.length > 0 then target_items = tgt.items
1911 curr_pos = pos
1912 end
1913
1914 redef fun index do return curr_pos
1915
1916 redef fun is_ok do return curr_pos >= 0
1917
1918 redef fun item do return target_items[curr_pos]
1919
1920 redef fun next do curr_pos -= 1
1921
1922 end
1923
1924 private class FlatBufferCharView
1925 super BufferCharView
1926
1927 redef type SELFTYPE: FlatBuffer
1928
1929 redef fun [](index) do return target.items[index]
1930
1931 redef fun []=(index, item)
1932 do
1933 assert index >= 0 and index <= length
1934 if index == length then
1935 add(item)
1936 return
1937 end
1938 target.items[index] = item
1939 end
1940
1941 redef fun push(c)
1942 do
1943 target.add(c)
1944 end
1945
1946 redef fun add(c)
1947 do
1948 target.add(c)
1949 end
1950
1951 fun enlarge(cap: Int)
1952 do
1953 target.enlarge(cap)
1954 end
1955
1956 redef fun append(s)
1957 do
1958 var s_length = s.length
1959 if target.capacity < s.length then enlarge(s_length + target.length)
1960 end
1961
1962 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1963
1964 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1965
1966 end
1967
1968 private class FlatBufferIterator
1969 super IndexedIterator[Char]
1970
1971 var target: FlatBuffer
1972
1973 var target_items: NativeString
1974
1975 var curr_pos: Int
1976
1977 init with_pos(tgt: FlatBuffer, pos: Int)
1978 do
1979 target = tgt
1980 if tgt.length > 0 then target_items = tgt.items
1981 curr_pos = pos
1982 end
1983
1984 redef fun index do return curr_pos
1985
1986 redef fun is_ok do return curr_pos < target.length
1987
1988 redef fun item do return target_items[curr_pos]
1989
1990 redef fun next do curr_pos += 1
1991
1992 end
1993
1994 ###############################################################################
1995 # Refinement #
1996 ###############################################################################
1997
1998 redef class Object
1999 # User readable representation of `self`.
2000 fun to_s: String do return inspect
2001
2002 # The class name of the object in NativeString format.
2003 private fun native_class_name: NativeString is intern
2004
2005 # The class name of the object.
2006 #
2007 # assert 5.class_name == "Int"
2008 fun class_name: String do return native_class_name.to_s
2009
2010 # Developer readable representation of `self`.
2011 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
2012 fun inspect: String
2013 do
2014 return "<{inspect_head}>"
2015 end
2016
2017 # Return "CLASSNAME:#OBJECTID".
2018 # This function is mainly used with the redefinition of the inspect method
2019 protected fun inspect_head: String
2020 do
2021 return "{class_name}:#{object_id.to_hex}"
2022 end
2023 end
2024
2025 redef class Bool
2026 # assert true.to_s == "true"
2027 # assert false.to_s == "false"
2028 redef fun to_s
2029 do
2030 if self then
2031 return once "true"
2032 else
2033 return once "false"
2034 end
2035 end
2036 end
2037
2038 redef class Byte
2039 # C function to calculate the length of the `NativeString` to receive `self`
2040 private fun byte_to_s_len: Int is extern "native_byte_length_str"
2041
2042 # C function to convert an nit Int to a NativeString (char*)
2043 private fun native_byte_to_s(nstr: NativeString, strlen: Int) is extern "native_byte_to_s"
2044
2045 # Displayable byte in its hexadecimal form (0x..)
2046 #
2047 # assert 1.to_b.to_s == "0x01"
2048 # assert (-123).to_b.to_s == "0x85"
2049 redef fun to_s do
2050 var nslen = byte_to_s_len
2051 var ns = new NativeString(nslen + 1)
2052 ns[nslen] = '\0'
2053 native_byte_to_s(ns, nslen + 1)
2054 return ns.to_s_with_length(nslen)
2055 end
2056 end
2057
2058 redef class Int
2059
2060 # Wrapper of strerror C function
2061 private fun strerror_ext: NativeString is extern "strerror"
2062
2063 # Returns a string describing error number
2064 fun strerror: String do return strerror_ext.to_s
2065
2066 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
2067 # assume < to_c max const of char
2068 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
2069 do
2070 var n: Int
2071 # Sign
2072 if self < 0 then
2073 n = - self
2074 s.chars[0] = '-'
2075 else if self == 0 then
2076 s.chars[0] = '0'
2077 return
2078 else
2079 n = self
2080 end
2081 # Fill digits
2082 var pos = digit_count(base) - 1
2083 while pos >= 0 and n > 0 do
2084 s.chars[pos] = (n % base).to_c
2085 n = n / base # /
2086 pos -= 1
2087 end
2088 end
2089
2090 # C function to calculate the length of the `NativeString` to receive `self`
2091 private fun int_to_s_len: Int is extern "native_int_length_str"
2092
2093 # C function to convert an nit Int to a NativeString (char*)
2094 private fun native_int_to_s(nstr: NativeString, strlen: Int) is extern "native_int_to_s"
2095
2096 # return displayable int in base 10 and signed
2097 #
2098 # assert 1.to_s == "1"
2099 # assert (-123).to_s == "-123"
2100 redef fun to_s do
2101 # Fast case for common numbers
2102 if self == 0 then return "0"
2103 if self == 1 then return "1"
2104
2105 var nslen = int_to_s_len
2106 var ns = new NativeString(nslen + 1)
2107 ns[nslen] = '\0'
2108 native_int_to_s(ns, nslen + 1)
2109 return ns.to_s_with_length(nslen)
2110 end
2111
2112 # return displayable int in hexadecimal
2113 #
2114 # assert 1.to_hex == "1"
2115 # assert (-255).to_hex == "-ff"
2116 fun to_hex: String do return to_base(16,false)
2117
2118 # return displayable int in base base and signed
2119 fun to_base(base: Int, signed: Bool): String
2120 do
2121 var l = digit_count(base)
2122 var s = new FlatBuffer.from(" " * l)
2123 fill_buffer(s, base, signed)
2124 return s.to_s
2125 end
2126 end
2127
2128 redef class Float
2129 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
2130 #
2131 # assert 12.34.to_s == "12.34"
2132 # assert (-0120.030).to_s == "-120.03"
2133 #
2134 # see `to_precision` for a custom precision.
2135 redef fun to_s do
2136 var str = to_precision( 3 )
2137 if is_inf != 0 or is_nan then return str
2138 var len = str.length
2139 for i in [0..len-1] do
2140 var j = len-1-i
2141 var c = str.chars[j]
2142 if c == '0' then
2143 continue
2144 else if c == '.' then
2145 return str.substring( 0, j+2 )
2146 else
2147 return str.substring( 0, j+1 )
2148 end
2149 end
2150 return str
2151 end
2152
2153 # `String` representation of `self` with the given number of `decimals`
2154 #
2155 # assert 12.345.to_precision(0) == "12"
2156 # assert 12.345.to_precision(3) == "12.345"
2157 # assert (-12.345).to_precision(3) == "-12.345"
2158 # assert (-0.123).to_precision(3) == "-0.123"
2159 # assert 0.999.to_precision(2) == "1.00"
2160 # assert 0.999.to_precision(4) == "0.9990"
2161 fun to_precision(decimals: Int): String
2162 do
2163 if is_nan then return "nan"
2164
2165 var isinf = self.is_inf
2166 if isinf == 1 then
2167 return "inf"
2168 else if isinf == -1 then
2169 return "-inf"
2170 end
2171
2172 if decimals == 0 then return self.to_i.to_s
2173 var f = self
2174 for i in [0..decimals[ do f = f * 10.0
2175 if self > 0.0 then
2176 f = f + 0.5
2177 else
2178 f = f - 0.5
2179 end
2180 var i = f.to_i
2181 if i == 0 then return "0." + "0"*decimals
2182
2183 # Prepare both parts of the float, before and after the "."
2184 var s = i.abs.to_s
2185 var sl = s.length
2186 var p1
2187 var p2
2188 if sl > decimals then
2189 # Has something before the "."
2190 p1 = s.substring(0, sl-decimals)
2191 p2 = s.substring(sl-decimals, decimals)
2192 else
2193 p1 = "0"
2194 p2 = "0"*(decimals-sl) + s
2195 end
2196
2197 if i < 0 then p1 = "-" + p1
2198
2199 return p1 + "." + p2
2200 end
2201 end
2202
2203 redef class Char
2204 # assert 'x'.to_s == "x"
2205 redef fun to_s
2206 do
2207 var s = new FlatBuffer.with_capacity(1)
2208 s.chars[0] = self
2209 return s.to_s
2210 end
2211
2212 # Returns true if the char is a numerical digit
2213 #
2214 # assert '0'.is_numeric
2215 # assert '9'.is_numeric
2216 # assert not 'a'.is_numeric
2217 # assert not '?'.is_numeric
2218 fun is_numeric: Bool
2219 do
2220 return self >= '0' and self <= '9'
2221 end
2222
2223 # Returns true if the char is an alpha digit
2224 #
2225 # assert 'a'.is_alpha
2226 # assert 'Z'.is_alpha
2227 # assert not '0'.is_alpha
2228 # assert not '?'.is_alpha
2229 fun is_alpha: Bool
2230 do
2231 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2232 end
2233
2234 # Returns true if the char is an alpha or a numeric digit
2235 #
2236 # assert 'a'.is_alphanumeric
2237 # assert 'Z'.is_alphanumeric
2238 # assert '0'.is_alphanumeric
2239 # assert '9'.is_alphanumeric
2240 # assert not '?'.is_alphanumeric
2241 fun is_alphanumeric: Bool
2242 do
2243 return self.is_numeric or self.is_alpha
2244 end
2245 end
2246
2247 redef class Collection[E]
2248 # Concatenate elements.
2249 redef fun to_s
2250 do
2251 return plain_to_s
2252 end
2253
2254 # Concatenate element without separators
2255 fun plain_to_s: String
2256 do
2257 var s = new FlatBuffer
2258 for e in self do if e != null then s.append(e.to_s)
2259 return s.to_s
2260 end
2261
2262 # Concatenate and separate each elements with `sep`.
2263 #
2264 # assert [1, 2, 3].join(":") == "1:2:3"
2265 # assert [1..3].join(":") == "1:2:3"
2266 fun join(sep: Text): String
2267 do
2268 if is_empty then return ""
2269
2270 var s = new FlatBuffer # Result
2271
2272 # Concat first item
2273 var i = iterator
2274 var e = i.item
2275 if e != null then s.append(e.to_s)
2276
2277 # Concat other items
2278 i.next
2279 while i.is_ok do
2280 s.append(sep)
2281 e = i.item
2282 if e != null then s.append(e.to_s)
2283 i.next
2284 end
2285 return s.to_s
2286 end
2287 end
2288
2289 redef class Array[E]
2290
2291 # Fast implementation
2292 redef fun plain_to_s
2293 do
2294 var l = length
2295 if l == 0 then return ""
2296 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2297 var its = _items
2298 var na = new NativeArray[String](l)
2299 var i = 0
2300 var sl = 0
2301 var mypos = 0
2302 while i < l do
2303 var itsi = its[i]
2304 if itsi == null then
2305 i += 1
2306 continue
2307 end
2308 var tmp = itsi.to_s
2309 sl += tmp.length
2310 na[mypos] = tmp
2311 i += 1
2312 mypos += 1
2313 end
2314 var ns = new NativeString(sl + 1)
2315 ns[sl] = '\0'
2316 i = 0
2317 var off = 0
2318 while i < mypos do
2319 var tmp = na[i]
2320 var tpl = tmp.length
2321 if tmp isa FlatString then
2322 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2323 off += tpl
2324 else
2325 for j in tmp.substrings do
2326 var s = j.as(FlatString)
2327 var slen = s.length
2328 s.items.copy_to(ns, slen, s.index_from, off)
2329 off += slen
2330 end
2331 end
2332 i += 1
2333 end
2334 return ns.to_s_with_length(sl)
2335 end
2336 end
2337
2338 redef class NativeArray[E]
2339 # Join all the elements using `to_s`
2340 #
2341 # REQUIRE: `self isa NativeArray[String]`
2342 # REQUIRE: all elements are initialized
2343 fun native_to_s: String
2344 do
2345 assert self isa NativeArray[String]
2346 var l = length
2347 var na = self
2348 var i = 0
2349 var sl = 0
2350 var mypos = 0
2351 while i < l do
2352 sl += na[i].length
2353 i += 1
2354 mypos += 1
2355 end
2356 var ns = new NativeString(sl + 1)
2357 ns[sl] = '\0'
2358 i = 0
2359 var off = 0
2360 while i < mypos do
2361 var tmp = na[i]
2362 var tpl = tmp.length
2363 if tmp isa FlatString then
2364 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2365 off += tpl
2366 else
2367 for j in tmp.substrings do
2368 var s = j.as(FlatString)
2369 var slen = s.length
2370 s.items.copy_to(ns, slen, s.index_from, off)
2371 off += slen
2372 end
2373 end
2374 i += 1
2375 end
2376 return ns.to_s_with_length(sl)
2377 end
2378 end
2379
2380 redef class Map[K,V]
2381 # Concatenate couple of 'key value'.
2382 # key and value are separated by `couple_sep`.
2383 # each couple is separated each couple with `sep`.
2384 #
2385 # var m = new ArrayMap[Int, String]
2386 # m[1] = "one"
2387 # m[10] = "ten"
2388 # assert m.join("; ", "=") == "1=one; 10=ten"
2389 fun join(sep: String, couple_sep: String): String
2390 do
2391 if is_empty then return ""
2392
2393 var s = new FlatBuffer # Result
2394
2395 # Concat first item
2396 var i = iterator
2397 var k = i.key
2398 var e = i.item
2399 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2400
2401 # Concat other items
2402 i.next
2403 while i.is_ok do
2404 s.append(sep)
2405 k = i.key
2406 e = i.item
2407 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2408 i.next
2409 end
2410 return s.to_s
2411 end
2412 end
2413
2414 ###############################################################################
2415 # Native classes #
2416 ###############################################################################
2417
2418 # Native strings are simple C char *
2419 extern class NativeString `{ char* `}
2420 # Creates a new NativeString with a capacity of `length`
2421 new(length: Int) is intern
2422
2423 # Returns a char* starting at `index`.
2424 #
2425 # WARNING: Unsafe for extern code, use only for temporary
2426 # pointer manipulation purposes (e.g. write to file or such)
2427 fun fast_cstring(index: Int): NativeString is intern
2428
2429 # Get char at `index`.
2430 fun [](index: Int): Char is intern
2431
2432 # Set char `item` at index.
2433 fun []=(index: Int, item: Char) is intern
2434
2435 # Copy `self` to `dest`.
2436 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2437
2438 # Position of the first nul character.
2439 fun cstring_length: Int
2440 do
2441 var l = 0
2442 while self[l] != '\0' do l += 1
2443 return l
2444 end
2445
2446 # Parse `self` as an Int.
2447 fun atoi: Int is intern
2448
2449 # Parse `self` as a Float.
2450 fun atof: Float is extern "atof"
2451
2452 redef fun to_s
2453 do
2454 return to_s_with_length(cstring_length)
2455 end
2456
2457 # Returns `self` as a String of `length`.
2458 fun to_s_with_length(length: Int): FlatString
2459 do
2460 assert length >= 0
2461 var str = new FlatString.with_infos(self, length, 0, length - 1)
2462 return str
2463 end
2464
2465 # Returns `self` as a new String.
2466 fun to_s_with_copy: FlatString
2467 do
2468 var length = cstring_length
2469 var new_self = new NativeString(length + 1)
2470 copy_to(new_self, length, 0, 0)
2471 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2472 new_self[length] = '\0'
2473 str.real_items = new_self
2474 return str
2475 end
2476 end
2477
2478 redef class Sys
2479 private var args_cache: nullable Sequence[String] = null
2480
2481 # The arguments of the program as given by the OS
2482 fun program_args: Sequence[String]
2483 do
2484 if _args_cache == null then init_args
2485 return _args_cache.as(not null)
2486 end
2487
2488 # The name of the program as given by the OS
2489 fun program_name: String
2490 do
2491 return native_argv(0).to_s
2492 end
2493
2494 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2495 private fun init_args
2496 do
2497 var argc = native_argc
2498 var args = new Array[String].with_capacity(0)
2499 var i = 1
2500 while i < argc do
2501 args[i-1] = native_argv(i).to_s
2502 i += 1
2503 end
2504 _args_cache = args
2505 end
2506
2507 # First argument of the main C function.
2508 private fun native_argc: Int is intern
2509
2510 # Second argument of the main C function.
2511 private fun native_argv(i: Int): NativeString is intern
2512 end
2513
2514 # Comparator that efficienlty use `to_s` to compare things
2515 #
2516 # The comparaison call `to_s` on object and use the result to order things.
2517 #
2518 # var a = [1, 2, 3, 10, 20]
2519 # (new CachedAlphaComparator).sort(a)
2520 # assert a == [1, 10, 2, 20, 3]
2521 #
2522 # Internally the result of `to_s` is cached in a HashMap to counter
2523 # uneficient implementation of `to_s`.
2524 #
2525 # Note: it caching is not usefull, see `alpha_comparator`
2526 class CachedAlphaComparator
2527 super Comparator
2528 redef type COMPARED: Object
2529
2530 private var cache = new HashMap[Object, String]
2531
2532 private fun do_to_s(a: Object): String do
2533 if cache.has_key(a) then return cache[a]
2534 var res = a.to_s
2535 cache[a] = res
2536 return res
2537 end
2538
2539 redef fun compare(a, b) do
2540 return do_to_s(a) <=> do_to_s(b)
2541 end
2542 end
2543
2544 # see `alpha_comparator`
2545 private class AlphaComparator
2546 super Comparator
2547 redef fun compare(a, b) do return a.to_s <=> b.to_s
2548 end
2549
2550 # Stateless comparator that naively use `to_s` to compare things.
2551 #
2552 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2553 # on a single instace. See `CachedAlphaComparator` as an alternative.
2554 #
2555 # var a = [1, 2, 3, 10, 20]
2556 # alpha_comparator.sort(a)
2557 # assert a == [1, 10, 2, 20, 3]
2558 fun alpha_comparator: Comparator do return once new AlphaComparator
2559
2560 # The arguments of the program as given by the OS
2561 fun args: Sequence[String]
2562 do
2563 return sys.program_args
2564 end