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