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