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