2c296591c8fc3a8724f275a4004c360a4c4ce94c
[nit.git] / lib / standard / text / abstract_text.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
9 # another product.
10
11 # Abstract class for manipulation of sequences of characters
12 module abstract_text
13
14 import native
15 import math
16 import collection
17 intrude import collection::array
18
19 # High-level abstraction for all text representations
20 abstract class Text
21 super Comparable
22
23 redef type OTHER: Text
24
25 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
26 type SELFTYPE: Text
27
28 # Gets a view on the chars of the Text object
29 #
30 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
31 fun chars: SequenceRead[Char] is abstract
32
33 # Number of characters contained in self.
34 #
35 # assert "12345".length == 5
36 # assert "".length == 0
37 fun length: Int is abstract
38
39 # Create a substring.
40 #
41 # assert "abcd".substring(1, 2) == "bc"
42 # assert "abcd".substring(-1, 2) == "a"
43 # assert "abcd".substring(1, 0) == ""
44 # assert "abcd".substring(2, 5) == "cd"
45 #
46 # A `from` index < 0 will be replaced by 0.
47 # Unless a `count` value is > 0 at the same time.
48 # In this case, `from += count` and `count -= from`.
49 fun substring(from: Int, count: Int): SELFTYPE is abstract
50
51 # Iterates on the substrings of self if any
52 fun substrings: Iterator[FlatText] is abstract
53
54 # Is the current Text empty (== "")
55 #
56 # assert "".is_empty
57 # assert not "foo".is_empty
58 fun is_empty: Bool do return self.length == 0
59
60 # Returns an empty Text of the right type
61 #
62 # This method is used internally to get the right
63 # implementation of an empty string.
64 protected fun empty: SELFTYPE is abstract
65
66 # Gets the first char of the Text
67 #
68 # DEPRECATED : Use self.chars.first instead
69 fun first: Char do return self.chars[0]
70
71 # Access a character at `index` in the string.
72 #
73 # assert "abcd"[2] == 'c'
74 #
75 # DEPRECATED : Use self.chars.[] instead
76 fun [](index: Int): Char do return self.chars[index]
77
78 # Gets the index of the first occurence of 'c'
79 #
80 # Returns -1 if not found
81 #
82 # DEPRECATED : Use self.chars.index_of instead
83 fun index_of(c: Char): Int
84 do
85 return index_of_from(c, 0)
86 end
87
88 # Gets the last char of self
89 #
90 # DEPRECATED : Use self.chars.last instead
91 fun last: Char do return self.chars[length-1]
92
93 # Gets the index of the first occurence of ´c´ starting from ´pos´
94 #
95 # Returns -1 if not found
96 #
97 # DEPRECATED : Use self.chars.index_of_from instead
98 fun index_of_from(c: Char, pos: Int): Int
99 do
100 var iter = self.chars.iterator_from(pos)
101 while iter.is_ok do
102 if iter.item == c then return iter.index
103 iter.next
104 end
105 return -1
106 end
107
108 # Gets the last index of char ´c´
109 #
110 # Returns -1 if not found
111 #
112 # DEPRECATED : Use self.chars.last_index_of instead
113 fun last_index_of(c: Char): Int
114 do
115 return last_index_of_from(c, length - 1)
116 end
117
118 # Return a null terminated char *
119 fun to_cstring: NativeString is abstract
120
121 # The index of the last occurrence of an element starting from pos (in reverse order).
122 #
123 # var s = "/etc/bin/test/test.nit"
124 # assert s.last_index_of_from('/', s.length-1) == 13
125 # assert s.last_index_of_from('/', 12) == 8
126 #
127 # Returns -1 if not found
128 #
129 # DEPRECATED : Use self.chars.last_index_of_from instead
130 fun last_index_of_from(item: Char, pos: Int): Int
131 do
132 var iter = self.chars.reverse_iterator_from(pos)
133 while iter.is_ok do
134 if iter.item == item then return iter.index
135 iter.next
136 end
137 return -1
138 end
139
140 # Gets an iterator on the chars of self
141 #
142 # DEPRECATED : Use self.chars.iterator instead
143 fun iterator: Iterator[Char]
144 do
145 return self.chars.iterator
146 end
147
148
149 # Gets an Array containing the chars of self
150 #
151 # DEPRECATED : Use self.chars.to_a instead
152 fun to_a: Array[Char] do return chars.to_a
153
154 # Create a substring from `self` beginning at the `from` position
155 #
156 # assert "abcd".substring_from(1) == "bcd"
157 # assert "abcd".substring_from(-1) == "abcd"
158 # assert "abcd".substring_from(2) == "cd"
159 #
160 # As with substring, a `from` index < 0 will be replaced by 0
161 fun substring_from(from: Int): SELFTYPE
162 do
163 if from >= self.length then return empty
164 if from < 0 then from = 0
165 return substring(from, length - from)
166 end
167
168 # Does self have a substring `str` starting from position `pos`?
169 #
170 # assert "abcd".has_substring("bc",1) == true
171 # assert "abcd".has_substring("bc",2) == false
172 #
173 # Returns true iff all characters of `str` are presents
174 # at the expected index in `self.`
175 # The first character of `str` being at `pos`, the second
176 # character being at `pos+1` and so on...
177 #
178 # This means that all characters of `str` need to be inside `self`.
179 #
180 # assert "abcd".has_substring("xab", -1) == false
181 # assert "abcd".has_substring("cdx", 2) == false
182 #
183 # And that the empty string is always a valid substring.
184 #
185 # assert "abcd".has_substring("", 2) == true
186 # assert "abcd".has_substring("", 200) == true
187 fun has_substring(str: String, pos: Int): Bool
188 do
189 if str.is_empty then return true
190 if pos < 0 or pos + str.length > length then return false
191 var myiter = self.chars.iterator_from(pos)
192 var itsiter = str.chars.iterator
193 while myiter.is_ok and itsiter.is_ok do
194 if myiter.item != itsiter.item then return false
195 myiter.next
196 itsiter.next
197 end
198 if itsiter.is_ok then return false
199 return true
200 end
201
202 # Is this string prefixed by `prefix`?
203 #
204 # assert "abcd".has_prefix("ab") == true
205 # assert "abcbc".has_prefix("bc") == false
206 # assert "ab".has_prefix("abcd") == false
207 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
208
209 # Is this string suffixed by `suffix`?
210 #
211 # assert "abcd".has_suffix("abc") == false
212 # assert "abcd".has_suffix("bcd") == true
213 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
214
215 # If `self` contains only digits, return the corresponding integer
216 #
217 # assert "123".to_i == 123
218 # assert "-1".to_i == -1
219 fun to_i: Int
220 do
221 # Shortcut
222 return to_s.to_cstring.atoi
223 end
224
225 # If `self` contains a float, return the corresponding float
226 #
227 # assert "123".to_f == 123.0
228 # assert "-1".to_f == -1.0
229 # assert "-1.2e-3".to_f == -0.0012
230 fun to_f: Float
231 do
232 # Shortcut
233 return to_s.to_cstring.atof
234 end
235
236 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
237 #
238 # assert "ff".to_hex == 255
239 fun to_hex: Int do return a_to(16)
240
241 # If `self` contains only digits <= '7', return the corresponding integer.
242 #
243 # assert "714".to_oct == 460
244 fun to_oct: Int do return a_to(8)
245
246 # If `self` contains only '0' et '1', return the corresponding integer.
247 #
248 # assert "101101".to_bin == 45
249 fun to_bin: Int do return a_to(2)
250
251 # If `self` contains only digits and letters, return the corresponding integer in a given base
252 #
253 # assert "120".a_to(3) == 15
254 fun a_to(base: Int) : Int
255 do
256 var i = 0
257 var neg = false
258
259 for j in [0..length[ do
260 var c = chars[j]
261 var v = c.to_i
262 if v > base then
263 if neg then
264 return -i
265 else
266 return i
267 end
268 else if v < 0 then
269 neg = true
270 else
271 i = i * base + v
272 end
273 end
274 if neg then
275 return -i
276 else
277 return i
278 end
279 end
280
281 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
282 #
283 # assert "123".is_numeric == true
284 # assert "1.2".is_numeric == true
285 # assert "1,2".is_numeric == true
286 # assert "1..2".is_numeric == false
287 fun is_numeric: Bool
288 do
289 var has_point_or_comma = false
290 for i in [0..length[ do
291 var c = chars[i]
292 if not c.is_numeric then
293 if (c == '.' or c == ',') and not has_point_or_comma then
294 has_point_or_comma = true
295 else
296 return false
297 end
298 end
299 end
300 return true
301 end
302
303 # Returns `true` if the string contains only Hex chars
304 #
305 # assert "048bf".is_hex == true
306 # assert "ABCDEF".is_hex == true
307 # assert "0G".is_hex == false
308 fun is_hex: Bool
309 do
310 for i in [0..length[ do
311 var c = chars[i]
312 if not (c >= 'a' and c <= 'f') and
313 not (c >= 'A' and c <= 'F') and
314 not (c >= '0' and c <= '9') then return false
315 end
316 return true
317 end
318
319 # Are all letters in `self` upper-case ?
320 #
321 # assert "HELLO WORLD".is_upper == true
322 # assert "%$&%!".is_upper == true
323 # assert "hello world".is_upper == false
324 # assert "Hello World".is_upper == false
325 fun is_upper: Bool
326 do
327 for i in [0..length[ do
328 var char = chars[i]
329 if char.is_lower then return false
330 end
331 return true
332 end
333
334 # Are all letters in `self` lower-case ?
335 #
336 # assert "hello world".is_lower == true
337 # assert "%$&%!".is_lower == true
338 # assert "Hello World".is_lower == false
339 fun is_lower: Bool
340 do
341 for i in [0..length[ do
342 var char = chars[i]
343 if char.is_upper then return false
344 end
345 return true
346 end
347
348 # Removes the whitespaces at the beginning of self
349 #
350 # assert " \n\thello \n\t".l_trim == "hello \n\t"
351 #
352 # `Char::is_whitespace` determines what is a whitespace.
353 fun l_trim: SELFTYPE
354 do
355 var iter = self.chars.iterator
356 while iter.is_ok do
357 if not iter.item.is_whitespace then break
358 iter.next
359 end
360 if iter.index == length then return self.empty
361 return self.substring_from(iter.index)
362 end
363
364 # Removes the whitespaces at the end of self
365 #
366 # assert " \n\thello \n\t".r_trim == " \n\thello"
367 #
368 # `Char::is_whitespace` determines what is a whitespace.
369 fun r_trim: SELFTYPE
370 do
371 var iter = self.chars.reverse_iterator
372 while iter.is_ok do
373 if not iter.item.is_whitespace then break
374 iter.next
375 end
376 if iter.index < 0 then return self.empty
377 return self.substring(0, iter.index + 1)
378 end
379
380 # Trims trailing and preceding white spaces
381 #
382 # assert " Hello World ! ".trim == "Hello World !"
383 # assert "\na\nb\tc\t".trim == "a\nb\tc"
384 #
385 # `Char::is_whitespace` determines what is a whitespace.
386 fun trim: SELFTYPE do return (self.l_trim).r_trim
387
388 # Is the string non-empty but only made of whitespaces?
389 #
390 # assert " \n\t ".is_whitespace == true
391 # assert " hello ".is_whitespace == false
392 # assert "".is_whitespace == false
393 #
394 # `Char::is_whitespace` determines what is a whitespace.
395 fun is_whitespace: Bool
396 do
397 if is_empty then return false
398 for c in self.chars do
399 if not c.is_whitespace then return false
400 end
401 return true
402 end
403
404 # Returns `self` removed from its last line terminator (if any).
405 #
406 # assert "Hello\n".chomp == "Hello"
407 # assert "Hello".chomp == "Hello"
408 #
409 # assert "\n".chomp == ""
410 # assert "".chomp == ""
411 #
412 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
413 # A single line terminator, the last one, is removed.
414 #
415 # assert "\r\n".chomp == ""
416 # assert "\r\n\n".chomp == "\r\n"
417 # assert "\r\n\r\n".chomp == "\r\n"
418 # assert "\r\n\r".chomp == "\r\n"
419 #
420 # Note: unlike with most IO methods like `Reader::read_line`,
421 # a single `\r` is considered here to be a line terminator and will be removed.
422 fun chomp: SELFTYPE
423 do
424 var len = length
425 if len == 0 then return self
426 var l = self.chars.last
427 if l == '\r' then
428 return substring(0, len-1)
429 else if l != '\n' then
430 return self
431 else if len > 1 and self.chars[len-2] == '\r' then
432 return substring(0, len-2)
433 else
434 return substring(0, len-1)
435 end
436 end
437
438 # Justify a self in a space of `length`
439 #
440 # `left` is the space ratio on the left side.
441 # * 0.0 for left-justified (no space at the left)
442 # * 1.0 for right-justified (all spaces at the left)
443 # * 0.5 for centered (half the spaces at the left)
444 #
445 # Examples
446 #
447 # assert "hello".justify(10, 0.0) == "hello "
448 # assert "hello".justify(10, 1.0) == " hello"
449 # assert "hello".justify(10, 0.5) == " hello "
450 #
451 # If `length` is not enough, `self` is returned as is.
452 #
453 # assert "hello".justify(2, 0.0) == "hello"
454 #
455 # REQUIRE: `left >= 0.0 and left <= 1.0`
456 # ENSURE: `self.length <= length implies result.length == length`
457 # ENSURE: `self.length >= length implies result == self`
458 fun justify(length: Int, left: Float): String
459 do
460 var diff = length - self.length
461 if diff <= 0 then return to_s
462 assert left >= 0.0 and left <= 1.0
463 var before = (diff.to_f * left).to_i
464 return " " * before + self + " " * (diff-before)
465 end
466
467 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
468 #
469 # This method is injective (two different inputs never produce the same
470 # output) and the returned string always respect the following rules:
471 #
472 # * Contains only US-ASCII letters, digits and underscores.
473 # * Never starts with a digit.
474 # * Never ends with an underscore.
475 # * Never contains two contiguous underscores.
476 #
477 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
478 # assert "__".to_cmangle == "_95d_95d"
479 # assert "__d".to_cmangle == "_95d_d"
480 # assert "_d_".to_cmangle == "_d_95d"
481 # assert "_42".to_cmangle == "_95d42"
482 # assert "foo".to_cmangle == "foo"
483 # assert "".to_cmangle == ""
484 fun to_cmangle: String
485 do
486 if is_empty then return ""
487 var res = new Buffer
488 var underscore = false
489 var start = 0
490 var c = chars[0]
491
492 if c >= '0' and c <= '9' then
493 res.add('_')
494 res.append(c.ascii.to_s)
495 res.add('d')
496 start = 1
497 end
498 for i in [start..length[ do
499 c = chars[i]
500 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
501 res.add(c)
502 underscore = false
503 continue
504 end
505 if underscore then
506 res.append('_'.ascii.to_s)
507 res.add('d')
508 end
509 if c >= '0' and c <= '9' then
510 res.add(c)
511 underscore = false
512 else if c == '_' then
513 res.add(c)
514 underscore = true
515 else
516 res.add('_')
517 res.append(c.ascii.to_s)
518 res.add('d')
519 underscore = false
520 end
521 end
522 if underscore then
523 res.append('_'.ascii.to_s)
524 res.add('d')
525 end
526 return res.to_s
527 end
528
529 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
530 #
531 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
532 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
533 #
534 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
535 # Three digits are always used to avoid following digits to be interpreted as an element
536 # of the octal sequence.
537 #
538 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
539 #
540 # The exceptions are the common `\t` and `\n`.
541 fun escape_to_c: String
542 do
543 var b = new Buffer
544 for i in [0..length[ do
545 var c = chars[i]
546 if c == '\n' then
547 b.append("\\n")
548 else if c == '\t' then
549 b.append("\\t")
550 else if c == '\0' then
551 b.append("\\000")
552 else if c == '"' then
553 b.append("\\\"")
554 else if c == '\'' then
555 b.append("\\\'")
556 else if c == '\\' then
557 b.append("\\\\")
558 else if c.ascii < 32 then
559 b.add('\\')
560 var oct = c.ascii.to_base(8, false)
561 # Force 3 octal digits since it is the
562 # maximum allowed in the C specification
563 if oct.length == 1 then
564 b.add('0')
565 b.add('0')
566 else if oct.length == 2 then
567 b.add('0')
568 end
569 b.append(oct)
570 else
571 b.add(c)
572 end
573 end
574 return b.to_s
575 end
576
577 # Escape additionnal characters
578 # The result might no be legal in C but be used in other languages
579 #
580 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
581 fun escape_more_to_c(chars: String): String
582 do
583 var b = new Buffer
584 for c in escape_to_c.chars do
585 if chars.chars.has(c) then
586 b.add('\\')
587 end
588 b.add(c)
589 end
590 return b.to_s
591 end
592
593 # Escape to C plus braces
594 #
595 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
596 fun escape_to_nit: String do return escape_more_to_c("\{\}")
597
598 # Escape to POSIX Shell (sh).
599 #
600 # Abort if the text contains a null byte.
601 #
602 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
603 fun escape_to_sh: String do
604 var b = new Buffer
605 b.chars.add '\''
606 for i in [0..length[ do
607 var c = chars[i]
608 if c == '\'' then
609 b.append("'\\''")
610 else
611 assert without_null_byte: c != '\0'
612 b.add(c)
613 end
614 end
615 b.chars.add '\''
616 return b.to_s
617 end
618
619 # Escape to include in a Makefile
620 #
621 # Unfortunately, some characters are not escapable in Makefile.
622 # These characters are `;`, `|`, `\`, and the non-printable ones.
623 # They will be rendered as `"?{hex}"`.
624 fun escape_to_mk: String do
625 var b = new Buffer
626 for i in [0..length[ do
627 var c = chars[i]
628 if c == '$' then
629 b.append("$$")
630 else if c == ':' or c == ' ' or c == '#' then
631 b.add('\\')
632 b.add(c)
633 else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
634 b.append("?{c.ascii.to_base(16, false)}")
635 else
636 b.add(c)
637 end
638 end
639 return b.to_s
640 end
641
642 # Return a string where Nit escape sequences are transformed.
643 #
644 # var s = "\\n"
645 # assert s.length == 2
646 # var u = s.unescape_nit
647 # assert u.length == 1
648 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
649 fun unescape_nit: String
650 do
651 var res = new Buffer.with_cap(self.length)
652 var was_slash = false
653 for i in [0..length[ do
654 var c = chars[i]
655 if not was_slash then
656 if c == '\\' then
657 was_slash = true
658 else
659 res.add(c)
660 end
661 continue
662 end
663 was_slash = false
664 if c == 'n' then
665 res.add('\n')
666 else if c == 'r' then
667 res.add('\r')
668 else if c == 't' then
669 res.add('\t')
670 else if c == '0' then
671 res.add('\0')
672 else
673 res.add(c)
674 end
675 end
676 return res.to_s
677 end
678
679 # Encode `self` to percent (or URL) encoding
680 #
681 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
682 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
683 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
684 fun to_percent_encoding: String
685 do
686 var buf = new Buffer
687
688 for i in [0..length[ do
689 var c = chars[i]
690 if (c >= '0' and c <= '9') or
691 (c >= 'a' and c <= 'z') or
692 (c >= 'A' and c <= 'Z') or
693 c == '-' or c == '.' or
694 c == '_' or c == '~'
695 then
696 buf.add c
697 else buf.append "%{c.ascii.to_hex}"
698 end
699
700 return buf.to_s
701 end
702
703 # Decode `self` from percent (or URL) encoding to a clear string
704 #
705 # Replace invalid use of '%' with '?'.
706 #
707 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
708 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
709 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
710 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
711 # assert "incomplete %".from_percent_encoding == "incomplete ?"
712 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
713 fun from_percent_encoding: String
714 do
715 var buf = new Buffer
716
717 var i = 0
718 while i < length do
719 var c = chars[i]
720 if c == '%' then
721 if i + 2 >= length then
722 # What follows % has been cut off
723 buf.add '?'
724 else
725 i += 1
726 var hex_s = substring(i, 2)
727 if hex_s.is_hex then
728 var hex_i = hex_s.to_hex
729 buf.add hex_i.ascii
730 i += 1
731 else
732 # What follows a % is not Hex
733 buf.add '?'
734 i -= 1
735 end
736 end
737 else buf.add c
738
739 i += 1
740 end
741
742 return buf.to_s
743 end
744
745 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
746 #
747 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
748 #
749 # 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>
750 fun html_escape: String
751 do
752 var buf = new Buffer
753
754 for i in [0..length[ do
755 var c = chars[i]
756 if c == '&' then
757 buf.append "&amp;"
758 else if c == '<' then
759 buf.append "&lt;"
760 else if c == '>' then
761 buf.append "&gt;"
762 else if c == '"' then
763 buf.append "&#34;"
764 else if c == '\'' then
765 buf.append "&#39;"
766 else if c == '/' then
767 buf.append "&#47;"
768 else buf.add c
769 end
770
771 return buf.to_s
772 end
773
774 # Equality of text
775 # Two pieces of text are equals if thez have the same characters in the same order.
776 #
777 # assert "hello" == "hello"
778 # assert "hello" != "HELLO"
779 # assert "hello" == "hel"+"lo"
780 #
781 # Things that are not Text are not equal.
782 #
783 # assert "9" != '9'
784 # assert "9" != ['9']
785 # assert "9" != 9
786 #
787 # assert "9".chars.first == '9' # equality of Char
788 # assert "9".chars == ['9'] # equality of Sequence
789 # assert "9".to_i == 9 # equality of Int
790 redef fun ==(o)
791 do
792 if o == null then return false
793 if not o isa Text then return false
794 if self.is_same_instance(o) then return true
795 if self.length != o.length then return false
796 return self.chars == o.chars
797 end
798
799 # Lexicographical comparaison
800 #
801 # assert "abc" < "xy"
802 # assert "ABC" < "abc"
803 redef fun <(other)
804 do
805 var self_chars = self.chars.iterator
806 var other_chars = other.chars.iterator
807
808 while self_chars.is_ok and other_chars.is_ok do
809 if self_chars.item < other_chars.item then return true
810 if self_chars.item > other_chars.item then return false
811 self_chars.next
812 other_chars.next
813 end
814
815 if self_chars.is_ok then
816 return false
817 else
818 return true
819 end
820 end
821
822 # Escape string used in labels for graphviz
823 #
824 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
825 fun escape_to_dot: String
826 do
827 return escape_more_to_c("|\{\}<>")
828 end
829
830 private var hash_cache: nullable Int = null
831
832 redef fun hash
833 do
834 if hash_cache == null then
835 # djb2 hash algorithm
836 var h = 5381
837
838 for i in [0..length[ do
839 var char = chars[i]
840 h = h.lshift(5) + h + char.ascii
841 end
842
843 hash_cache = h
844 end
845 return hash_cache.as(not null)
846 end
847
848 # Gives the formatted string back as a Nit string with `args` in place
849 #
850 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
851 # assert "\\%1 This string".format("String") == "\\%1 This string"
852 fun format(args: Object...): String do
853 var s = new Array[Text]
854 var curr_st = 0
855 var i = 0
856 while i < length do
857 # Skip escaped characters
858 if self[i] == '\\' then
859 i += 1
860 # In case of format
861 else if self[i] == '%' then
862 var fmt_st = i
863 i += 1
864 var ciph_st = i
865 while i < length and self[i].is_numeric do
866 i += 1
867 end
868 i -= 1
869 var fmt_end = i
870 var ciph_len = fmt_end - ciph_st + 1
871 s.push substring(curr_st, fmt_st - curr_st)
872 s.push args[substring(ciph_st, ciph_len).to_i - 1].to_s
873 curr_st = i + 1
874 end
875 i += 1
876 end
877 s.push substring(curr_st, length - curr_st)
878 return s.plain_to_s
879 end
880
881 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
882 #
883 # Basically a high-level synonym of NativeString::copy_to
884 #
885 # REQUIRE: `n` must be large enough to contain `len` bytes
886 #
887 # var ns = new NativeString(8)
888 # "Text is String".copy_to_native(ns, 8, 2, 0)
889 # assert ns.to_s_with_length(8) == "xt is St"
890 #
891 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
892 var mypos = src_offset
893 var itspos = dest_offset
894 while n > 0 do
895 dest[itspos] = self.chars[mypos]
896 itspos += 1
897 mypos += 1
898 n -= 1
899 end
900 end
901
902 end
903
904 # All kinds of array-based text representations.
905 abstract class FlatText
906 super Text
907
908 # Underlying C-String (`char*`)
909 #
910 # Warning : Might be void in some subclasses, be sure to check
911 # if set before using it.
912 private var items: NativeString is noinit
913
914 # Real items, used as cache for to_cstring is called
915 private var real_items: nullable NativeString = null
916
917 # Returns a char* starting at position `index_from`
918 #
919 # WARNING: If you choose to use this service, be careful of the following.
920 #
921 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
922 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
923 # deallocated at any moment, rendering the pointer returned by this function invalid.
924 # Any access to freed memory may very likely cause undefined behaviour or a crash.
925 # (Failure to do so will most certainly result in long and painful debugging hours)
926 #
927 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
928 # then immediately return).
929 #
930 # As always, do not modify the content of the String in C code, if this is what you want
931 # copy locally the char* as Nit Strings are immutable.
932 private fun fast_cstring: NativeString is abstract
933
934 redef var length = 0
935
936 redef fun output
937 do
938 var i = 0
939 while i < length do
940 items[i].output
941 i += 1
942 end
943 end
944
945 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
946 items.copy_to(dest, n, src_offset, dest_offset)
947 end
948 end
949
950 # Abstract class for the SequenceRead compatible
951 # views on String and Buffer objects
952 private abstract class StringCharView
953 super SequenceRead[Char]
954
955 type SELFTYPE: Text
956
957 var target: SELFTYPE
958
959 redef fun is_empty do return target.is_empty
960
961 redef fun length do return target.length
962
963 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
964
965 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
966 end
967
968 # Immutable sequence of characters.
969 #
970 # String objects may be created using literals.
971 #
972 # assert "Hello World!" isa String
973 abstract class String
974 super Text
975
976 redef type SELFTYPE: String is fixed
977
978 redef fun to_s do return self
979
980 # Concatenates `o` to `self`
981 #
982 # assert "hello" + "world" == "helloworld"
983 # assert "" + "hello" + "" == "hello"
984 fun +(o: Text): SELFTYPE is abstract
985
986 # Concatenates self `i` times
987 #
988 # assert "abc" * 4 == "abcabcabcabc"
989 # assert "abc" * 1 == "abc"
990 # assert "abc" * 0 == ""
991 fun *(i: Int): SELFTYPE is abstract
992
993 # Insert `s` at `pos`.
994 #
995 # assert "helloworld".insert_at(" ", 5) == "hello world"
996 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
997
998 redef fun substrings is abstract
999
1000 # Returns a reversed version of self
1001 #
1002 # assert "hello".reversed == "olleh"
1003 # assert "bob".reversed == "bob"
1004 # assert "".reversed == ""
1005 fun reversed: SELFTYPE is abstract
1006
1007 # A upper case version of `self`
1008 #
1009 # assert "Hello World!".to_upper == "HELLO WORLD!"
1010 fun to_upper: SELFTYPE is abstract
1011
1012 # A lower case version of `self`
1013 #
1014 # assert "Hello World!".to_lower == "hello world!"
1015 fun to_lower : SELFTYPE is abstract
1016
1017 # Takes a camel case `self` and converts it to snake case
1018 #
1019 # assert "randomMethodId".to_snake_case == "random_method_id"
1020 #
1021 # The rules are the following:
1022 #
1023 # An uppercase is always converted to a lowercase
1024 #
1025 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1026 #
1027 # An uppercase that follows a lowercase is prefixed with an underscore
1028 #
1029 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1030 #
1031 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1032 #
1033 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1034 #
1035 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1036 #
1037 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1038 fun to_snake_case: SELFTYPE
1039 do
1040 if self.is_lower then return self
1041
1042 var new_str = new Buffer.with_cap(self.length)
1043 var prev_is_lower = false
1044 var prev_is_upper = false
1045
1046 for i in [0..length[ do
1047 var char = chars[i]
1048 if char.is_lower then
1049 new_str.add(char)
1050 prev_is_lower = true
1051 prev_is_upper = false
1052 else if char.is_upper then
1053 if prev_is_lower then
1054 new_str.add('_')
1055 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1056 new_str.add('_')
1057 end
1058 new_str.add(char.to_lower)
1059 prev_is_lower = false
1060 prev_is_upper = true
1061 else
1062 new_str.add(char)
1063 prev_is_lower = false
1064 prev_is_upper = false
1065 end
1066 end
1067
1068 return new_str.to_s
1069 end
1070
1071 # Takes a snake case `self` and converts it to camel case
1072 #
1073 # assert "random_method_id".to_camel_case == "randomMethodId"
1074 #
1075 # If the identifier is prefixed by an underscore, the underscore is ignored
1076 #
1077 # assert "_private_field".to_camel_case == "_privateField"
1078 #
1079 # If `self` is upper, it is returned unchanged
1080 #
1081 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1082 #
1083 # If there are several consecutive underscores, they are considered as a single one
1084 #
1085 # assert "random__method_id".to_camel_case == "randomMethodId"
1086 fun to_camel_case: SELFTYPE
1087 do
1088 if self.is_upper then return self
1089
1090 var new_str = new Buffer
1091 var is_first_char = true
1092 var follows_us = false
1093
1094 for i in [0..length[ do
1095 var char = chars[i]
1096 if is_first_char then
1097 new_str.add(char)
1098 is_first_char = false
1099 else if char == '_' then
1100 follows_us = true
1101 else if follows_us then
1102 new_str.add(char.to_upper)
1103 follows_us = false
1104 else
1105 new_str.add(char)
1106 end
1107 end
1108
1109 return new_str.to_s
1110 end
1111
1112 # Returns a capitalized `self`
1113 #
1114 # Letters that follow a letter are lowercased
1115 # Letters that follow a non-letter are upcased.
1116 #
1117 # SEE : `Char::is_letter` for the definition of letter.
1118 #
1119 # assert "jAVASCRIPT".capitalized == "Javascript"
1120 # assert "i am root".capitalized == "I Am Root"
1121 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1122 fun capitalized: SELFTYPE do
1123 if length == 0 then return self
1124
1125 var buf = new Buffer.with_cap(length)
1126
1127 var curr = chars[0].to_upper
1128 var prev = curr
1129 buf[0] = curr
1130
1131 for i in [1 .. length[ do
1132 prev = curr
1133 curr = self[i]
1134 if prev.is_letter then
1135 buf[i] = curr.to_lower
1136 else
1137 buf[i] = curr.to_upper
1138 end
1139 end
1140
1141 return buf.to_s
1142 end
1143 end
1144
1145 # A mutable sequence of characters.
1146 abstract class Buffer
1147 super Text
1148
1149 # Returns an arbitrary subclass of `Buffer` with default parameters
1150 new is abstract
1151
1152 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1153 new with_cap(i: Int) is abstract
1154
1155 redef type SELFTYPE: Buffer is fixed
1156
1157 # Specific implementations MUST set this to `true` in order to invalidate caches
1158 protected var is_dirty = true
1159
1160 # Copy-On-Write flag
1161 #
1162 # If the `Buffer` was to_s'd, the next in-place altering
1163 # operation will cause the current `Buffer` to be re-allocated.
1164 #
1165 # The flag will then be set at `false`.
1166 protected var written = false
1167
1168 # Modifies the char contained at pos `index`
1169 #
1170 # DEPRECATED : Use self.chars.[]= instead
1171 fun []=(index: Int, item: Char) is abstract
1172
1173 # Adds a char `c` at the end of self
1174 #
1175 # DEPRECATED : Use self.chars.add instead
1176 fun add(c: Char) is abstract
1177
1178 # Clears the buffer
1179 #
1180 # var b = new Buffer
1181 # b.append "hello"
1182 # assert not b.is_empty
1183 # b.clear
1184 # assert b.is_empty
1185 fun clear is abstract
1186
1187 # Enlarges the subsequent array containing the chars of self
1188 fun enlarge(cap: Int) is abstract
1189
1190 # Adds the content of text `s` at the end of self
1191 #
1192 # var b = new Buffer
1193 # b.append "hello"
1194 # b.append "world"
1195 # assert b == "helloworld"
1196 fun append(s: Text) is abstract
1197
1198 # `self` is appended in such a way that `self` is repeated `r` times
1199 #
1200 # var b = new Buffer
1201 # b.append "hello"
1202 # b.times 3
1203 # assert b == "hellohellohello"
1204 fun times(r: Int) is abstract
1205
1206 # Reverses itself in-place
1207 #
1208 # var b = new Buffer
1209 # b.append("hello")
1210 # b.reverse
1211 # assert b == "olleh"
1212 fun reverse is abstract
1213
1214 # Changes each lower-case char in `self` by its upper-case variant
1215 #
1216 # var b = new Buffer
1217 # b.append("Hello World!")
1218 # b.upper
1219 # assert b == "HELLO WORLD!"
1220 fun upper is abstract
1221
1222 # Changes each upper-case char in `self` by its lower-case variant
1223 #
1224 # var b = new Buffer
1225 # b.append("Hello World!")
1226 # b.lower
1227 # assert b == "hello world!"
1228 fun lower is abstract
1229
1230 # Capitalizes each word in `self`
1231 #
1232 # Letters that follow a letter are lowercased
1233 # Letters that follow a non-letter are upcased.
1234 #
1235 # SEE: `Char::is_letter` for the definition of a letter.
1236 #
1237 # var b = new FlatBuffer.from("jAVAsCriPt")
1238 # b.capitalize
1239 # assert b == "Javascript"
1240 # b = new FlatBuffer.from("i am root")
1241 # b.capitalize
1242 # assert b == "I Am Root"
1243 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1244 # b.capitalize
1245 # assert b == "Ab_C -Ab0C Ab\nC"
1246 fun capitalize do
1247 if length == 0 then return
1248 var c = self[0].to_upper
1249 self[0] = c
1250 var prev = c
1251 for i in [1 .. length[ do
1252 prev = c
1253 c = self[i]
1254 if prev.is_letter then
1255 self[i] = c.to_lower
1256 else
1257 self[i] = c.to_upper
1258 end
1259 end
1260 end
1261
1262 redef fun hash
1263 do
1264 if is_dirty then hash_cache = null
1265 return super
1266 end
1267
1268 # In Buffers, the internal sequence of character is mutable
1269 # Thus, `chars` can be used to modify the buffer.
1270 redef fun chars: Sequence[Char] is abstract
1271 end
1272
1273 # View on Buffer objects, extends Sequence
1274 # for mutation operations
1275 private abstract class BufferCharView
1276 super StringCharView
1277 super Sequence[Char]
1278
1279 redef type SELFTYPE: Buffer
1280
1281 end
1282
1283 redef class Object
1284 # User readable representation of `self`.
1285 fun to_s: String do return inspect
1286
1287 # The class name of the object in NativeString format.
1288 private fun native_class_name: NativeString is intern
1289
1290 # The class name of the object.
1291 #
1292 # assert 5.class_name == "Int"
1293 fun class_name: String do return native_class_name.to_s
1294
1295 # Developer readable representation of `self`.
1296 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1297 fun inspect: String
1298 do
1299 return "<{inspect_head}>"
1300 end
1301
1302 # Return "CLASSNAME:#OBJECTID".
1303 # This function is mainly used with the redefinition of the inspect method
1304 protected fun inspect_head: String
1305 do
1306 return "{class_name}:#{object_id.to_hex}"
1307 end
1308 end
1309
1310 redef class Bool
1311 # assert true.to_s == "true"
1312 # assert false.to_s == "false"
1313 redef fun to_s
1314 do
1315 if self then
1316 return once "true"
1317 else
1318 return once "false"
1319 end
1320 end
1321 end
1322
1323 redef class Byte
1324 # C function to calculate the length of the `NativeString` to receive `self`
1325 private fun byte_to_s_len: Int is extern "native_byte_length_str"
1326
1327 # C function to convert an nit Int to a NativeString (char*)
1328 private fun native_byte_to_s(nstr: NativeString, strlen: Int) is extern "native_byte_to_s"
1329
1330 # Displayable byte in its hexadecimal form (0x..)
1331 #
1332 # assert 1.to_b.to_s == "0x01"
1333 # assert (-123).to_b.to_s == "0x85"
1334 redef fun to_s do
1335 var nslen = byte_to_s_len
1336 var ns = new NativeString(nslen + 1)
1337 ns[nslen] = '\0'
1338 native_byte_to_s(ns, nslen + 1)
1339 return ns.to_s_with_length(nslen)
1340 end
1341 end
1342
1343 redef class Int
1344
1345 # Wrapper of strerror C function
1346 private fun strerror_ext: NativeString is extern "strerror"
1347
1348 # Returns a string describing error number
1349 fun strerror: String do return strerror_ext.to_s
1350
1351 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1352 # assume < to_c max const of char
1353 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1354 do
1355 var n: Int
1356 # Sign
1357 if self < 0 then
1358 n = - self
1359 s.chars[0] = '-'
1360 else if self == 0 then
1361 s.chars[0] = '0'
1362 return
1363 else
1364 n = self
1365 end
1366 # Fill digits
1367 var pos = digit_count(base) - 1
1368 while pos >= 0 and n > 0 do
1369 s.chars[pos] = (n % base).to_c
1370 n = n / base # /
1371 pos -= 1
1372 end
1373 end
1374
1375 # C function to calculate the length of the `NativeString` to receive `self`
1376 private fun int_to_s_len: Int is extern "native_int_length_str"
1377
1378 # C function to convert an nit Int to a NativeString (char*)
1379 private fun native_int_to_s(nstr: NativeString, strlen: Int) is extern "native_int_to_s"
1380
1381 # return displayable int in base base and signed
1382 fun to_base(base: Int, signed: Bool): String is abstract
1383
1384 # return displayable int in hexadecimal
1385 #
1386 # assert 1.to_hex == "1"
1387 # assert (-255).to_hex == "-ff"
1388 fun to_hex: String do return to_base(16,false)
1389 end
1390
1391 redef class Float
1392 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1393 #
1394 # assert 12.34.to_s == "12.34"
1395 # assert (-0120.030).to_s == "-120.03"
1396 #
1397 # see `to_precision` for a custom precision.
1398 redef fun to_s do
1399 var str = to_precision( 3 )
1400 if is_inf != 0 or is_nan then return str
1401 var len = str.length
1402 for i in [0..len-1] do
1403 var j = len-1-i
1404 var c = str.chars[j]
1405 if c == '0' then
1406 continue
1407 else if c == '.' then
1408 return str.substring( 0, j+2 )
1409 else
1410 return str.substring( 0, j+1 )
1411 end
1412 end
1413 return str
1414 end
1415
1416 # `String` representation of `self` with the given number of `decimals`
1417 #
1418 # assert 12.345.to_precision(0) == "12"
1419 # assert 12.345.to_precision(3) == "12.345"
1420 # assert (-12.345).to_precision(3) == "-12.345"
1421 # assert (-0.123).to_precision(3) == "-0.123"
1422 # assert 0.999.to_precision(2) == "1.00"
1423 # assert 0.999.to_precision(4) == "0.9990"
1424 fun to_precision(decimals: Int): String
1425 do
1426 if is_nan then return "nan"
1427
1428 var isinf = self.is_inf
1429 if isinf == 1 then
1430 return "inf"
1431 else if isinf == -1 then
1432 return "-inf"
1433 end
1434
1435 if decimals == 0 then return self.to_i.to_s
1436 var f = self
1437 for i in [0..decimals[ do f = f * 10.0
1438 if self > 0.0 then
1439 f = f + 0.5
1440 else
1441 f = f - 0.5
1442 end
1443 var i = f.to_i
1444 if i == 0 then return "0." + "0"*decimals
1445
1446 # Prepare both parts of the float, before and after the "."
1447 var s = i.abs.to_s
1448 var sl = s.length
1449 var p1
1450 var p2
1451 if sl > decimals then
1452 # Has something before the "."
1453 p1 = s.substring(0, sl-decimals)
1454 p2 = s.substring(sl-decimals, decimals)
1455 else
1456 p1 = "0"
1457 p2 = "0"*(decimals-sl) + s
1458 end
1459
1460 if i < 0 then p1 = "-" + p1
1461
1462 return p1 + "." + p2
1463 end
1464 end
1465
1466 redef class Char
1467 # assert 'x'.to_s == "x"
1468 redef fun to_s
1469 do
1470 var s = new Buffer.with_cap(1)
1471 s.chars[0] = self
1472 return s.to_s
1473 end
1474
1475 # Returns true if the char is a numerical digit
1476 #
1477 # assert '0'.is_numeric
1478 # assert '9'.is_numeric
1479 # assert not 'a'.is_numeric
1480 # assert not '?'.is_numeric
1481 fun is_numeric: Bool
1482 do
1483 return self >= '0' and self <= '9'
1484 end
1485
1486 # Returns true if the char is an alpha digit
1487 #
1488 # assert 'a'.is_alpha
1489 # assert 'Z'.is_alpha
1490 # assert not '0'.is_alpha
1491 # assert not '?'.is_alpha
1492 fun is_alpha: Bool
1493 do
1494 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1495 end
1496
1497 # Returns true if the char is an alpha or a numeric digit
1498 #
1499 # assert 'a'.is_alphanumeric
1500 # assert 'Z'.is_alphanumeric
1501 # assert '0'.is_alphanumeric
1502 # assert '9'.is_alphanumeric
1503 # assert not '?'.is_alphanumeric
1504 fun is_alphanumeric: Bool
1505 do
1506 return self.is_numeric or self.is_alpha
1507 end
1508 end
1509
1510 redef class Collection[E]
1511 # String representation of the content of the collection.
1512 #
1513 # The standard representation is the list of elements separated with commas.
1514 #
1515 # ~~~
1516 # assert [1,2,3].to_s == "[1,2,3]"
1517 # assert [1..3].to_s == "[1,2,3]"
1518 # assert (new Array[Int]).to_s == "[]" # empty collection
1519 # ~~~
1520 #
1521 # Subclasses may return a more specific string representation.
1522 redef fun to_s
1523 do
1524 return "[" + join(",") + "]"
1525 end
1526
1527 # Concatenate elements without separators
1528 #
1529 # ~~~
1530 # assert [1,2,3].plain_to_s == "123"
1531 # assert [11..13].plain_to_s == "111213"
1532 # assert (new Array[Int]).plain_to_s == "" # empty collection
1533 # ~~~
1534 fun plain_to_s: String
1535 do
1536 var s = new Buffer
1537 for e in self do if e != null then s.append(e.to_s)
1538 return s.to_s
1539 end
1540
1541 # Concatenate and separate each elements with `sep`.
1542 #
1543 # assert [1, 2, 3].join(":") == "1:2:3"
1544 # assert [1..3].join(":") == "1:2:3"
1545 fun join(sep: Text): String
1546 do
1547 if is_empty then return ""
1548
1549 var s = new Buffer # Result
1550
1551 # Concat first item
1552 var i = iterator
1553 var e = i.item
1554 if e != null then s.append(e.to_s)
1555
1556 # Concat other items
1557 i.next
1558 while i.is_ok do
1559 s.append(sep)
1560 e = i.item
1561 if e != null then s.append(e.to_s)
1562 i.next
1563 end
1564 return s.to_s
1565 end
1566 end
1567
1568 redef class Map[K,V]
1569 # Concatenate couple of 'key value'.
1570 # key and value are separated by `couple_sep`.
1571 # each couple is separated each couple with `sep`.
1572 #
1573 # var m = new ArrayMap[Int, String]
1574 # m[1] = "one"
1575 # m[10] = "ten"
1576 # assert m.join("; ", "=") == "1=one; 10=ten"
1577 fun join(sep: String, couple_sep: String): String is abstract
1578 end
1579
1580 redef class Sys
1581 private var args_cache: nullable Sequence[String] = null
1582
1583 # The arguments of the program as given by the OS
1584 fun program_args: Sequence[String]
1585 do
1586 if _args_cache == null then init_args
1587 return _args_cache.as(not null)
1588 end
1589
1590 # The name of the program as given by the OS
1591 fun program_name: String
1592 do
1593 return native_argv(0).to_s
1594 end
1595
1596 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1597 private fun init_args
1598 do
1599 var argc = native_argc
1600 var args = new Array[String].with_capacity(0)
1601 var i = 1
1602 while i < argc do
1603 args[i-1] = native_argv(i).to_s
1604 i += 1
1605 end
1606 _args_cache = args
1607 end
1608
1609 # First argument of the main C function.
1610 private fun native_argc: Int is intern
1611
1612 # Second argument of the main C function.
1613 private fun native_argv(i: Int): NativeString is intern
1614 end
1615
1616 # Comparator that efficienlty use `to_s` to compare things
1617 #
1618 # The comparaison call `to_s` on object and use the result to order things.
1619 #
1620 # var a = [1, 2, 3, 10, 20]
1621 # (new CachedAlphaComparator).sort(a)
1622 # assert a == [1, 10, 2, 20, 3]
1623 #
1624 # Internally the result of `to_s` is cached in a HashMap to counter
1625 # uneficient implementation of `to_s`.
1626 #
1627 # Note: it caching is not usefull, see `alpha_comparator`
1628 class CachedAlphaComparator
1629 super Comparator
1630 redef type COMPARED: Object
1631
1632 private var cache = new HashMap[Object, String]
1633
1634 private fun do_to_s(a: Object): String do
1635 if cache.has_key(a) then return cache[a]
1636 var res = a.to_s
1637 cache[a] = res
1638 return res
1639 end
1640
1641 redef fun compare(a, b) do
1642 return do_to_s(a) <=> do_to_s(b)
1643 end
1644 end
1645
1646 # see `alpha_comparator`
1647 private class AlphaComparator
1648 super Comparator
1649 redef fun compare(a, b) do return a.to_s <=> b.to_s
1650 end
1651
1652 # Stateless comparator that naively use `to_s` to compare things.
1653 #
1654 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1655 # on a single instace. See `CachedAlphaComparator` as an alternative.
1656 #
1657 # var a = [1, 2, 3, 10, 20]
1658 # alpha_comparator.sort(a)
1659 # assert a == [1, 10, 2, 20, 3]
1660 fun alpha_comparator: Comparator do return once new AlphaComparator
1661
1662 # The arguments of the program as given by the OS
1663 fun args: Sequence[String]
1664 do
1665 return sys.program_args
1666 end
1667
1668 redef class NativeString
1669 # Returns `self` as a new String.
1670 fun to_s_with_copy: String is abstract
1671
1672 # Returns `self` as a String of `length`.
1673 fun to_s_with_length(length: Int): String is abstract
1674 end
1675
1676 redef class NativeArray[E]
1677 # Join all the elements using `to_s`
1678 #
1679 # REQUIRE: `self isa NativeArray[String]`
1680 # REQUIRE: all elements are initialized
1681 fun native_to_s: String is abstract
1682 end