Merge: glesv2: services for textures, shaders, framebuffers, renderbuffers & more...
[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.code_point.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('_'.code_point.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.code_point.to_s)
570 res.add('d')
571 underscore = false
572 end
573 end
574 if underscore then
575 res.append('_'.code_point.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.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".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 == '"' then
603 b.append("\\\"")
604 else if c == '\'' then
605 b.append("\\\'")
606 else if c == '\\' then
607 b.append("\\\\")
608 else if c.code_point < 32 then
609 b.add('\\')
610 var oct = c.code_point.to_base(8, false)
611 # Force 3 octal digits since it is the
612 # maximum allowed in the C specification
613 if oct.length == 1 then
614 b.add('0')
615 b.add('0')
616 else if oct.length == 2 then
617 b.add('0')
618 end
619 b.append(oct)
620 else
621 b.add(c)
622 end
623 end
624 return b.to_s
625 end
626
627 # Escape additionnal characters
628 # The result might no be legal in C but be used in other languages
629 #
630 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
631 fun escape_more_to_c(chars: String): String
632 do
633 var b = new Buffer
634 for c in escape_to_c.chars do
635 if chars.chars.has(c) then
636 b.add('\\')
637 end
638 b.add(c)
639 end
640 return b.to_s
641 end
642
643 # Escape to C plus braces
644 #
645 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
646 fun escape_to_nit: String do return escape_more_to_c("\{\}")
647
648 # Escape to POSIX Shell (sh).
649 #
650 # Abort if the text contains a null byte.
651 #
652 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
653 fun escape_to_sh: String do
654 var b = new Buffer
655 b.chars.add '\''
656 for i in [0..length[ do
657 var c = chars[i]
658 if c == '\'' then
659 b.append("'\\''")
660 else
661 assert without_null_byte: c != '\0'
662 b.add(c)
663 end
664 end
665 b.chars.add '\''
666 return b.to_s
667 end
668
669 # Escape to include in a Makefile
670 #
671 # Unfortunately, some characters are not escapable in Makefile.
672 # These characters are `;`, `|`, `\`, and the non-printable ones.
673 # They will be rendered as `"?{hex}"`.
674 fun escape_to_mk: String do
675 var b = new Buffer
676 for i in [0..length[ do
677 var c = chars[i]
678 if c == '$' then
679 b.append("$$")
680 else if c == ':' or c == ' ' or c == '#' then
681 b.add('\\')
682 b.add(c)
683 else if c.code_point < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
684 b.append("?{c.code_point.to_base(16, false)}")
685 else
686 b.add(c)
687 end
688 end
689 return b.to_s
690 end
691
692 # Return a string where Nit escape sequences are transformed.
693 #
694 # var s = "\\n"
695 # assert s.length == 2
696 # var u = s.unescape_nit
697 # assert u.length == 1
698 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
699 fun unescape_nit: String
700 do
701 var res = new Buffer.with_cap(self.length)
702 var was_slash = false
703 for i in [0..length[ do
704 var c = chars[i]
705 if not was_slash then
706 if c == '\\' then
707 was_slash = true
708 else
709 res.add(c)
710 end
711 continue
712 end
713 was_slash = false
714 if c == 'n' then
715 res.add('\n')
716 else if c == 'r' then
717 res.add('\r')
718 else if c == 't' then
719 res.add('\t')
720 else if c == '0' then
721 res.add('\0')
722 else
723 res.add(c)
724 end
725 end
726 return res.to_s
727 end
728
729 # Encode `self` to percent (or URL) encoding
730 #
731 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
732 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
733 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
734 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
735 fun to_percent_encoding: String
736 do
737 var buf = new Buffer
738
739 for i in [0..length[ do
740 var c = chars[i]
741 if (c >= '0' and c <= '9') or
742 (c >= 'a' and c <= 'z') or
743 (c >= 'A' and c <= 'Z') or
744 c == '-' or c == '.' or
745 c == '_' or c == '~'
746 then
747 buf.add c
748 else
749 var bytes = c.to_s.bytes
750 for b in bytes do buf.append "%{b.to_i.to_hex}"
751 end
752 end
753
754 return buf.to_s
755 end
756
757 # Decode `self` from percent (or URL) encoding to a clear string
758 #
759 # Replace invalid use of '%' with '?'.
760 #
761 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
762 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
763 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
764 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
765 # assert "incomplete %".from_percent_encoding == "incomplete ?"
766 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
767 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
768 fun from_percent_encoding: String
769 do
770 var len = bytelen
771 var has_percent = false
772 for c in chars do
773 if c == '%' then
774 len -= 2
775 has_percent = true
776 end
777 end
778
779 # If no transformation is needed, return self as a string
780 if not has_percent then return to_s
781
782 var buf = new NativeString(len)
783 var i = 0
784 var l = 0
785 while i < length do
786 var c = chars[i]
787 if c == '%' then
788 if i + 2 >= length then
789 # What follows % has been cut off
790 buf[l] = '?'.ascii
791 else
792 i += 1
793 var hex_s = substring(i, 2)
794 if hex_s.is_hex then
795 var hex_i = hex_s.to_hex
796 buf[l] = hex_i.to_b
797 i += 1
798 else
799 # What follows a % is not Hex
800 buf[l] = '?'.ascii
801 i -= 1
802 end
803 end
804 else buf[l] = c.ascii
805
806 i += 1
807 l += 1
808 end
809
810 return buf.to_s_with_length(l)
811 end
812
813 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
814 #
815 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
816 #
817 # 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>
818 fun html_escape: String
819 do
820 var buf = new Buffer
821
822 for i in [0..length[ do
823 var c = chars[i]
824 if c == '&' then
825 buf.append "&amp;"
826 else if c == '<' then
827 buf.append "&lt;"
828 else if c == '>' then
829 buf.append "&gt;"
830 else if c == '"' then
831 buf.append "&#34;"
832 else if c == '\'' then
833 buf.append "&#39;"
834 else if c == '/' then
835 buf.append "&#47;"
836 else buf.add c
837 end
838
839 return buf.to_s
840 end
841
842 # Equality of text
843 # Two pieces of text are equals if thez have the same characters in the same order.
844 #
845 # assert "hello" == "hello"
846 # assert "hello" != "HELLO"
847 # assert "hello" == "hel"+"lo"
848 #
849 # Things that are not Text are not equal.
850 #
851 # assert "9" != '9'
852 # assert "9" != ['9']
853 # assert "9" != 9
854 #
855 # assert "9".chars.first == '9' # equality of Char
856 # assert "9".chars == ['9'] # equality of Sequence
857 # assert "9".to_i == 9 # equality of Int
858 redef fun ==(o)
859 do
860 if o == null then return false
861 if not o isa Text then return false
862 if self.is_same_instance(o) then return true
863 if self.length != o.length then return false
864 return self.chars == o.chars
865 end
866
867 # Lexicographical comparaison
868 #
869 # assert "abc" < "xy"
870 # assert "ABC" < "abc"
871 redef fun <(other)
872 do
873 var self_chars = self.chars.iterator
874 var other_chars = other.chars.iterator
875
876 while self_chars.is_ok and other_chars.is_ok do
877 if self_chars.item < other_chars.item then return true
878 if self_chars.item > other_chars.item then return false
879 self_chars.next
880 other_chars.next
881 end
882
883 if self_chars.is_ok then
884 return false
885 else
886 return true
887 end
888 end
889
890 # Escape string used in labels for graphviz
891 #
892 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
893 fun escape_to_dot: String
894 do
895 return escape_more_to_c("|\{\}<>")
896 end
897
898 private var hash_cache: nullable Int = null
899
900 redef fun hash
901 do
902 if hash_cache == null then
903 # djb2 hash algorithm
904 var h = 5381
905
906 for i in [0..length[ do
907 var char = chars[i]
908 h = (h << 5) + h + char.code_point
909 end
910
911 hash_cache = h
912 end
913 return hash_cache.as(not null)
914 end
915
916 # Gives the formatted string back as a Nit string with `args` in place
917 #
918 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
919 # assert "\\%1 This string".format("String") == "\\%1 This string"
920 fun format(args: Object...): String do
921 var s = new Array[Text]
922 var curr_st = 0
923 var i = 0
924 while i < length do
925 # Skip escaped characters
926 if self[i] == '\\' then
927 i += 1
928 # In case of format
929 else if self[i] == '%' then
930 var fmt_st = i
931 i += 1
932 var ciph_st = i
933 while i < length and self[i].is_numeric do
934 i += 1
935 end
936 i -= 1
937 var fmt_end = i
938 var ciph_len = fmt_end - ciph_st + 1
939
940 var arg_index = substring(ciph_st, ciph_len).to_i - 1
941 if arg_index >= args.length then continue
942
943 s.push substring(curr_st, fmt_st - curr_st)
944 s.push args[arg_index].to_s
945 curr_st = i + 1
946 end
947 i += 1
948 end
949 s.push substring(curr_st, length - curr_st)
950 return s.plain_to_s
951 end
952
953 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
954 #
955 # Basically a high-level synonym of NativeString::copy_to
956 #
957 # REQUIRE: `n` must be large enough to contain `len` bytes
958 #
959 # var ns = new NativeString(8)
960 # "Text is String".copy_to_native(ns, 8, 2, 0)
961 # assert ns.to_s_with_length(8) == "xt is St"
962 #
963 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
964 var mypos = src_offset
965 var itspos = dest_offset
966 while n > 0 do
967 dest[itspos] = self.bytes[mypos]
968 itspos += 1
969 mypos += 1
970 n -= 1
971 end
972 end
973
974 end
975
976 # All kinds of array-based text representations.
977 abstract class FlatText
978 super Text
979
980 # Underlying C-String (`char*`)
981 #
982 # Warning : Might be void in some subclasses, be sure to check
983 # if set before using it.
984 private var items: NativeString is noinit
985
986 # Real items, used as cache for to_cstring is called
987 private var real_items: nullable NativeString = null
988
989 # Returns a char* starting at position `first_byte`
990 #
991 # WARNING: If you choose to use this service, be careful of the following.
992 #
993 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
994 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
995 # deallocated at any moment, rendering the pointer returned by this function invalid.
996 # Any access to freed memory may very likely cause undefined behaviour or a crash.
997 # (Failure to do so will most certainly result in long and painful debugging hours)
998 #
999 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1000 # then immediately return).
1001 #
1002 # As always, do not modify the content of the String in C code, if this is what you want
1003 # copy locally the char* as Nit Strings are immutable.
1004 private fun fast_cstring: NativeString is abstract
1005
1006 redef var length = 0
1007
1008 redef var bytelen = 0
1009
1010 redef fun output
1011 do
1012 var i = 0
1013 while i < length do
1014 items[i].output
1015 i += 1
1016 end
1017 end
1018
1019 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1020 items.copy_to(dest, n, src_offset, dest_offset)
1021 end
1022 end
1023
1024 # Abstract class for the SequenceRead compatible
1025 # views on the chars of any Text
1026 private abstract class StringCharView
1027 super SequenceRead[Char]
1028
1029 type SELFTYPE: Text
1030
1031 var target: SELFTYPE
1032
1033 redef fun is_empty do return target.is_empty
1034
1035 redef fun length do return target.length
1036
1037 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1038
1039 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1040 end
1041
1042 # Abstract class for the SequenceRead compatible
1043 # views on the bytes of any Text
1044 private abstract class StringByteView
1045 super SequenceRead[Byte]
1046
1047 type SELFTYPE: Text
1048
1049 var target: SELFTYPE
1050
1051 redef fun is_empty do return target.is_empty
1052
1053 redef fun length do return target.bytelen
1054
1055 redef fun iterator do return self.iterator_from(0)
1056
1057 redef fun reverse_iterator do return self.reverse_iterator_from(target.bytelen - 1)
1058 end
1059
1060 # Immutable sequence of characters.
1061 #
1062 # String objects may be created using literals.
1063 #
1064 # assert "Hello World!" isa String
1065 abstract class String
1066 super Text
1067
1068 redef type SELFTYPE: String is fixed
1069
1070 redef fun to_s do return self
1071
1072 # Concatenates `o` to `self`
1073 #
1074 # assert "hello" + "world" == "helloworld"
1075 # assert "" + "hello" + "" == "hello"
1076 fun +(o: Text): SELFTYPE is abstract
1077
1078 # Concatenates self `i` times
1079 #
1080 # assert "abc" * 4 == "abcabcabcabc"
1081 # assert "abc" * 1 == "abc"
1082 # assert "abc" * 0 == ""
1083 fun *(i: Int): SELFTYPE is abstract
1084
1085 # Insert `s` at `pos`.
1086 #
1087 # assert "helloworld".insert_at(" ", 5) == "hello world"
1088 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1089
1090 redef fun substrings is abstract
1091
1092 # Returns a reversed version of self
1093 #
1094 # assert "hello".reversed == "olleh"
1095 # assert "bob".reversed == "bob"
1096 # assert "".reversed == ""
1097 fun reversed: SELFTYPE is abstract
1098
1099 # A upper case version of `self`
1100 #
1101 # assert "Hello World!".to_upper == "HELLO WORLD!"
1102 fun to_upper: SELFTYPE is abstract
1103
1104 # A lower case version of `self`
1105 #
1106 # assert "Hello World!".to_lower == "hello world!"
1107 fun to_lower : SELFTYPE is abstract
1108
1109 # Takes a camel case `self` and converts it to snake case
1110 #
1111 # assert "randomMethodId".to_snake_case == "random_method_id"
1112 #
1113 # The rules are the following:
1114 #
1115 # An uppercase is always converted to a lowercase
1116 #
1117 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1118 #
1119 # An uppercase that follows a lowercase is prefixed with an underscore
1120 #
1121 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1122 #
1123 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1124 #
1125 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1126 #
1127 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1128 #
1129 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1130 fun to_snake_case: SELFTYPE
1131 do
1132 if self.is_lower then return self
1133
1134 var new_str = new Buffer.with_cap(self.length)
1135 var prev_is_lower = false
1136 var prev_is_upper = false
1137
1138 for i in [0..length[ do
1139 var char = chars[i]
1140 if char.is_lower then
1141 new_str.add(char)
1142 prev_is_lower = true
1143 prev_is_upper = false
1144 else if char.is_upper then
1145 if prev_is_lower then
1146 new_str.add('_')
1147 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1148 new_str.add('_')
1149 end
1150 new_str.add(char.to_lower)
1151 prev_is_lower = false
1152 prev_is_upper = true
1153 else
1154 new_str.add(char)
1155 prev_is_lower = false
1156 prev_is_upper = false
1157 end
1158 end
1159
1160 return new_str.to_s
1161 end
1162
1163 # Takes a snake case `self` and converts it to camel case
1164 #
1165 # assert "random_method_id".to_camel_case == "randomMethodId"
1166 #
1167 # If the identifier is prefixed by an underscore, the underscore is ignored
1168 #
1169 # assert "_private_field".to_camel_case == "_privateField"
1170 #
1171 # If `self` is upper, it is returned unchanged
1172 #
1173 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1174 #
1175 # If there are several consecutive underscores, they are considered as a single one
1176 #
1177 # assert "random__method_id".to_camel_case == "randomMethodId"
1178 fun to_camel_case: SELFTYPE
1179 do
1180 if self.is_upper then return self
1181
1182 var new_str = new Buffer
1183 var is_first_char = true
1184 var follows_us = false
1185
1186 for i in [0..length[ do
1187 var char = chars[i]
1188 if is_first_char then
1189 new_str.add(char)
1190 is_first_char = false
1191 else if char == '_' then
1192 follows_us = true
1193 else if follows_us then
1194 new_str.add(char.to_upper)
1195 follows_us = false
1196 else
1197 new_str.add(char)
1198 end
1199 end
1200
1201 return new_str.to_s
1202 end
1203
1204 # Returns a capitalized `self`
1205 #
1206 # Letters that follow a letter are lowercased
1207 # Letters that follow a non-letter are upcased.
1208 #
1209 # SEE : `Char::is_letter` for the definition of letter.
1210 #
1211 # assert "jAVASCRIPT".capitalized == "Javascript"
1212 # assert "i am root".capitalized == "I Am Root"
1213 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1214 fun capitalized: SELFTYPE do
1215 if length == 0 then return self
1216
1217 var buf = new Buffer.with_cap(length)
1218
1219 var curr = chars[0].to_upper
1220 var prev = curr
1221 buf[0] = curr
1222
1223 for i in [1 .. length[ do
1224 prev = curr
1225 curr = self[i]
1226 if prev.is_letter then
1227 buf[i] = curr.to_lower
1228 else
1229 buf[i] = curr.to_upper
1230 end
1231 end
1232
1233 return buf.to_s
1234 end
1235 end
1236
1237 # A mutable sequence of characters.
1238 abstract class Buffer
1239 super Text
1240
1241 # Returns an arbitrary subclass of `Buffer` with default parameters
1242 new is abstract
1243
1244 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1245 new with_cap(i: Int) is abstract
1246
1247 redef type SELFTYPE: Buffer is fixed
1248
1249 # Specific implementations MUST set this to `true` in order to invalidate caches
1250 protected var is_dirty = true
1251
1252 # Copy-On-Write flag
1253 #
1254 # If the `Buffer` was to_s'd, the next in-place altering
1255 # operation will cause the current `Buffer` to be re-allocated.
1256 #
1257 # The flag will then be set at `false`.
1258 protected var written = false
1259
1260 # Modifies the char contained at pos `index`
1261 #
1262 # DEPRECATED : Use self.chars.[]= instead
1263 fun []=(index: Int, item: Char) is abstract
1264
1265 # Adds a char `c` at the end of self
1266 #
1267 # DEPRECATED : Use self.chars.add instead
1268 fun add(c: Char) is abstract
1269
1270 # Clears the buffer
1271 #
1272 # var b = new Buffer
1273 # b.append "hello"
1274 # assert not b.is_empty
1275 # b.clear
1276 # assert b.is_empty
1277 fun clear is abstract
1278
1279 # Enlarges the subsequent array containing the chars of self
1280 fun enlarge(cap: Int) is abstract
1281
1282 # Adds the content of text `s` at the end of self
1283 #
1284 # var b = new Buffer
1285 # b.append "hello"
1286 # b.append "world"
1287 # assert b == "helloworld"
1288 fun append(s: Text) is abstract
1289
1290 # `self` is appended in such a way that `self` is repeated `r` times
1291 #
1292 # var b = new Buffer
1293 # b.append "hello"
1294 # b.times 3
1295 # assert b == "hellohellohello"
1296 fun times(r: Int) is abstract
1297
1298 # Reverses itself in-place
1299 #
1300 # var b = new Buffer
1301 # b.append("hello")
1302 # b.reverse
1303 # assert b == "olleh"
1304 fun reverse is abstract
1305
1306 # Changes each lower-case char in `self` by its upper-case variant
1307 #
1308 # var b = new Buffer
1309 # b.append("Hello World!")
1310 # b.upper
1311 # assert b == "HELLO WORLD!"
1312 fun upper is abstract
1313
1314 # Changes each upper-case char in `self` by its lower-case variant
1315 #
1316 # var b = new Buffer
1317 # b.append("Hello World!")
1318 # b.lower
1319 # assert b == "hello world!"
1320 fun lower is abstract
1321
1322 # Capitalizes each word in `self`
1323 #
1324 # Letters that follow a letter are lowercased
1325 # Letters that follow a non-letter are upcased.
1326 #
1327 # SEE: `Char::is_letter` for the definition of a letter.
1328 #
1329 # var b = new FlatBuffer.from("jAVAsCriPt")
1330 # b.capitalize
1331 # assert b == "Javascript"
1332 # b = new FlatBuffer.from("i am root")
1333 # b.capitalize
1334 # assert b == "I Am Root"
1335 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1336 # b.capitalize
1337 # assert b == "Ab_C -Ab0C Ab\nC"
1338 fun capitalize do
1339 if length == 0 then return
1340 var c = self[0].to_upper
1341 self[0] = c
1342 var prev = c
1343 for i in [1 .. length[ do
1344 prev = c
1345 c = self[i]
1346 if prev.is_letter then
1347 self[i] = c.to_lower
1348 else
1349 self[i] = c.to_upper
1350 end
1351 end
1352 end
1353
1354 redef fun hash
1355 do
1356 if is_dirty then hash_cache = null
1357 return super
1358 end
1359
1360 # In Buffers, the internal sequence of character is mutable
1361 # Thus, `chars` can be used to modify the buffer.
1362 redef fun chars: Sequence[Char] is abstract
1363 end
1364
1365 # View for chars on Buffer objects, extends Sequence
1366 # for mutation operations
1367 private abstract class BufferCharView
1368 super StringCharView
1369 super Sequence[Char]
1370
1371 redef type SELFTYPE: Buffer
1372
1373 end
1374
1375 # View for bytes on Buffer objects, extends Sequence
1376 # for mutation operations
1377 private abstract class BufferByteView
1378 super StringByteView
1379
1380 redef type SELFTYPE: Buffer
1381 end
1382
1383 redef class Object
1384 # User readable representation of `self`.
1385 fun to_s: String do return inspect
1386
1387 # The class name of the object in NativeString format.
1388 private fun native_class_name: NativeString is intern
1389
1390 # The class name of the object.
1391 #
1392 # assert 5.class_name == "Int"
1393 fun class_name: String do return native_class_name.to_s
1394
1395 # Developer readable representation of `self`.
1396 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1397 fun inspect: String
1398 do
1399 return "<{inspect_head}>"
1400 end
1401
1402 # Return "CLASSNAME:#OBJECTID".
1403 # This function is mainly used with the redefinition of the inspect method
1404 protected fun inspect_head: String
1405 do
1406 return "{class_name}:#{object_id.to_hex}"
1407 end
1408 end
1409
1410 redef class Bool
1411 # assert true.to_s == "true"
1412 # assert false.to_s == "false"
1413 redef fun to_s
1414 do
1415 if self then
1416 return once "true"
1417 else
1418 return once "false"
1419 end
1420 end
1421 end
1422
1423 redef class Byte
1424 # C function to calculate the length of the `NativeString` to receive `self`
1425 private fun byte_to_s_len: Int `{
1426 return snprintf(NULL, 0, "0x%02x", self);
1427 `}
1428
1429 # C function to convert an nit Int to a NativeString (char*)
1430 private fun native_byte_to_s(nstr: NativeString, strlen: Int) `{
1431 snprintf(nstr, strlen, "0x%02x", self);
1432 `}
1433
1434 # Displayable byte in its hexadecimal form (0x..)
1435 #
1436 # assert 1.to_b.to_s == "0x01"
1437 # assert (-123).to_b.to_s == "0x85"
1438 redef fun to_s do
1439 var nslen = byte_to_s_len
1440 var ns = new NativeString(nslen + 1)
1441 ns[nslen] = 0u8
1442 native_byte_to_s(ns, nslen + 1)
1443 return ns.to_s_with_length(nslen)
1444 end
1445 end
1446
1447 redef class Int
1448
1449 # Wrapper of strerror C function
1450 private fun strerror_ext: NativeString `{ return strerror(self); `}
1451
1452 # Returns a string describing error number
1453 fun strerror: String do return strerror_ext.to_s
1454
1455 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1456 # assume < to_c max const of char
1457 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1458 do
1459 var n: Int
1460 # Sign
1461 if self < 0 then
1462 n = - self
1463 s.chars[0] = '-'
1464 else if self == 0 then
1465 s.chars[0] = '0'
1466 return
1467 else
1468 n = self
1469 end
1470 # Fill digits
1471 var pos = digit_count(base) - 1
1472 while pos >= 0 and n > 0 do
1473 s.chars[pos] = (n % base).to_c
1474 n = n / base # /
1475 pos -= 1
1476 end
1477 end
1478
1479 # C function to calculate the length of the `NativeString` to receive `self`
1480 private fun int_to_s_len: Int `{
1481 return snprintf(NULL, 0, "%ld", self);
1482 `}
1483
1484 # C function to convert an nit Int to a NativeString (char*)
1485 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1486 snprintf(nstr, strlen, "%ld", self);
1487 `}
1488
1489 # return displayable int in base base and signed
1490 fun to_base(base: Int, signed: Bool): String is abstract
1491
1492 # return displayable int in hexadecimal
1493 #
1494 # assert 1.to_hex == "1"
1495 # assert (-255).to_hex == "-ff"
1496 fun to_hex: String do return to_base(16,false)
1497 end
1498
1499 redef class Float
1500 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1501 #
1502 # assert 12.34.to_s == "12.34"
1503 # assert (-0120.030).to_s == "-120.03"
1504 #
1505 # see `to_precision` for a custom precision.
1506 redef fun to_s do
1507 var str = to_precision( 3 )
1508 if is_inf != 0 or is_nan then return str
1509 var len = str.length
1510 for i in [0..len-1] do
1511 var j = len-1-i
1512 var c = str.chars[j]
1513 if c == '0' then
1514 continue
1515 else if c == '.' then
1516 return str.substring( 0, j+2 )
1517 else
1518 return str.substring( 0, j+1 )
1519 end
1520 end
1521 return str
1522 end
1523
1524 # `String` representation of `self` with the given number of `decimals`
1525 #
1526 # assert 12.345.to_precision(0) == "12"
1527 # assert 12.345.to_precision(3) == "12.345"
1528 # assert (-12.345).to_precision(3) == "-12.345"
1529 # assert (-0.123).to_precision(3) == "-0.123"
1530 # assert 0.999.to_precision(2) == "1.00"
1531 # assert 0.999.to_precision(4) == "0.9990"
1532 fun to_precision(decimals: Int): String
1533 do
1534 if is_nan then return "nan"
1535
1536 var isinf = self.is_inf
1537 if isinf == 1 then
1538 return "inf"
1539 else if isinf == -1 then
1540 return "-inf"
1541 end
1542
1543 if decimals == 0 then return self.to_i.to_s
1544 var f = self
1545 for i in [0..decimals[ do f = f * 10.0
1546 if self > 0.0 then
1547 f = f + 0.5
1548 else
1549 f = f - 0.5
1550 end
1551 var i = f.to_i
1552 if i == 0 then return "0." + "0"*decimals
1553
1554 # Prepare both parts of the float, before and after the "."
1555 var s = i.abs.to_s
1556 var sl = s.length
1557 var p1
1558 var p2
1559 if sl > decimals then
1560 # Has something before the "."
1561 p1 = s.substring(0, sl-decimals)
1562 p2 = s.substring(sl-decimals, decimals)
1563 else
1564 p1 = "0"
1565 p2 = "0"*(decimals-sl) + s
1566 end
1567
1568 if i < 0 then p1 = "-" + p1
1569
1570 return p1 + "." + p2
1571 end
1572 end
1573
1574 redef class Char
1575
1576 # Returns a sequence with the UTF-8 bytes of `self`
1577 #
1578 # assert 'a'.bytes == [0x61u8]
1579 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1580 fun bytes: SequenceRead[Byte] do return to_s.bytes
1581
1582 # Length of `self` in a UTF-8 String
1583 private fun u8char_len: Int do
1584 var c = self.code_point
1585 if c < 0x80 then return 1
1586 if c <= 0x7FF then return 2
1587 if c <= 0xFFFF then return 3
1588 if c <= 0x10FFFF then return 4
1589 # Bad character format
1590 return 1
1591 end
1592
1593 # assert 'x'.to_s == "x"
1594 redef fun to_s do
1595 var ln = u8char_len
1596 var ns = new NativeString(ln + 1)
1597 u8char_tos(ns, ln)
1598 return ns.to_s_with_length(ln)
1599 end
1600
1601 private fun u8char_tos(r: NativeString, len: Int) `{
1602 r[len] = '\0';
1603 switch(len){
1604 case 1:
1605 r[0] = self;
1606 break;
1607 case 2:
1608 r[0] = 0xC0 | ((self & 0x7C0) >> 6);
1609 r[1] = 0x80 | (self & 0x3F);
1610 break;
1611 case 3:
1612 r[0] = 0xE0 | ((self & 0xF000) >> 12);
1613 r[1] = 0x80 | ((self & 0xFC0) >> 6);
1614 r[2] = 0x80 | (self & 0x3F);
1615 break;
1616 case 4:
1617 r[0] = 0xF0 | ((self & 0x1C0000) >> 18);
1618 r[1] = 0x80 | ((self & 0x3F000) >> 12);
1619 r[2] = 0x80 | ((self & 0xFC0) >> 6);
1620 r[3] = 0x80 | (self & 0x3F);
1621 break;
1622 }
1623 `}
1624
1625 # Returns true if the char is a numerical digit
1626 #
1627 # assert '0'.is_numeric
1628 # assert '9'.is_numeric
1629 # assert not 'a'.is_numeric
1630 # assert not '?'.is_numeric
1631 #
1632 # FIXME: Works on ASCII-range only
1633 fun is_numeric: Bool
1634 do
1635 return self >= '0' and self <= '9'
1636 end
1637
1638 # Returns true if the char is an alpha digit
1639 #
1640 # assert 'a'.is_alpha
1641 # assert 'Z'.is_alpha
1642 # assert not '0'.is_alpha
1643 # assert not '?'.is_alpha
1644 #
1645 # FIXME: Works on ASCII-range only
1646 fun is_alpha: Bool
1647 do
1648 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1649 end
1650
1651 # Returns true if the char is an alpha or a numeric digit
1652 #
1653 # assert 'a'.is_alphanumeric
1654 # assert 'Z'.is_alphanumeric
1655 # assert '0'.is_alphanumeric
1656 # assert '9'.is_alphanumeric
1657 # assert not '?'.is_alphanumeric
1658 #
1659 # FIXME: Works on ASCII-range only
1660 fun is_alphanumeric: Bool
1661 do
1662 return self.is_numeric or self.is_alpha
1663 end
1664 end
1665
1666 redef class Collection[E]
1667 # String representation of the content of the collection.
1668 #
1669 # The standard representation is the list of elements separated with commas.
1670 #
1671 # ~~~
1672 # assert [1,2,3].to_s == "[1,2,3]"
1673 # assert [1..3].to_s == "[1,2,3]"
1674 # assert (new Array[Int]).to_s == "[]" # empty collection
1675 # ~~~
1676 #
1677 # Subclasses may return a more specific string representation.
1678 redef fun to_s
1679 do
1680 return "[" + join(",") + "]"
1681 end
1682
1683 # Concatenate elements without separators
1684 #
1685 # ~~~
1686 # assert [1,2,3].plain_to_s == "123"
1687 # assert [11..13].plain_to_s == "111213"
1688 # assert (new Array[Int]).plain_to_s == "" # empty collection
1689 # ~~~
1690 fun plain_to_s: String
1691 do
1692 var s = new Buffer
1693 for e in self do if e != null then s.append(e.to_s)
1694 return s.to_s
1695 end
1696
1697 # Concatenate and separate each elements with `separator`.
1698 #
1699 # Only concatenate if `separator == null`.
1700 #
1701 # assert [1, 2, 3].join(":") == "1:2:3"
1702 # assert [1..3].join(":") == "1:2:3"
1703 # assert [1..3].join == "123"
1704 fun join(separator: nullable Text): String
1705 do
1706 if is_empty then return ""
1707
1708 var s = new Buffer # Result
1709
1710 # Concat first item
1711 var i = iterator
1712 var e = i.item
1713 if e != null then s.append(e.to_s)
1714
1715 # Concat other items
1716 i.next
1717 while i.is_ok do
1718 if separator != null then s.append(separator)
1719 e = i.item
1720 if e != null then s.append(e.to_s)
1721 i.next
1722 end
1723 return s.to_s
1724 end
1725 end
1726
1727 redef class Map[K,V]
1728 # Concatenate couples of key value.
1729 # Key and value are separated by `couple_sep`.
1730 # Couples are separated by `sep`.
1731 #
1732 # var m = new HashMap[Int, String]
1733 # m[1] = "one"
1734 # m[10] = "ten"
1735 # assert m.join("; ", "=") == "1=one; 10=ten"
1736 fun join(sep, couple_sep: String): String is abstract
1737 end
1738
1739 redef class Sys
1740 private var args_cache: nullable Sequence[String] = null
1741
1742 # The arguments of the program as given by the OS
1743 fun program_args: Sequence[String]
1744 do
1745 if _args_cache == null then init_args
1746 return _args_cache.as(not null)
1747 end
1748
1749 # The name of the program as given by the OS
1750 fun program_name: String
1751 do
1752 return native_argv(0).to_s
1753 end
1754
1755 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1756 private fun init_args
1757 do
1758 var argc = native_argc
1759 var args = new Array[String].with_capacity(0)
1760 var i = 1
1761 while i < argc do
1762 args[i-1] = native_argv(i).to_s
1763 i += 1
1764 end
1765 _args_cache = args
1766 end
1767
1768 # First argument of the main C function.
1769 private fun native_argc: Int is intern
1770
1771 # Second argument of the main C function.
1772 private fun native_argv(i: Int): NativeString is intern
1773 end
1774
1775 # Comparator that efficienlty use `to_s` to compare things
1776 #
1777 # The comparaison call `to_s` on object and use the result to order things.
1778 #
1779 # var a = [1, 2, 3, 10, 20]
1780 # (new CachedAlphaComparator).sort(a)
1781 # assert a == [1, 10, 2, 20, 3]
1782 #
1783 # Internally the result of `to_s` is cached in a HashMap to counter
1784 # uneficient implementation of `to_s`.
1785 #
1786 # Note: it caching is not usefull, see `alpha_comparator`
1787 class CachedAlphaComparator
1788 super Comparator
1789 redef type COMPARED: Object
1790
1791 private var cache = new HashMap[Object, String]
1792
1793 private fun do_to_s(a: Object): String do
1794 if cache.has_key(a) then return cache[a]
1795 var res = a.to_s
1796 cache[a] = res
1797 return res
1798 end
1799
1800 redef fun compare(a, b) do
1801 return do_to_s(a) <=> do_to_s(b)
1802 end
1803 end
1804
1805 # see `alpha_comparator`
1806 private class AlphaComparator
1807 super Comparator
1808 redef fun compare(a, b) do return a.to_s <=> b.to_s
1809 end
1810
1811 # Stateless comparator that naively use `to_s` to compare things.
1812 #
1813 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1814 # on a single instace. See `CachedAlphaComparator` as an alternative.
1815 #
1816 # var a = [1, 2, 3, 10, 20]
1817 # alpha_comparator.sort(a)
1818 # assert a == [1, 10, 2, 20, 3]
1819 fun alpha_comparator: Comparator do return once new AlphaComparator
1820
1821 # The arguments of the program as given by the OS
1822 fun args: Sequence[String]
1823 do
1824 return sys.program_args
1825 end
1826
1827 redef class NativeString
1828 # Returns `self` as a new String.
1829 fun to_s_with_copy: String is abstract
1830
1831 # Returns `self` as a String of `length`.
1832 fun to_s_with_length(length: Int): String is abstract
1833
1834 # Returns `self` as a String with `bytelen` and `length` set
1835 #
1836 # SEE: `abstract_text::Text` for more infos on the difference
1837 # between `Text::bytelen` and `Text::length`
1838 fun to_s_full(bytelen, unilen: Int): String is abstract
1839 end
1840
1841 redef class NativeArray[E]
1842 # Join all the elements using `to_s`
1843 #
1844 # REQUIRE: `self isa NativeArray[String]`
1845 # REQUIRE: all elements are initialized
1846 fun native_to_s: String is abstract
1847 end