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