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