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