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