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