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