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