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