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