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