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