2ac2ca4b462754e1dc4bc618cb3ed35e47d020f0
[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".byte_length == 5
54 # assert "あいうえお".byte_length == 15
55 fun byte_length: 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 `"` `\` `'`, trigraphs 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 # assert "allo???!".escape_to_c == "allo??\\?!"
598 # assert "??=??/??'??(??)".escape_to_c == "?\\?=?\\?/??\\'?\\?(?\\?)"
599 # assert "??!??<??>??-".escape_to_c == "?\\?!?\\?<?\\?>?\\?-"
600 #
601 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
602 # Three digits are always used to avoid following digits to be interpreted as an element
603 # of the octal sequence.
604 #
605 # assert "{0.code_point}{1.code_point}{8.code_point}{31.code_point}{32.code_point}".escape_to_c == "\\000\\001\\010\\037 "
606 #
607 # The exceptions are the common `\t` and `\n`.
608 fun escape_to_c: String
609 do
610 var b = new Buffer
611 for i in [0..length[ do
612 var c = chars[i]
613 if c == '\n' then
614 b.append("\\n")
615 else if c == '\t' then
616 b.append("\\t")
617 else if c == '"' then
618 b.append("\\\"")
619 else if c == '\'' then
620 b.append("\\\'")
621 else if c == '\\' then
622 b.append("\\\\")
623 else if c == '?' then
624 # Escape if it is the last question mark of a ANSI C trigraph.
625 var j = i + 1
626 if j < length then
627 var next = chars[j]
628 # We ignore `??'` because it will be escaped as `??\'`.
629 if
630 next == '!' or
631 next == '(' or
632 next == ')' or
633 next == '-' or
634 next == '/' or
635 next == '<' or
636 next == '=' or
637 next == '>'
638 then b.add('\\')
639 end
640 b.add('?')
641 else if c.code_point < 32 then
642 b.add('\\')
643 var oct = c.code_point.to_base(8)
644 # Force 3 octal digits since it is the
645 # maximum allowed in the C specification
646 if oct.length == 1 then
647 b.add('0')
648 b.add('0')
649 else if oct.length == 2 then
650 b.add('0')
651 end
652 b.append(oct)
653 else
654 b.add(c)
655 end
656 end
657 return b.to_s
658 end
659
660 # Escape additionnal characters
661 # The result might no be legal in C but be used in other languages
662 #
663 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
664 # assert "allo???!".escape_more_to_c("") == "allo??\\?!"
665 fun escape_more_to_c(chars: String): String
666 do
667 var b = new Buffer
668 for c in escape_to_c.chars do
669 if chars.chars.has(c) then
670 b.add('\\')
671 end
672 b.add(c)
673 end
674 return b.to_s
675 end
676
677 # Escape to C plus braces
678 #
679 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
680 fun escape_to_nit: String do return escape_more_to_c("\{\}")
681
682 # Escape to POSIX Shell (sh).
683 #
684 # Abort if the text contains a null byte.
685 #
686 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
687 fun escape_to_sh: String do
688 var b = new Buffer
689 b.chars.add '\''
690 for i in [0..length[ do
691 var c = chars[i]
692 if c == '\'' then
693 b.append("'\\''")
694 else
695 assert without_null_byte: c != '\0'
696 b.add(c)
697 end
698 end
699 b.chars.add '\''
700 return b.to_s
701 end
702
703 # Escape to include in a Makefile
704 #
705 # Unfortunately, some characters are not escapable in Makefile.
706 # These characters are `;`, `|`, `\`, and the non-printable ones.
707 # They will be rendered as `"?{hex}"`.
708 fun escape_to_mk: String do
709 var b = new Buffer
710 for i in [0..length[ do
711 var c = chars[i]
712 if c == '$' then
713 b.append("$$")
714 else if c == ':' or c == ' ' or c == '#' then
715 b.add('\\')
716 b.add(c)
717 else if c.code_point < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
718 b.append("?{c.code_point.to_base(16)}")
719 else
720 b.add(c)
721 end
722 end
723 return b.to_s
724 end
725
726 # Return a string where Nit escape sequences are transformed.
727 #
728 # var s = "\\n"
729 # assert s.length == 2
730 # var u = s.unescape_nit
731 # assert u.length == 1
732 # assert u.chars[0].code_point == 10 # (the ASCII value of the "new line" character)
733 fun unescape_nit: String
734 do
735 var res = new Buffer.with_cap(self.length)
736 var was_slash = false
737 for i in [0..length[ do
738 var c = chars[i]
739 if not was_slash then
740 if c == '\\' then
741 was_slash = true
742 else
743 res.add(c)
744 end
745 continue
746 end
747 was_slash = false
748 if c == 'n' then
749 res.add('\n')
750 else if c == 'r' then
751 res.add('\r')
752 else if c == 't' then
753 res.add('\t')
754 else if c == '0' then
755 res.add('\0')
756 else
757 res.add(c)
758 end
759 end
760 return res.to_s
761 end
762
763 # Returns `self` with all characters escaped with their UTF-16 representation
764 #
765 # assert "Aèあ𐏓".escape_to_utf16 == "\\u0041\\u00e8\\u3042\\ud800\\udfd3"
766 fun escape_to_utf16: String do
767 var buf = new Buffer
768 for i in chars do buf.append i.escape_to_utf16
769 return buf.to_s
770 end
771
772 # Returns the Unicode char escaped by `self`
773 #
774 # assert "\\u0041".from_utf16_escape == 'A'
775 # assert "\\ud800\\udfd3".from_utf16_escape == '𐏓'
776 # assert "\\u00e8".from_utf16_escape == 'è'
777 # assert "\\u3042".from_utf16_escape == 'あ'
778 fun from_utf16_escape(pos, ln: nullable Int): Char do
779 if pos == null then pos = 0
780 if ln == null then ln = length - pos
781 if ln < 6 then return 0xFFFD.code_point
782 var cp = from_utf16_digit(pos + 2)
783 if cp < 0xD800 then return cp.code_point
784 if cp > 0xDFFF then return cp.code_point
785 if cp > 0xDBFF then return 0xFFFD.code_point
786 if ln == 6 then return 0xFFFD.code_point
787 if ln < 12 then return 0xFFFD.code_point
788 cp <<= 16
789 cp += from_utf16_digit(pos + 8)
790 var cplo = cp & 0xFFFF
791 if cplo < 0xDC00 then return 0xFFFD.code_point
792 if cplo > 0xDFFF then return 0xFFFD.code_point
793 return cp.from_utf16_surr.code_point
794 end
795
796 # Returns a UTF-16 escape value
797 #
798 # var s = "\\ud800\\udfd3"
799 # assert s.from_utf16_digit(2) == 0xD800
800 # assert s.from_utf16_digit(8) == 0xDFD3
801 fun from_utf16_digit(pos: nullable Int): Int do
802 if pos == null then pos = 0
803 return to_hex(pos, 4)
804 end
805
806 # Encode `self` to percent (or URL) encoding
807 #
808 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
809 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
810 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
811 # assert "éあいう".to_percent_encoding == "%c3%a9%e3%81%82%e3%81%84%e3%81%86"
812 fun to_percent_encoding: String
813 do
814 var buf = new Buffer
815
816 for i in [0..length[ do
817 var c = chars[i]
818 if (c >= '0' and c <= '9') or
819 (c >= 'a' and c <= 'z') or
820 (c >= 'A' and c <= 'Z') or
821 c == '-' or c == '.' or
822 c == '_' or c == '~'
823 then
824 buf.add c
825 else
826 var bytes = c.to_s.bytes
827 for b in bytes do buf.append "%{b.to_i.to_hex}"
828 end
829 end
830
831 return buf.to_s
832 end
833
834 # Decode `self` from percent (or URL) encoding to a clear string
835 #
836 # Replace invalid use of '%' with '?'.
837 #
838 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
839 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
840 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
841 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
842 # assert "incomplete %".from_percent_encoding == "incomplete ?"
843 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
844 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".from_percent_encoding == "éあいう"
845 fun from_percent_encoding: String
846 do
847 var len = byte_length
848 var has_percent = false
849 for c in chars do
850 if c == '%' then
851 len -= 2
852 has_percent = true
853 end
854 end
855
856 # If no transformation is needed, return self as a string
857 if not has_percent then return to_s
858
859 var buf = new NativeString(len)
860 var i = 0
861 var l = 0
862 while i < length do
863 var c = chars[i]
864 if c == '%' then
865 if i + 2 >= length then
866 # What follows % has been cut off
867 buf[l] = '?'.ascii
868 else
869 i += 1
870 var hex_s = substring(i, 2)
871 if hex_s.is_hex then
872 var hex_i = hex_s.to_hex
873 buf[l] = hex_i.to_b
874 i += 1
875 else
876 # What follows a % is not Hex
877 buf[l] = '?'.ascii
878 i -= 1
879 end
880 end
881 else buf[l] = c.ascii
882
883 i += 1
884 l += 1
885 end
886
887 return buf.to_s_unsafe(l)
888 end
889
890 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
891 #
892 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
893 #
894 # 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>
895 fun html_escape: String
896 do
897 var buf = new Buffer
898
899 for i in [0..length[ do
900 var c = chars[i]
901 if c == '&' then
902 buf.append "&amp;"
903 else if c == '<' then
904 buf.append "&lt;"
905 else if c == '>' then
906 buf.append "&gt;"
907 else if c == '"' then
908 buf.append "&#34;"
909 else if c == '\'' then
910 buf.append "&#39;"
911 else if c == '/' then
912 buf.append "&#47;"
913 else buf.add c
914 end
915
916 return buf.to_s
917 end
918
919 # Equality of text
920 # Two pieces of text are equals if thez have the same characters in the same order.
921 #
922 # assert "hello" == "hello"
923 # assert "hello" != "HELLO"
924 # assert "hello" == "hel"+"lo"
925 #
926 # Things that are not Text are not equal.
927 #
928 # assert "9" != '9'
929 # assert "9" != ['9']
930 # assert "9" != 9
931 #
932 # assert "9".chars.first == '9' # equality of Char
933 # assert "9".chars == ['9'] # equality of Sequence
934 # assert "9".to_i == 9 # equality of Int
935 redef fun ==(o)
936 do
937 if o == null then return false
938 if not o isa Text then return false
939 if self.is_same_instance(o) then return true
940 if self.length != o.length then return false
941 return self.chars == o.chars
942 end
943
944 # Lexicographical comparaison
945 #
946 # assert "abc" < "xy"
947 # assert "ABC" < "abc"
948 redef fun <(other)
949 do
950 var self_chars = self.chars.iterator
951 var other_chars = other.chars.iterator
952
953 while self_chars.is_ok and other_chars.is_ok do
954 if self_chars.item < other_chars.item then return true
955 if self_chars.item > other_chars.item then return false
956 self_chars.next
957 other_chars.next
958 end
959
960 if self_chars.is_ok then
961 return false
962 else
963 return true
964 end
965 end
966
967 # Escape string used in labels for graphviz
968 #
969 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
970 fun escape_to_dot: String
971 do
972 return escape_more_to_c("|\{\}<>")
973 end
974
975 private var hash_cache: nullable Int = null
976
977 redef fun hash
978 do
979 if hash_cache == null then
980 # djb2 hash algorithm
981 var h = 5381
982
983 for i in [0..length[ do
984 var char = chars[i]
985 h = (h << 5) + h + char.code_point
986 end
987
988 hash_cache = h
989 end
990 return hash_cache.as(not null)
991 end
992
993 # Format `self` by replacing each `%n` with the `n`th item of `args`
994 #
995 # The character `%` followed by something other than a number are left as is.
996 # To represent a `%` followed by a number, double the `%`, as in `%%7`.
997 #
998 # assert "This %0 is a %1.".format("String", "formatted String") == "This String is a formatted String."
999 # assert "Do not escape % nor %%1".format("unused") == "Do not escape % nor %1"
1000 fun format(args: Object...): String do
1001 var s = new Array[Text]
1002 var curr_st = 0
1003 var i = 0
1004 while i < length do
1005 if self[i] == '%' then
1006 var fmt_st = i
1007 i += 1
1008 var ciph_st = i
1009 while i < length and self[i].is_numeric do
1010 i += 1
1011 end
1012
1013 var ciph_len = i - ciph_st
1014 if ciph_len == 0 then
1015 # What follows '%' is not a number.
1016 s.push substring(curr_st, i - curr_st)
1017 if i < length and self[i] == '%' then
1018 # Skip the next `%`
1019 i += 1
1020 end
1021 curr_st = i
1022 continue
1023 end
1024
1025 var arg_index = substring(ciph_st, ciph_len).to_i
1026 if arg_index >= args.length then continue
1027
1028 s.push substring(curr_st, fmt_st - curr_st)
1029 s.push args[arg_index].to_s
1030
1031 curr_st = i
1032 i -= 1
1033 end
1034 i += 1
1035 end
1036 s.push substring(curr_st, length - curr_st)
1037 return s.plain_to_s
1038 end
1039
1040 # Return the Levenshtein distance between two strings
1041 #
1042 # ~~~
1043 # assert "abcd".levenshtein_distance("abcd") == 0
1044 # assert "".levenshtein_distance("abcd") == 4
1045 # assert "abcd".levenshtein_distance("") == 4
1046 # assert "abcd".levenshtein_distance("xyz") == 4
1047 # assert "abcd".levenshtein_distance("xbdy") == 3
1048 # ~~~
1049 fun levenshtein_distance(other: String): Int
1050 do
1051 var slen = self.length
1052 var olen = other.length
1053
1054 # fast cases
1055 if slen == 0 then return olen
1056 if olen == 0 then return slen
1057 if self == other then return 0
1058
1059 # previous row of distances
1060 var v0 = new Array[Int].with_capacity(olen+1)
1061
1062 # current row of distances
1063 var v1 = new Array[Int].with_capacity(olen+1)
1064
1065 for j in [0..olen] do
1066 # prefix insert cost
1067 v0[j] = j
1068 end
1069
1070 for i in [0..slen[ do
1071
1072 # prefix delete cost
1073 v1[0] = i + 1
1074
1075 for j in [0..olen[ do
1076 # delete cost
1077 var cost1 = v1[j] + 1
1078 # insert cost
1079 var cost2 = v0[j + 1] + 1
1080 # same char cost (+0)
1081 var cost3 = v0[j]
1082 # change cost
1083 if self[i] != other[j] then cost3 += 1
1084 # keep the min
1085 v1[j+1] = cost1.min(cost2).min(cost3)
1086 end
1087
1088 # Switch columns:
1089 # * v1 become v0 in the next iteration
1090 # * old v0 is reused as the new v1
1091 var tmp = v1
1092 v1 = v0
1093 v0 = tmp
1094 end
1095
1096 return v0[olen]
1097 end
1098
1099 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
1100 #
1101 # Basically a high-level synonym of NativeString::copy_to
1102 #
1103 # REQUIRE: `n` must be large enough to contain `len` bytes
1104 #
1105 # var ns = new NativeString(8)
1106 # "Text is String".copy_to_native(ns, 8, 2, 0)
1107 # assert ns.to_s_unsafe(8) == "xt is St"
1108 #
1109 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
1110 var mypos = src_offset
1111 var itspos = dest_offset
1112 while n > 0 do
1113 dest[itspos] = self.bytes[mypos]
1114 itspos += 1
1115 mypos += 1
1116 n -= 1
1117 end
1118 end
1119
1120 # Packs the content of a string in packs of `ln` chars.
1121 # This variant ensures that only the last element might be smaller than `ln`
1122 #
1123 # ~~~nit
1124 # var s = "abcdefghijklmnopqrstuvwxyz"
1125 # assert s.pack_l(4) == ["abcd","efgh","ijkl","mnop","qrst","uvwx","yz"]
1126 # ~~~
1127 fun pack_l(ln: Int): Array[Text] do
1128 var st = 0
1129 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1130 while st < length do
1131 retarr.add(substring(st, ln))
1132 st += ln
1133 end
1134 return retarr
1135 end
1136
1137 # Packs the content of a string in packs of `ln` chars.
1138 # This variant ensures that only the first element might be smaller than `ln`
1139 #
1140 # ~~~nit
1141 # var s = "abcdefghijklmnopqrstuvwxyz"
1142 # assert s.pack_r(4) == ["ab","cdef","ghij","klmn","opqr","stuv","wxyz"]
1143 # ~~~
1144 fun pack_r(ln: Int): Array[Text] do
1145 var st = length
1146 var retarr = new Array[Text].with_capacity(length / ln + length % ln)
1147 while st >= 0 do
1148 retarr.add(substring(st - ln, ln))
1149 st -= ln
1150 end
1151 return retarr.reversed
1152 end
1153 end
1154
1155 # All kinds of array-based text representations.
1156 abstract class FlatText
1157 super Text
1158
1159 # Underlying C-String (`char*`)
1160 #
1161 # Warning : Might be void in some subclasses, be sure to check
1162 # if set before using it.
1163 var items: NativeString is noinit
1164
1165 # Returns a char* starting at position `first_byte`
1166 #
1167 # WARNING: If you choose to use this service, be careful of the following.
1168 #
1169 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
1170 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
1171 # deallocated at any moment, rendering the pointer returned by this function invalid.
1172 # Any access to freed memory may very likely cause undefined behaviour or a crash.
1173 # (Failure to do so will most certainly result in long and painful debugging hours)
1174 #
1175 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
1176 # then immediately return).
1177 #
1178 # As always, do not modify the content of the String in C code, if this is what you want
1179 # copy locally the char* as Nit Strings are immutable.
1180 fun fast_cstring: NativeString is abstract
1181
1182 redef var length = 0
1183
1184 redef var byte_length = 0
1185
1186 redef fun output
1187 do
1188 var i = 0
1189 while i < length do
1190 items[i].output
1191 i += 1
1192 end
1193 end
1194
1195 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
1196 items.copy_to(dest, n, src_offset, dest_offset)
1197 end
1198 end
1199
1200 # Abstract class for the SequenceRead compatible
1201 # views on the chars of any Text
1202 private abstract class StringCharView
1203 super SequenceRead[Char]
1204
1205 type SELFTYPE: Text
1206
1207 var target: SELFTYPE
1208
1209 redef fun is_empty do return target.is_empty
1210
1211 redef fun length do return target.length
1212
1213 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
1214
1215 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
1216 end
1217
1218 # Abstract class for the SequenceRead compatible
1219 # views on the bytes of any Text
1220 private abstract class StringByteView
1221 super SequenceRead[Byte]
1222
1223 type SELFTYPE: Text
1224
1225 var target: SELFTYPE
1226
1227 redef fun is_empty do return target.is_empty
1228
1229 redef fun length do return target.byte_length
1230
1231 redef fun iterator do return self.iterator_from(0)
1232
1233 redef fun reverse_iterator do return self.reverse_iterator_from(target.byte_length - 1)
1234 end
1235
1236 # Immutable sequence of characters.
1237 #
1238 # String objects may be created using literals.
1239 #
1240 # assert "Hello World!" isa String
1241 abstract class String
1242 super Text
1243
1244 redef type SELFTYPE: String is fixed
1245
1246 redef fun to_s do return self
1247
1248 # Concatenates `o` to `self`
1249 #
1250 # assert "hello" + "world" == "helloworld"
1251 # assert "" + "hello" + "" == "hello"
1252 fun +(o: Text): SELFTYPE is abstract
1253
1254 # Concatenates self `i` times
1255 #
1256 # assert "abc" * 4 == "abcabcabcabc"
1257 # assert "abc" * 1 == "abc"
1258 # assert "abc" * 0 == ""
1259 fun *(i: Int): SELFTYPE is abstract
1260
1261 # Insert `s` at `pos`.
1262 #
1263 # assert "helloworld".insert_at(" ", 5) == "hello world"
1264 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1265
1266 redef fun substrings is abstract
1267
1268 # Returns a reversed version of self
1269 #
1270 # assert "hello".reversed == "olleh"
1271 # assert "bob".reversed == "bob"
1272 # assert "".reversed == ""
1273 fun reversed: SELFTYPE is abstract
1274
1275 # A upper case version of `self`
1276 #
1277 # assert "Hello World!".to_upper == "HELLO WORLD!"
1278 fun to_upper: SELFTYPE is abstract
1279
1280 # A lower case version of `self`
1281 #
1282 # assert "Hello World!".to_lower == "hello world!"
1283 fun to_lower : SELFTYPE is abstract
1284
1285 # Takes a camel case `self` and converts it to snake case
1286 #
1287 # assert "randomMethodId".to_snake_case == "random_method_id"
1288 #
1289 # The rules are the following:
1290 #
1291 # An uppercase is always converted to a lowercase
1292 #
1293 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1294 #
1295 # An uppercase that follows a lowercase is prefixed with an underscore
1296 #
1297 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1298 #
1299 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1300 #
1301 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1302 #
1303 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1304 #
1305 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1306 fun to_snake_case: SELFTYPE
1307 do
1308 if self.is_lower then return self
1309
1310 var new_str = new Buffer.with_cap(self.length)
1311 var prev_is_lower = false
1312 var prev_is_upper = false
1313
1314 for i in [0..length[ do
1315 var char = chars[i]
1316 if char.is_lower then
1317 new_str.add(char)
1318 prev_is_lower = true
1319 prev_is_upper = false
1320 else if char.is_upper then
1321 if prev_is_lower then
1322 new_str.add('_')
1323 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1324 new_str.add('_')
1325 end
1326 new_str.add(char.to_lower)
1327 prev_is_lower = false
1328 prev_is_upper = true
1329 else
1330 new_str.add(char)
1331 prev_is_lower = false
1332 prev_is_upper = false
1333 end
1334 end
1335
1336 return new_str.to_s
1337 end
1338
1339 # Takes a snake case `self` and converts it to camel case
1340 #
1341 # assert "random_method_id".to_camel_case == "randomMethodId"
1342 #
1343 # If the identifier is prefixed by an underscore, the underscore is ignored
1344 #
1345 # assert "_private_field".to_camel_case == "_privateField"
1346 #
1347 # If `self` is upper, it is returned unchanged
1348 #
1349 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1350 #
1351 # If there are several consecutive underscores, they are considered as a single one
1352 #
1353 # assert "random__method_id".to_camel_case == "randomMethodId"
1354 fun to_camel_case: SELFTYPE
1355 do
1356 if self.is_upper then return self
1357
1358 var new_str = new Buffer
1359 var is_first_char = true
1360 var follows_us = false
1361
1362 for i in [0..length[ do
1363 var char = chars[i]
1364 if is_first_char then
1365 new_str.add(char)
1366 is_first_char = false
1367 else if char == '_' then
1368 follows_us = true
1369 else if follows_us then
1370 new_str.add(char.to_upper)
1371 follows_us = false
1372 else
1373 new_str.add(char)
1374 end
1375 end
1376
1377 return new_str.to_s
1378 end
1379
1380 # Returns a capitalized `self`
1381 #
1382 # Letters that follow a letter are lowercased
1383 # Letters that follow a non-letter are upcased.
1384 #
1385 # If `keep_upper = true`, already uppercase letters are not lowercased.
1386 #
1387 # SEE : `Char::is_letter` for the definition of letter.
1388 #
1389 # assert "jAVASCRIPT".capitalized == "Javascript"
1390 # assert "i am root".capitalized == "I Am Root"
1391 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1392 # assert "preserve my ACRONYMS".capitalized(keep_upper=true) == "Preserve My ACRONYMS"
1393 fun capitalized(keep_upper: nullable Bool): SELFTYPE do
1394 if length == 0 then return self
1395
1396 var buf = new Buffer.with_cap(length)
1397 buf.capitalize(keep_upper=keep_upper, src=self)
1398 return buf.to_s
1399 end
1400 end
1401
1402 # A mutable sequence of characters.
1403 abstract class Buffer
1404 super Text
1405
1406 # Returns an arbitrary subclass of `Buffer` with default parameters
1407 new is abstract
1408
1409 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1410 new with_cap(i: Int) is abstract
1411
1412 redef type SELFTYPE: Buffer is fixed
1413
1414 # Copy-On-Write flag
1415 #
1416 # If the `Buffer` was to_s'd, the next in-place altering
1417 # operation will cause the current `Buffer` to be re-allocated.
1418 #
1419 # The flag will then be set at `false`.
1420 protected var written = false
1421
1422 # Modifies the char contained at pos `index`
1423 #
1424 # DEPRECATED : Use self.chars.[]= instead
1425 fun []=(index: Int, item: Char) is abstract
1426
1427 # Adds a char `c` at the end of self
1428 #
1429 # DEPRECATED : Use self.chars.add instead
1430 fun add(c: Char) is abstract
1431
1432 # Clears the buffer
1433 #
1434 # var b = new Buffer
1435 # b.append "hello"
1436 # assert not b.is_empty
1437 # b.clear
1438 # assert b.is_empty
1439 fun clear is abstract
1440
1441 # Enlarges the subsequent array containing the chars of self
1442 fun enlarge(cap: Int) is abstract
1443
1444 # Adds the content of text `s` at the end of self
1445 #
1446 # var b = new Buffer
1447 # b.append "hello"
1448 # b.append "world"
1449 # assert b == "helloworld"
1450 fun append(s: Text) is abstract
1451
1452 # `self` is appended in such a way that `self` is repeated `r` times
1453 #
1454 # var b = new Buffer
1455 # b.append "hello"
1456 # b.times 3
1457 # assert b == "hellohellohello"
1458 fun times(r: Int) is abstract
1459
1460 # Reverses itself in-place
1461 #
1462 # var b = new Buffer
1463 # b.append("hello")
1464 # b.reverse
1465 # assert b == "olleh"
1466 fun reverse is abstract
1467
1468 # Changes each lower-case char in `self` by its upper-case variant
1469 #
1470 # var b = new Buffer
1471 # b.append("Hello World!")
1472 # b.upper
1473 # assert b == "HELLO WORLD!"
1474 fun upper is abstract
1475
1476 # Changes each upper-case char in `self` by its lower-case variant
1477 #
1478 # var b = new Buffer
1479 # b.append("Hello World!")
1480 # b.lower
1481 # assert b == "hello world!"
1482 fun lower is abstract
1483
1484 # Capitalizes each word in `self`
1485 #
1486 # Letters that follow a letter are lowercased
1487 # Letters that follow a non-letter are upcased.
1488 #
1489 # If `keep_upper = true`, uppercase letters are not lowercased.
1490 #
1491 # When `src` is specified, this method reads from `src` instead of `self`
1492 # but it still writes the result to the beginning of `self`.
1493 # This requires `self` to have the capacity to receive all of the
1494 # capitalized content of `src`.
1495 #
1496 # SEE: `Char::is_letter` for the definition of a letter.
1497 #
1498 # var b = new FlatBuffer.from("jAVAsCriPt")
1499 # b.capitalize
1500 # assert b == "Javascript"
1501 # b = new FlatBuffer.from("i am root")
1502 # b.capitalize
1503 # assert b == "I Am Root"
1504 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1505 # b.capitalize
1506 # assert b == "Ab_C -Ab0C Ab\nC"
1507 #
1508 # b = new FlatBuffer.from("12345")
1509 # b.capitalize(src="foo")
1510 # assert b == "Foo45"
1511 #
1512 # b = new FlatBuffer.from("preserve my ACRONYMS")
1513 # b.capitalize(keep_upper=true)
1514 # assert b == "Preserve My ACRONYMS"
1515 fun capitalize(keep_upper: nullable Bool, src: nullable Text) do
1516 src = src or else self
1517 var length = src.length
1518 if length == 0 then return
1519 keep_upper = keep_upper or else false
1520
1521 var c = src[0].to_upper
1522 self[0] = c
1523 var prev = c
1524 for i in [1 .. length[ do
1525 prev = c
1526 c = src[i]
1527 if prev.is_letter then
1528 if keep_upper then
1529 self[i] = c
1530 else
1531 self[i] = c.to_lower
1532 end
1533 else
1534 self[i] = c.to_upper
1535 end
1536 end
1537 end
1538
1539 # In Buffers, the internal sequence of character is mutable
1540 # Thus, `chars` can be used to modify the buffer.
1541 redef fun chars: Sequence[Char] is abstract
1542
1543 # Appends `length` chars from `s` starting at index `from`
1544 #
1545 # ~~~nit
1546 # var b = new Buffer
1547 # b.append_substring("abcde", 1, 2)
1548 # assert b == "bc"
1549 # b.append_substring("vwxyz", 2, 3)
1550 # assert b == "bcxyz"
1551 # b.append_substring("ABCDE", 4, 300)
1552 # assert b == "bcxyzE"
1553 # b.append_substring("VWXYZ", 400, 1)
1554 # assert b == "bcxyzE"
1555 # ~~~
1556 fun append_substring(s: Text, from, length: Int) do
1557 if from < 0 then
1558 length += from
1559 from = 0
1560 end
1561 var ln = s.length
1562 if (length + from) > ln then length = ln - from
1563 if length <= 0 then return
1564 append_substring_impl(s, from, length)
1565 end
1566
1567 # Unsafe version of `append_substring` for performance
1568 #
1569 # NOTE: Use only if sure about `from` and `length`, no checks
1570 # or bound recalculation is done
1571 fun append_substring_impl(s: Text, from, length: Int) do
1572 var pos = from
1573 for i in [0 .. length[ do
1574 self.add s[pos]
1575 pos += 1
1576 end
1577 end
1578 end
1579
1580 # View for chars on Buffer objects, extends Sequence
1581 # for mutation operations
1582 private abstract class BufferCharView
1583 super StringCharView
1584 super Sequence[Char]
1585
1586 redef type SELFTYPE: Buffer
1587
1588 end
1589
1590 # View for bytes on Buffer objects, extends Sequence
1591 # for mutation operations
1592 private abstract class BufferByteView
1593 super StringByteView
1594
1595 redef type SELFTYPE: Buffer
1596 end
1597
1598 redef class Object
1599 # User readable representation of `self`.
1600 fun to_s: String do return inspect
1601
1602 # The class name of the object in NativeString format.
1603 private fun native_class_name: NativeString is intern
1604
1605 # The class name of the object.
1606 #
1607 # assert 5.class_name == "Int"
1608 fun class_name: String do return native_class_name.to_s
1609
1610 # Developer readable representation of `self`.
1611 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1612 fun inspect: String
1613 do
1614 return "<{inspect_head}>"
1615 end
1616
1617 # Return "CLASSNAME:#OBJECTID".
1618 # This function is mainly used with the redefinition of the inspect method
1619 protected fun inspect_head: String
1620 do
1621 return "{class_name}:#{object_id.to_hex}"
1622 end
1623 end
1624
1625 redef class Bool
1626 # assert true.to_s == "true"
1627 # assert false.to_s == "false"
1628 redef fun to_s
1629 do
1630 if self then
1631 return once "true"
1632 else
1633 return once "false"
1634 end
1635 end
1636 end
1637
1638 redef class Byte
1639 # C function to calculate the length of the `NativeString` to receive `self`
1640 private fun byte_to_s_len: Int `{
1641 return snprintf(NULL, 0, "0x%02x", self);
1642 `}
1643
1644 # C function to convert an nit Int to a NativeString (char*)
1645 private fun native_byte_to_s(nstr: NativeString, strlen: Int) `{
1646 snprintf(nstr, strlen, "0x%02x", self);
1647 `}
1648
1649 # Displayable byte in its hexadecimal form (0x..)
1650 #
1651 # assert 1.to_b.to_s == "0x01"
1652 # assert (-123).to_b.to_s == "0x85"
1653 redef fun to_s do
1654 var nslen = byte_to_s_len
1655 var ns = new NativeString(nslen + 1)
1656 ns[nslen] = 0u8
1657 native_byte_to_s(ns, nslen + 1)
1658 return ns.to_s_unsafe(nslen)
1659 end
1660 end
1661
1662 redef class Int
1663
1664 # Wrapper of strerror C function
1665 private fun strerror_ext: NativeString `{ return strerror((int)self); `}
1666
1667 # Returns a string describing error number
1668 fun strerror: String do return strerror_ext.to_s
1669
1670 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if negative).
1671 # assume < to_c max const of char
1672 private fun fill_buffer(s: Buffer, base: Int)
1673 do
1674 var n: Int
1675 # Sign
1676 if self < 0 then
1677 n = - self
1678 s.chars[0] = '-'
1679 else if self == 0 then
1680 s.chars[0] = '0'
1681 return
1682 else
1683 n = self
1684 end
1685 # Fill digits
1686 var pos = digit_count(base) - 1
1687 while pos >= 0 and n > 0 do
1688 s.chars[pos] = (n % base).to_c
1689 n = n / base # /
1690 pos -= 1
1691 end
1692 end
1693
1694 # C function to calculate the length of the `NativeString` to receive `self`
1695 private fun int_to_s_len: Int `{
1696 return snprintf(NULL, 0, "%ld", self);
1697 `}
1698
1699 # C function to convert an nit Int to a NativeString (char*)
1700 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1701 snprintf(nstr, strlen, "%ld", self);
1702 `}
1703
1704 # String representation of `self` in the given `base`
1705 #
1706 # ~~~
1707 # assert 15.to_base(10) == "15"
1708 # assert 15.to_base(16) == "f"
1709 # assert 15.to_base(2) == "1111"
1710 # assert (-10).to_base(3) == "-101"
1711 # ~~~
1712 fun to_base(base: Int): String
1713 do
1714 var l = digit_count(base)
1715 var s = new Buffer
1716 s.enlarge(l)
1717 for x in [0..l[ do s.add(' ')
1718 fill_buffer(s, base)
1719 return s.to_s
1720 end
1721
1722
1723 # return displayable int in hexadecimal
1724 #
1725 # assert 1.to_hex == "1"
1726 # assert (-255).to_hex == "-ff"
1727 fun to_hex: String do return to_base(16)
1728 end
1729
1730 redef class Float
1731 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1732 #
1733 # assert 12.34.to_s == "12.34"
1734 # assert (-0120.030).to_s == "-120.03"
1735 #
1736 # see `to_precision` for a custom precision.
1737 redef fun to_s do
1738 var str = to_precision( 3 )
1739 if is_inf != 0 or is_nan then return str
1740 var len = str.length
1741 for i in [0..len-1] do
1742 var j = len-1-i
1743 var c = str.chars[j]
1744 if c == '0' then
1745 continue
1746 else if c == '.' then
1747 return str.substring( 0, j+2 )
1748 else
1749 return str.substring( 0, j+1 )
1750 end
1751 end
1752 return str
1753 end
1754
1755 # `String` representation of `self` with the given number of `decimals`
1756 #
1757 # assert 12.345.to_precision(0) == "12"
1758 # assert 12.345.to_precision(3) == "12.345"
1759 # assert (-12.345).to_precision(3) == "-12.345"
1760 # assert (-0.123).to_precision(3) == "-0.123"
1761 # assert 0.999.to_precision(2) == "1.00"
1762 # assert 0.999.to_precision(4) == "0.9990"
1763 fun to_precision(decimals: Int): String
1764 do
1765 if is_nan then return "nan"
1766
1767 var isinf = self.is_inf
1768 if isinf == 1 then
1769 return "inf"
1770 else if isinf == -1 then
1771 return "-inf"
1772 end
1773
1774 if decimals == 0 then return self.to_i.to_s
1775 var f = self
1776 for i in [0..decimals[ do f = f * 10.0
1777 if self > 0.0 then
1778 f = f + 0.5
1779 else
1780 f = f - 0.5
1781 end
1782 var i = f.to_i
1783 if i == 0 then return "0." + "0"*decimals
1784
1785 # Prepare both parts of the float, before and after the "."
1786 var s = i.abs.to_s
1787 var sl = s.length
1788 var p1
1789 var p2
1790 if sl > decimals then
1791 # Has something before the "."
1792 p1 = s.substring(0, sl-decimals)
1793 p2 = s.substring(sl-decimals, decimals)
1794 else
1795 p1 = "0"
1796 p2 = "0"*(decimals-sl) + s
1797 end
1798
1799 if i < 0 then p1 = "-" + p1
1800
1801 return p1 + "." + p2
1802 end
1803 end
1804
1805 redef class Char
1806
1807 # Returns a sequence with the UTF-8 bytes of `self`
1808 #
1809 # assert 'a'.bytes == [0x61u8]
1810 # assert 'ま'.bytes == [0xE3u8, 0x81u8, 0xBEu8]
1811 fun bytes: SequenceRead[Byte] do return to_s.bytes
1812
1813 # Is `self` an UTF-16 surrogate pair ?
1814 fun is_surrogate: Bool do
1815 var cp = code_point
1816 return cp >= 0xD800 and cp <= 0xDFFF
1817 end
1818
1819 # Is `self` a UTF-16 high surrogate ?
1820 fun is_hi_surrogate: Bool do
1821 var cp = code_point
1822 return cp >= 0xD800 and cp <= 0xDBFF
1823 end
1824
1825 # Is `self` a UTF-16 low surrogate ?
1826 fun is_lo_surrogate: Bool do
1827 var cp = code_point
1828 return cp >= 0xDC00 and cp <= 0xDFFF
1829 end
1830
1831 # Length of `self` in a UTF-8 String
1832 fun u8char_len: Int do
1833 var c = self.code_point
1834 if c < 0x80 then return 1
1835 if c <= 0x7FF then return 2
1836 if c <= 0xFFFF then return 3
1837 if c <= 0x10FFFF then return 4
1838 # Bad character format
1839 return 1
1840 end
1841
1842 # assert 'x'.to_s == "x"
1843 redef fun to_s do
1844 var ln = u8char_len
1845 var ns = new NativeString(ln + 1)
1846 u8char_tos(ns, ln)
1847 return ns.to_s_unsafe(ln)
1848 end
1849
1850 # Returns `self` escaped to UTF-16
1851 #
1852 # i.e. Represents `self`.`code_point` using UTF-16 codets escaped
1853 # with a `\u`
1854 #
1855 # assert 'A'.escape_to_utf16 == "\\u0041"
1856 # assert 'è'.escape_to_utf16 == "\\u00e8"
1857 # assert 'あ'.escape_to_utf16 == "\\u3042"
1858 # assert '𐏓'.escape_to_utf16 == "\\ud800\\udfd3"
1859 fun escape_to_utf16: String do
1860 var cp = code_point
1861 var buf: Buffer
1862 if cp < 0xD800 or (cp >= 0xE000 and cp <= 0xFFFF) then
1863 buf = new Buffer.with_cap(6)
1864 buf.append("\\u0000")
1865 var hx = cp.to_hex
1866 var outid = 5
1867 for i in hx.chars.reverse_iterator do
1868 buf[outid] = i
1869 outid -= 1
1870 end
1871 else
1872 buf = new Buffer.with_cap(12)
1873 buf.append("\\u0000\\u0000")
1874 var lo = (((cp - 0x10000) & 0x3FF) + 0xDC00).to_hex
1875 var hi = ((((cp - 0x10000) & 0xFFC00) >> 10) + 0xD800).to_hex
1876 var out = 2
1877 for i in hi do
1878 buf[out] = i
1879 out += 1
1880 end
1881 out = 8
1882 for i in lo do
1883 buf[out] = i
1884 out += 1
1885 end
1886 end
1887 return buf.to_s
1888 end
1889
1890 private fun u8char_tos(r: NativeString, len: Int) `{
1891 r[len] = '\0';
1892 switch(len){
1893 case 1:
1894 r[0] = self;
1895 break;
1896 case 2:
1897 r[0] = 0xC0 | ((self & 0x7C0) >> 6);
1898 r[1] = 0x80 | (self & 0x3F);
1899 break;
1900 case 3:
1901 r[0] = 0xE0 | ((self & 0xF000) >> 12);
1902 r[1] = 0x80 | ((self & 0xFC0) >> 6);
1903 r[2] = 0x80 | (self & 0x3F);
1904 break;
1905 case 4:
1906 r[0] = 0xF0 | ((self & 0x1C0000) >> 18);
1907 r[1] = 0x80 | ((self & 0x3F000) >> 12);
1908 r[2] = 0x80 | ((self & 0xFC0) >> 6);
1909 r[3] = 0x80 | (self & 0x3F);
1910 break;
1911 }
1912 `}
1913
1914 # Returns true if the char is a numerical digit
1915 #
1916 # assert '0'.is_numeric
1917 # assert '9'.is_numeric
1918 # assert not 'a'.is_numeric
1919 # assert not '?'.is_numeric
1920 #
1921 # FIXME: Works on ASCII-range only
1922 fun is_numeric: Bool
1923 do
1924 return self >= '0' and self <= '9'
1925 end
1926
1927 # Returns true if the char is an alpha digit
1928 #
1929 # assert 'a'.is_alpha
1930 # assert 'Z'.is_alpha
1931 # assert not '0'.is_alpha
1932 # assert not '?'.is_alpha
1933 #
1934 # FIXME: Works on ASCII-range only
1935 fun is_alpha: Bool
1936 do
1937 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1938 end
1939
1940 # Is `self` an hexadecimal digit ?
1941 #
1942 # assert 'A'.is_hexdigit
1943 # assert not 'G'.is_hexdigit
1944 # assert 'a'.is_hexdigit
1945 # assert not 'g'.is_hexdigit
1946 # assert '5'.is_hexdigit
1947 fun is_hexdigit: Bool do return (self >= '0' and self <= '9') or (self >= 'A' and self <= 'F') or
1948 (self >= 'a' and self <= 'f')
1949
1950 # Returns true if the char is an alpha or a numeric digit
1951 #
1952 # assert 'a'.is_alphanumeric
1953 # assert 'Z'.is_alphanumeric
1954 # assert '0'.is_alphanumeric
1955 # assert '9'.is_alphanumeric
1956 # assert not '?'.is_alphanumeric
1957 #
1958 # FIXME: Works on ASCII-range only
1959 fun is_alphanumeric: Bool
1960 do
1961 return self.is_numeric or self.is_alpha
1962 end
1963
1964 # Returns `self` to its int value
1965 #
1966 # REQUIRE: `is_hexdigit`
1967 fun from_hex: Int do
1968 if self >= '0' and self <= '9' then return code_point - 0x30
1969 if self >= 'A' and self <= 'F' then return code_point - 0x37
1970 if self >= 'a' and self <= 'f' then return code_point - 0x57
1971 # Happens if self is not a hexdigit
1972 assert self.is_hexdigit
1973 # To make flow analysis happy
1974 abort
1975 end
1976 end
1977
1978 redef class Collection[E]
1979 # String representation of the content of the collection.
1980 #
1981 # The standard representation is the list of elements separated with commas.
1982 #
1983 # ~~~
1984 # assert [1,2,3].to_s == "[1,2,3]"
1985 # assert [1..3].to_s == "[1,2,3]"
1986 # assert (new Array[Int]).to_s == "[]" # empty collection
1987 # ~~~
1988 #
1989 # Subclasses may return a more specific string representation.
1990 redef fun to_s
1991 do
1992 return "[" + join(",") + "]"
1993 end
1994
1995 # Concatenate elements without separators
1996 #
1997 # ~~~
1998 # assert [1,2,3].plain_to_s == "123"
1999 # assert [11..13].plain_to_s == "111213"
2000 # assert (new Array[Int]).plain_to_s == "" # empty collection
2001 # ~~~
2002 fun plain_to_s: String
2003 do
2004 var s = new Buffer
2005 for e in self do if e != null then s.append(e.to_s)
2006 return s.to_s
2007 end
2008
2009 # Concatenate and separate each elements with `separator`.
2010 #
2011 # Only concatenate if `separator == null`.
2012 #
2013 # assert [1, 2, 3].join(":") == "1:2:3"
2014 # assert [1..3].join(":") == "1:2:3"
2015 # assert [1..3].join == "123"
2016 #
2017 # if `last_separator` is given, then it is used to separate the last element.
2018 #
2019 # assert [1, 2, 3, 4].join(", ", " and ") == "1, 2, 3 and 4"
2020 fun join(separator: nullable Text, last_separator: nullable Text): String
2021 do
2022 if is_empty then return ""
2023
2024 var s = new Buffer # Result
2025
2026 # Concat first item
2027 var i = iterator
2028 var e = i.item
2029 if e != null then s.append(e.to_s)
2030
2031 if last_separator == null then last_separator = separator
2032
2033 # Concat other items
2034 i.next
2035 while i.is_ok do
2036 e = i.item
2037 i.next
2038 if i.is_ok then
2039 if separator != null then s.append(separator)
2040 else
2041 if last_separator != null then s.append(last_separator)
2042 end
2043 if e != null then s.append(e.to_s)
2044 end
2045 return s.to_s
2046 end
2047 end
2048
2049 redef class Map[K,V]
2050 # Concatenate couples of key value.
2051 # Key and value are separated by `couple_sep`.
2052 # Couples are separated by `sep`.
2053 #
2054 # var m = new HashMap[Int, String]
2055 # m[1] = "one"
2056 # m[10] = "ten"
2057 # assert m.join("; ", "=") == "1=one; 10=ten"
2058 fun join(sep, couple_sep: String): String is abstract
2059 end
2060
2061 redef class Sys
2062 private var args_cache: nullable Sequence[String] = null
2063
2064 # The arguments of the program as given by the OS
2065 fun program_args: Sequence[String]
2066 do
2067 if _args_cache == null then init_args
2068 return _args_cache.as(not null)
2069 end
2070
2071 # The name of the program as given by the OS
2072 fun program_name: String
2073 do
2074 return native_argv(0).to_s
2075 end
2076
2077 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2078 private fun init_args
2079 do
2080 var argc = native_argc
2081 var args = new Array[String].with_capacity(0)
2082 var i = 1
2083 while i < argc do
2084 args[i-1] = native_argv(i).to_s
2085 i += 1
2086 end
2087 _args_cache = args
2088 end
2089
2090 # First argument of the main C function.
2091 private fun native_argc: Int is intern
2092
2093 # Second argument of the main C function.
2094 private fun native_argv(i: Int): NativeString is intern
2095 end
2096
2097 # Comparator that efficienlty use `to_s` to compare things
2098 #
2099 # The comparaison call `to_s` on object and use the result to order things.
2100 #
2101 # var a = [1, 2, 3, 10, 20]
2102 # (new CachedAlphaComparator).sort(a)
2103 # assert a == [1, 10, 2, 20, 3]
2104 #
2105 # Internally the result of `to_s` is cached in a HashMap to counter
2106 # uneficient implementation of `to_s`.
2107 #
2108 # Note: it caching is not usefull, see `alpha_comparator`
2109 class CachedAlphaComparator
2110 super Comparator
2111 redef type COMPARED: Object
2112
2113 private var cache = new HashMap[Object, String]
2114
2115 private fun do_to_s(a: Object): String do
2116 if cache.has_key(a) then return cache[a]
2117 var res = a.to_s
2118 cache[a] = res
2119 return res
2120 end
2121
2122 redef fun compare(a, b) do
2123 return do_to_s(a) <=> do_to_s(b)
2124 end
2125 end
2126
2127 # see `alpha_comparator`
2128 private class AlphaComparator
2129 super Comparator
2130 redef fun compare(a, b) do
2131 if a == b then return 0
2132 if a == null then return -1
2133 if b == null then return 1
2134 return a.to_s <=> b.to_s
2135 end
2136 end
2137
2138 # Stateless comparator that naively use `to_s` to compare things.
2139 #
2140 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2141 # on a single instace. See `CachedAlphaComparator` as an alternative.
2142 #
2143 # var a = [1, 2, 3, 10, 20]
2144 # alpha_comparator.sort(a)
2145 # assert a == [1, 10, 2, 20, 3]
2146 fun alpha_comparator: Comparator do return once new AlphaComparator
2147
2148 # The arguments of the program as given by the OS
2149 fun args: Sequence[String]
2150 do
2151 return sys.program_args
2152 end
2153
2154 redef class NativeString
2155 # Get a `String` from the data at `self` copied into Nit memory
2156 #
2157 # Require: `self` is a null-terminated string.
2158 fun to_s_with_copy: String is abstract
2159
2160 # Get a `String` from `length` bytes at `self`
2161 #
2162 # The result may point to the data at `self` or
2163 # it may make a copy in Nit controlled memory.
2164 # This method should only be used when `self` was allocated by the Nit GC,
2165 # or when manually controlling the deallocation of `self`.
2166 fun to_s_with_length(length: Int): String is abstract
2167
2168 # Get a `String` from the raw `length` bytes at `self`
2169 #
2170 # The default value of `length` is the number of bytes before
2171 # the first null character.
2172 #
2173 # The created `String` points to the data at `self`.
2174 # This method should be used when `self` was allocated by the Nit GC,
2175 # or when manually controlling the deallocation of `self`.
2176 #
2177 # /!\: This service does not clean the items for compliance with UTF-8,
2178 # use only when the data has already been verified as valid UTF-8.
2179 fun to_s_unsafe(length: nullable Int): String is abstract
2180
2181 # Get a `String` from the raw `byte_length` bytes at `self` with `unilen` Unicode characters
2182 #
2183 # The created `String` points to the data at `self`.
2184 # This method should be used when `self` was allocated by the Nit GC,
2185 # or when manually controlling the deallocation of `self`.
2186 #
2187 # /!\: This service does not clean the items for compliance with UTF-8,
2188 # use only when the data has already been verified as valid UTF-8.
2189 #
2190 # SEE: `abstract_text::Text` for more info on the difference
2191 # between `Text::byte_length` and `Text::length`.
2192 fun to_s_full(byte_length, unilen: Int): String is abstract
2193
2194 # Copies the content of `src` to `self`
2195 #
2196 # NOTE: `self` must be large enough to withold `self.byte_length` bytes
2197 fun fill_from(src: Text) do src.copy_to_native(self, src.byte_length, 0, 0)
2198 end
2199
2200 redef class NativeArray[E]
2201 # Join all the elements using `to_s`
2202 #
2203 # REQUIRE: `self isa NativeArray[String]`
2204 # REQUIRE: all elements are initialized
2205 fun native_to_s: String is abstract
2206 end