nitc&lib: MapIterator keys can be nullable
[nit.git] / lib / standard / string.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
5 #
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
12 # another product.
13
14 # Basic manipulations of strings of characters
15 module string
16
17 import math
18 import collection
19 intrude import collection::array
20
21 `{
22 #include <stdio.h>
23 #include <string.h>
24 `}
25
26 ###############################################################################
27 # String #
28 ###############################################################################
29
30 # High-level abstraction for all text representations
31 abstract class Text
32 super Comparable
33
34 redef type OTHER: Text
35
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
37 type SELFTYPE: Text
38
39 # Gets a view on the chars of the Text object
40 #
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars: SequenceRead[Char] is abstract
43
44 # Number of characters contained in self.
45 #
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length: Int is abstract
49
50 # Create a substring.
51 #
52 # assert "abcd".substring(1, 2) == "bc"
53 # assert "abcd".substring(-1, 2) == "a"
54 # assert "abcd".substring(1, 0) == ""
55 # assert "abcd".substring(2, 5) == "cd"
56 #
57 # A `from` index < 0 will be replaced by 0.
58 # Unless a `count` value is > 0 at the same time.
59 # In this case, `from += count` and `count -= from`.
60 fun substring(from: Int, count: Int): SELFTYPE is abstract
61
62 # Iterates on the substrings of self if any
63 fun substrings: Iterator[Text] is abstract
64
65 # Is the current Text empty (== "")
66 #
67 # assert "".is_empty
68 # assert not "foo".is_empty
69 fun is_empty: Bool do return self.length == 0
70
71 # Returns an empty Text of the right type
72 #
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty: SELFTYPE is abstract
76
77 # Gets the first char of the Text
78 #
79 # DEPRECATED : Use self.chars.first instead
80 fun first: Char do return self.chars[0]
81
82 # Access a character at `index` in the string.
83 #
84 # assert "abcd"[2] == 'c'
85 #
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index: Int): Char do return self.chars[index]
88
89 # Gets the index of the first occurence of 'c'
90 #
91 # Returns -1 if not found
92 #
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of(c: Char): Int
95 do
96 return index_of_from(c, 0)
97 end
98
99 # Gets the last char of self
100 #
101 # DEPRECATED : Use self.chars.last instead
102 fun last: Char do return self.chars[length-1]
103
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
105 #
106 # Returns -1 if not found
107 #
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from(c: Char, pos: Int): Int
110 do
111 var iter = self.chars.iterator_from(pos)
112 while iter.is_ok do
113 if iter.item == c then return iter.index
114 iter.next
115 end
116 return -1
117 end
118
119 # Gets the last index of char ´c´
120 #
121 # Returns -1 if not found
122 #
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of(c: Char): Int
125 do
126 return last_index_of_from(c, length - 1)
127 end
128
129 # Return a null terminated char *
130 fun to_cstring: NativeString do return flatten.to_cstring
131
132 # The index of the last occurrence of an element starting from pos (in reverse order).
133 #
134 # var s = "/etc/bin/test/test.nit"
135 # assert s.last_index_of_from('/', s.length-1) == 13
136 # assert s.last_index_of_from('/', 12) == 8
137 #
138 # Returns -1 if not found
139 #
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from(item: Char, pos: Int): Int
142 do
143 var iter = self.chars.reverse_iterator_from(pos)
144 while iter.is_ok do
145 if iter.item == item then return iter.index
146 iter.next
147 end
148 return -1
149 end
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 # If `self` contains only digits, return the corresponding integer
227 #
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
230 fun to_i: Int
231 do
232 # Shortcut
233 return to_s.to_cstring.atoi
234 end
235
236 # If `self` contains a float, return the corresponding float
237 #
238 # assert "123".to_f == 123.0
239 # assert "-1".to_f == -1.0
240 # assert "-1.2e-3".to_f == -0.0012
241 fun to_f: Float
242 do
243 # Shortcut
244 return to_s.to_cstring.atof
245 end
246
247 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
248 #
249 # assert "ff".to_hex == 255
250 fun to_hex: Int do return a_to(16)
251
252 # If `self` contains only digits and letters, return the corresponding integer in a given base
253 #
254 # assert "120".a_to(3) == 15
255 fun a_to(base: Int) : Int
256 do
257 var i = 0
258 var neg = false
259
260 for j in [0..length[ do
261 var c = chars[j]
262 var v = c.to_i
263 if v > base then
264 if neg then
265 return -i
266 else
267 return i
268 end
269 else if v < 0 then
270 neg = true
271 else
272 i = i * base + v
273 end
274 end
275 if neg then
276 return -i
277 else
278 return i
279 end
280 end
281
282 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
283 #
284 # assert "123".is_numeric == true
285 # assert "1.2".is_numeric == true
286 # assert "1,2".is_numeric == true
287 # assert "1..2".is_numeric == false
288 fun is_numeric: Bool
289 do
290 var has_point_or_comma = false
291 for i in [0..length[ do
292 var c = chars[i]
293 if not c.is_numeric then
294 if (c == '.' or c == ',') and not has_point_or_comma then
295 has_point_or_comma = true
296 else
297 return false
298 end
299 end
300 end
301 return true
302 end
303
304 # Returns `true` if the string contains only Hex chars
305 #
306 # assert "048bf".is_hex == true
307 # assert "ABCDEF".is_hex == true
308 # assert "0G".is_hex == false
309 fun is_hex: Bool
310 do
311 for i in [0..length[ do
312 var c = chars[i]
313 if not (c >= 'a' and c <= 'f') and
314 not (c >= 'A' and c <= 'F') and
315 not (c >= '0' and c <= '9') then return false
316 end
317 return true
318 end
319
320 # Are all letters in `self` upper-case ?
321 #
322 # assert "HELLO WORLD".is_upper == true
323 # assert "%$&%!".is_upper == true
324 # assert "hello world".is_upper == false
325 # assert "Hello World".is_upper == false
326 fun is_upper: Bool
327 do
328 for i in [0..length[ do
329 var char = chars[i]
330 if char.is_lower then return false
331 end
332 return true
333 end
334
335 # Are all letters in `self` lower-case ?
336 #
337 # assert "hello world".is_lower == true
338 # assert "%$&%!".is_lower == true
339 # assert "Hello World".is_lower == false
340 fun is_lower: Bool
341 do
342 for i in [0..length[ do
343 var char = chars[i]
344 if char.is_upper then return false
345 end
346 return true
347 end
348
349 # Removes the whitespaces at the beginning of self
350 #
351 # assert " \n\thello \n\t".l_trim == "hello \n\t"
352 #
353 # A whitespace is defined as any character which ascii value is less than or equal to 32
354 fun l_trim: SELFTYPE
355 do
356 var iter = self.chars.iterator
357 while iter.is_ok do
358 if iter.item.ascii > 32 then break
359 iter.next
360 end
361 if iter.index == length then return self.empty
362 return self.substring_from(iter.index)
363 end
364
365 # Removes the whitespaces at the end of self
366 #
367 # assert " \n\thello \n\t".r_trim == " \n\thello"
368 #
369 # A whitespace is defined as any character which ascii value is less than or equal to 32
370 fun r_trim: SELFTYPE
371 do
372 var iter = self.chars.reverse_iterator
373 while iter.is_ok do
374 if iter.item.ascii > 32 then break
375 iter.next
376 end
377 if iter.index < 0 then return self.empty
378 return self.substring(0, iter.index + 1)
379 end
380
381 # Trims trailing and preceding white spaces
382 # A whitespace is defined as any character which ascii value is less than or equal to 32
383 #
384 # assert " Hello World ! ".trim == "Hello World !"
385 # assert "\na\nb\tc\t".trim == "a\nb\tc"
386 fun trim: SELFTYPE do return (self.l_trim).r_trim
387
388 # Returns `self` removed from its last line terminator (if any).
389 #
390 # assert "Hello\n".chomp == "Hello"
391 # assert "Hello".chomp == "Hello"
392 #
393 # assert "\n".chomp == ""
394 # assert "".chomp == ""
395 #
396 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
397 # A single line terminator, the last one, is removed.
398 #
399 # assert "\r\n".chomp == ""
400 # assert "\r\n\n".chomp == "\r\n"
401 # assert "\r\n\r\n".chomp == "\r\n"
402 # assert "\r\n\r".chomp == "\r\n"
403 #
404 # Note: unlike with most IO methods like `IStream::read_line`,
405 # a single `\r` is considered here to be a line terminator and will be removed.
406 fun chomp: SELFTYPE
407 do
408 var len = length
409 if len == 0 then return self
410 var l = self.chars.last
411 if l == '\r' then
412 return substring(0, len-1)
413 else if l != '\n' then
414 return self
415 else if len > 1 and self.chars[len-2] == '\r' then
416 return substring(0, len-2)
417 else
418 return substring(0, len-1)
419 end
420 end
421
422 # Justify a self in a space of `length`
423 #
424 # `left` is the space ratio on the left side.
425 # * 0.0 for left-justified (no space at the left)
426 # * 1.0 for right-justified (all spaces at the left)
427 # * 0.5 for centered (half the spaces at the left)
428 #
429 # Examples
430 #
431 # assert "hello".justify(10, 0.0) == "hello "
432 # assert "hello".justify(10, 1.0) == " hello"
433 # assert "hello".justify(10, 0.5) == " hello "
434 #
435 # If `length` is not enough, `self` is returned as is.
436 #
437 # assert "hello".justify(2, 0.0) == "hello"
438 #
439 # REQUIRE: `left >= 0.0 and left <= 1.0`
440 # ENSURE: `self.length <= length implies result.length == length`
441 # ENSURE: `self.length >= length implies result == self`
442 fun justify(length: Int, left: Float): SELFTYPE
443 do
444 var diff = length - self.length
445 if diff <= 0 then return self
446 assert left >= 0.0 and left <= 1.0
447 var before = (diff.to_f * left).to_i
448 return " " * before + self + " " * (diff-before)
449 end
450
451 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
452 #
453 # This method is injective (two different inputs never produce the same
454 # output) and the returned string always respect the following rules:
455 #
456 # * Contains only US-ASCII letters, digits and underscores.
457 # * Never starts with a digit.
458 # * Never ends with an underscore.
459 # * Never contains two contiguous underscores.
460 #
461 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
462 # assert "__".to_cmangle == "_95d_95d"
463 # assert "__d".to_cmangle == "_95d_d"
464 # assert "_d_".to_cmangle == "_d_95d"
465 # assert "_42".to_cmangle == "_95d42"
466 # assert "foo".to_cmangle == "foo"
467 # assert "".to_cmangle == ""
468 fun to_cmangle: String
469 do
470 if is_empty then return ""
471 var res = new FlatBuffer
472 var underscore = false
473 var start = 0
474 var c = chars[0]
475
476 if c >= '0' and c <= '9' then
477 res.add('_')
478 res.append(c.ascii.to_s)
479 res.add('d')
480 start = 1
481 end
482 for i in [start..length[ do
483 c = chars[i]
484 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
485 res.add(c)
486 underscore = false
487 continue
488 end
489 if underscore then
490 res.append('_'.ascii.to_s)
491 res.add('d')
492 end
493 if c >= '0' and c <= '9' then
494 res.add(c)
495 underscore = false
496 else if c == '_' then
497 res.add(c)
498 underscore = true
499 else
500 res.add('_')
501 res.append(c.ascii.to_s)
502 res.add('d')
503 underscore = false
504 end
505 end
506 if underscore then
507 res.append('_'.ascii.to_s)
508 res.add('d')
509 end
510 return res.to_s
511 end
512
513 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
514 #
515 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
516 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
517 fun escape_to_c: String
518 do
519 var b = new FlatBuffer
520 for i in [0..length[ do
521 var c = chars[i]
522 if c == '\n' then
523 b.append("\\n")
524 else if c == '\0' then
525 b.append("\\0")
526 else if c == '"' then
527 b.append("\\\"")
528 else if c == '\'' then
529 b.append("\\\'")
530 else if c == '\\' then
531 b.append("\\\\")
532 else if c.ascii < 32 then
533 b.append("\\{c.ascii.to_base(8, false)}")
534 else
535 b.add(c)
536 end
537 end
538 return b.to_s
539 end
540
541 # Escape additionnal characters
542 # The result might no be legal in C but be used in other languages
543 #
544 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
545 fun escape_more_to_c(chars: String): String
546 do
547 var b = new FlatBuffer
548 for c in escape_to_c.chars do
549 if chars.chars.has(c) then
550 b.add('\\')
551 end
552 b.add(c)
553 end
554 return b.to_s
555 end
556
557 # Escape to C plus braces
558 #
559 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
560 fun escape_to_nit: String do return escape_more_to_c("\{\}")
561
562 # Escape to POSIX Shell (sh).
563 #
564 # Abort if the text contains a null byte.
565 #
566 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
567 fun escape_to_sh: String do
568 var b = new FlatBuffer
569 b.chars.add '\''
570 for i in [0..length[ do
571 var c = chars[i]
572 if c == '\'' then
573 b.append("'\\''")
574 else
575 assert without_null_byte: c != '\0'
576 b.add(c)
577 end
578 end
579 b.chars.add '\''
580 return b.to_s
581 end
582
583 # Escape to include in a Makefile
584 #
585 # Unfortunately, some characters are not escapable in Makefile.
586 # These characters are `;`, `|`, `\`, and the non-printable ones.
587 # They will be rendered as `"?{hex}"`.
588 fun escape_to_mk: String do
589 var b = new FlatBuffer
590 for i in [0..length[ do
591 var c = chars[i]
592 if c == '$' then
593 b.append("$$")
594 else if c == ':' or c == ' ' or c == '#' then
595 b.add('\\')
596 b.add(c)
597 else if c.ascii < 32 or c == ';' or c == '|' or c == '\\' or c == '=' then
598 b.append("?{c.ascii.to_base(16, false)}")
599 else
600 b.add(c)
601 end
602 end
603 return b.to_s
604 end
605
606 # Return a string where Nit escape sequences are transformed.
607 #
608 # var s = "\\n"
609 # assert s.length == 2
610 # var u = s.unescape_nit
611 # assert u.length == 1
612 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
613 fun unescape_nit: String
614 do
615 var res = new FlatBuffer.with_capacity(self.length)
616 var was_slash = false
617 for i in [0..length[ do
618 var c = chars[i]
619 if not was_slash then
620 if c == '\\' then
621 was_slash = true
622 else
623 res.add(c)
624 end
625 continue
626 end
627 was_slash = false
628 if c == 'n' then
629 res.add('\n')
630 else if c == 'r' then
631 res.add('\r')
632 else if c == 't' then
633 res.add('\t')
634 else if c == '0' then
635 res.add('\0')
636 else
637 res.add(c)
638 end
639 end
640 return res.to_s
641 end
642
643 # Encode `self` to percent (or URL) encoding
644 #
645 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
646 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
647 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
648 fun to_percent_encoding: String
649 do
650 var buf = new FlatBuffer
651
652 for i in [0..length[ do
653 var c = chars[i]
654 if (c >= '0' and c <= '9') or
655 (c >= 'a' and c <= 'z') or
656 (c >= 'A' and c <= 'Z') or
657 c == '-' or c == '.' or
658 c == '_' or c == '~'
659 then
660 buf.add c
661 else buf.append "%{c.ascii.to_hex}"
662 end
663
664 return buf.to_s
665 end
666
667 # Decode `self` from percent (or URL) encoding to a clear string
668 #
669 # Replace invalid use of '%' with '?'.
670 #
671 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
672 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
673 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
674 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
675 # assert "incomplete %".from_percent_encoding == "incomplete ?"
676 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
677 fun from_percent_encoding: String
678 do
679 var buf = new FlatBuffer
680
681 var i = 0
682 while i < length do
683 var c = chars[i]
684 if c == '%' then
685 if i + 2 >= length then
686 # What follows % has been cut off
687 buf.add '?'
688 else
689 i += 1
690 var hex_s = substring(i, 2)
691 if hex_s.is_hex then
692 var hex_i = hex_s.to_hex
693 buf.add hex_i.ascii
694 i += 1
695 else
696 # What follows a % is not Hex
697 buf.add '?'
698 i -= 1
699 end
700 end
701 else buf.add c
702
703 i += 1
704 end
705
706 return buf.to_s
707 end
708
709 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
710 #
711 # assert "a&b-<>\"x\"/'".html_escape == "a&amp;b-&lt;&gt;&#34;x&#34;&#47;&#39;"
712 #
713 # 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>
714 fun html_escape: SELFTYPE
715 do
716 var buf = new FlatBuffer
717
718 for i in [0..length[ do
719 var c = chars[i]
720 if c == '&' then
721 buf.append "&amp;"
722 else if c == '<' then
723 buf.append "&lt;"
724 else if c == '>' then
725 buf.append "&gt;"
726 else if c == '"' then
727 buf.append "&#34;"
728 else if c == '\'' then
729 buf.append "&#39;"
730 else if c == '/' then
731 buf.append "&#47;"
732 else buf.add c
733 end
734
735 return buf.to_s
736 end
737
738 # Equality of text
739 # Two pieces of text are equals if thez have the same characters in the same order.
740 #
741 # assert "hello" == "hello"
742 # assert "hello" != "HELLO"
743 # assert "hello" == "hel"+"lo"
744 #
745 # Things that are not Text are not equal.
746 #
747 # assert "9" != '9'
748 # assert "9" != ['9']
749 # assert "9" != 9
750 #
751 # assert "9".chars.first == '9' # equality of Char
752 # assert "9".chars == ['9'] # equality of Sequence
753 # assert "9".to_i == 9 # equality of Int
754 redef fun ==(o)
755 do
756 if o == null then return false
757 if not o isa Text then return false
758 if self.is_same_instance(o) then return true
759 if self.length != o.length then return false
760 return self.chars == o.chars
761 end
762
763 # Lexicographical comparaison
764 #
765 # assert "abc" < "xy"
766 # assert "ABC" < "abc"
767 redef fun <(other)
768 do
769 var self_chars = self.chars.iterator
770 var other_chars = other.chars.iterator
771
772 while self_chars.is_ok and other_chars.is_ok do
773 if self_chars.item < other_chars.item then return true
774 if self_chars.item > other_chars.item then return false
775 self_chars.next
776 other_chars.next
777 end
778
779 if self_chars.is_ok then
780 return false
781 else
782 return true
783 end
784 end
785
786 # Escape string used in labels for graphviz
787 #
788 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
789 fun escape_to_dot: String
790 do
791 return escape_more_to_c("|\{\}<>")
792 end
793
794 # Flat representation of self
795 fun flatten: FlatText is abstract
796
797 private var hash_cache: nullable Int = null
798
799 redef fun hash
800 do
801 if hash_cache == null then
802 # djb2 hash algorithm
803 var h = 5381
804
805 for i in [0..length[ do
806 var char = chars[i]
807 h = h.lshift(5) + h + char.ascii
808 end
809
810 hash_cache = h
811 end
812 return hash_cache.as(not null)
813 end
814
815 end
816
817 # All kinds of array-based text representations.
818 abstract class FlatText
819 super Text
820
821 # Underlying C-String (`char*`)
822 #
823 # Warning : Might be void in some subclasses, be sure to check
824 # if set before using it.
825 private var items: NativeString is noinit
826
827 # Real items, used as cache for to_cstring is called
828 private var real_items: nullable NativeString = null
829
830 redef var length: Int = 0
831
832 redef fun output
833 do
834 var i = 0
835 while i < length do
836 items[i].output
837 i += 1
838 end
839 end
840
841 redef fun flatten do return self
842 end
843
844 # Abstract class for the SequenceRead compatible
845 # views on String and Buffer objects
846 private abstract class StringCharView
847 super SequenceRead[Char]
848
849 type SELFTYPE: Text
850
851 var target: SELFTYPE
852
853 redef fun is_empty do return target.is_empty
854
855 redef fun length do return target.length
856
857 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
858
859 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
860 end
861
862 # View on Buffer objects, extends Sequence
863 # for mutation operations
864 private abstract class BufferCharView
865 super StringCharView
866 super Sequence[Char]
867
868 redef type SELFTYPE: Buffer
869
870 end
871
872 # A `String` holds and manipulates an arbitrary sequence of characters.
873 #
874 # String objects may be created using literals.
875 #
876 # assert "Hello World!" isa String
877 abstract class String
878 super Text
879
880 redef type SELFTYPE: String
881
882 redef fun to_s do return self
883
884 # Concatenates `o` to `self`
885 #
886 # assert "hello" + "world" == "helloworld"
887 # assert "" + "hello" + "" == "hello"
888 fun +(o: Text): SELFTYPE is abstract
889
890 # Concatenates self `i` times
891 #
892 # assert "abc" * 4 == "abcabcabcabc"
893 # assert "abc" * 1 == "abc"
894 # assert "abc" * 0 == ""
895 fun *(i: Int): SELFTYPE is abstract
896
897 # Insert `s` at `pos`.
898 #
899 # assert "helloworld".insert_at(" ", 5) == "hello world"
900 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
901
902 redef fun substrings: Iterator[String] is abstract
903
904 # Returns a reversed version of self
905 #
906 # assert "hello".reversed == "olleh"
907 # assert "bob".reversed == "bob"
908 # assert "".reversed == ""
909 fun reversed: SELFTYPE is abstract
910
911 # A upper case version of `self`
912 #
913 # assert "Hello World!".to_upper == "HELLO WORLD!"
914 fun to_upper: SELFTYPE is abstract
915
916 # A lower case version of `self`
917 #
918 # assert "Hello World!".to_lower == "hello world!"
919 fun to_lower : SELFTYPE is abstract
920
921 # Takes a camel case `self` and converts it to snake case
922 #
923 # assert "randomMethodId".to_snake_case == "random_method_id"
924 #
925 # If `self` is upper, it is returned unchanged
926 #
927 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
928 #
929 # If the identifier is prefixed by an underscore, the underscore is ignored
930 #
931 # assert "_privateField".to_snake_case == "_private_field"
932 fun to_snake_case: SELFTYPE
933 do
934 if self.is_upper then return self
935
936 var new_str = new FlatBuffer.with_capacity(self.length)
937 var is_first_char = true
938
939 for i in [0..length[ do
940 var char = chars[i]
941 if is_first_char then
942 new_str.add(char.to_lower)
943 is_first_char = false
944 else if char.is_upper then
945 new_str.add('_')
946 new_str.add(char.to_lower)
947 else
948 new_str.add(char)
949 end
950 end
951
952 return new_str.to_s
953 end
954
955 # Takes a snake case `self` and converts it to camel case
956 #
957 # assert "random_method_id".to_camel_case == "randomMethodId"
958 #
959 # If the identifier is prefixed by an underscore, the underscore is ignored
960 #
961 # assert "_private_field".to_camel_case == "_privateField"
962 #
963 # If `self` is upper, it is returned unchanged
964 #
965 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
966 #
967 # If there are several consecutive underscores, they are considered as a single one
968 #
969 # assert "random__method_id".to_camel_case == "randomMethodId"
970 fun to_camel_case: SELFTYPE
971 do
972 if self.is_upper then return self
973
974 var new_str = new FlatBuffer
975 var is_first_char = true
976 var follows_us = false
977
978 for i in [0..length[ do
979 var char = chars[i]
980 if is_first_char then
981 new_str.add(char)
982 is_first_char = false
983 else if char == '_' then
984 follows_us = true
985 else if follows_us then
986 new_str.add(char.to_upper)
987 follows_us = false
988 else
989 new_str.add(char)
990 end
991 end
992
993 return new_str.to_s
994 end
995
996 # Returns a capitalized `self`
997 #
998 # Letters that follow a letter are lowercased
999 # Letters that follow a non-letter are upcased.
1000 #
1001 # SEE : `Char::is_letter` for the definition of letter.
1002 #
1003 # assert "jAVASCRIPT".capitalized == "Javascript"
1004 # assert "i am root".capitalized == "I Am Root"
1005 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1006 fun capitalized: SELFTYPE do
1007 if length == 0 then return self
1008
1009 var buf = new FlatBuffer.with_capacity(length)
1010
1011 var curr = chars[0].to_upper
1012 var prev = curr
1013 buf[0] = curr
1014
1015 for i in [1 .. length[ do
1016 prev = curr
1017 curr = self[i]
1018 if prev.is_letter then
1019 buf[i] = curr.to_lower
1020 else
1021 buf[i] = curr.to_upper
1022 end
1023 end
1024
1025 return buf.to_s
1026 end
1027 end
1028
1029 private class FlatSubstringsIter
1030 super Iterator[FlatText]
1031
1032 var tgt: nullable FlatText
1033
1034 redef fun item do
1035 assert is_ok
1036 return tgt.as(not null)
1037 end
1038
1039 redef fun is_ok do return tgt != null
1040
1041 redef fun next do tgt = null
1042 end
1043
1044 # Immutable strings of characters.
1045 class FlatString
1046 super FlatText
1047 super String
1048
1049 # Index in _items of the start of the string
1050 private var index_from: Int is noinit
1051
1052 # Indes in _items of the last item of the string
1053 private var index_to: Int is noinit
1054
1055 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
1056
1057 redef fun [](index)
1058 do
1059 # Check that the index (+ index_from) is not larger than indexTo
1060 # In other terms, if the index is valid
1061 assert index >= 0
1062 assert (index + index_from) <= index_to
1063 return items[index + index_from]
1064 end
1065
1066 ################################################
1067 # AbstractString specific methods #
1068 ################################################
1069
1070 redef fun reversed
1071 do
1072 var native = new NativeString(self.length + 1)
1073 var length = self.length
1074 var items = self.items
1075 var pos = 0
1076 var ipos = length-1
1077 while pos < length do
1078 native[pos] = items[ipos]
1079 pos += 1
1080 ipos -= 1
1081 end
1082 return native.to_s_with_length(self.length)
1083 end
1084
1085 redef fun substring(from, count)
1086 do
1087 assert count >= 0
1088
1089 if from < 0 then
1090 count += from
1091 if count < 0 then count = 0
1092 from = 0
1093 end
1094
1095 var realFrom = index_from + from
1096
1097 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
1098
1099 if count == 0 then return empty
1100
1101 var to = realFrom + count - 1
1102
1103 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
1104 end
1105
1106 redef fun empty do return "".as(FlatString)
1107
1108 redef fun to_upper
1109 do
1110 var outstr = new NativeString(self.length + 1)
1111 var out_index = 0
1112
1113 var myitems = self.items
1114 var index_from = self.index_from
1115 var max = self.index_to
1116
1117 while index_from <= max do
1118 outstr[out_index] = myitems[index_from].to_upper
1119 out_index += 1
1120 index_from += 1
1121 end
1122
1123 outstr[self.length] = '\0'
1124
1125 return outstr.to_s_with_length(self.length)
1126 end
1127
1128 redef fun to_lower
1129 do
1130 var outstr = new NativeString(self.length + 1)
1131 var out_index = 0
1132
1133 var myitems = self.items
1134 var index_from = self.index_from
1135 var max = self.index_to
1136
1137 while index_from <= max do
1138 outstr[out_index] = myitems[index_from].to_lower
1139 out_index += 1
1140 index_from += 1
1141 end
1142
1143 outstr[self.length] = '\0'
1144
1145 return outstr.to_s_with_length(self.length)
1146 end
1147
1148 redef fun output
1149 do
1150 var i = self.index_from
1151 var imax = self.index_to
1152 while i <= imax do
1153 items[i].output
1154 i += 1
1155 end
1156 end
1157
1158 ##################################################
1159 # String Specific Methods #
1160 ##################################################
1161
1162 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1163 do
1164 self.items = items
1165 length = len
1166 index_from = from
1167 index_to = to
1168 end
1169
1170 redef fun to_cstring: NativeString
1171 do
1172 if real_items != null then
1173 return real_items.as(not null)
1174 else
1175 var newItems = new NativeString(length + 1)
1176 self.items.copy_to(newItems, length, index_from, 0)
1177 newItems[length] = '\0'
1178 self.real_items = newItems
1179 return newItems
1180 end
1181 end
1182
1183 redef fun ==(other)
1184 do
1185 if not other isa FlatString then return super
1186
1187 if self.object_id == other.object_id then return true
1188
1189 var my_length = length
1190
1191 if other.length != my_length then return false
1192
1193 var my_index = index_from
1194 var its_index = other.index_from
1195
1196 var last_iteration = my_index + my_length
1197
1198 var itsitems = other.items
1199 var myitems = self.items
1200
1201 while my_index < last_iteration do
1202 if myitems[my_index] != itsitems[its_index] then return false
1203 my_index += 1
1204 its_index += 1
1205 end
1206
1207 return true
1208 end
1209
1210 redef fun <(other)
1211 do
1212 if not other isa FlatString then return super
1213
1214 if self.object_id == other.object_id then return false
1215
1216 var my_curr_char : Char
1217 var its_curr_char : Char
1218
1219 var curr_id_self = self.index_from
1220 var curr_id_other = other.index_from
1221
1222 var my_items = self.items
1223 var its_items = other.items
1224
1225 var my_length = self.length
1226 var its_length = other.length
1227
1228 var max_iterations = curr_id_self + my_length
1229
1230 while curr_id_self < max_iterations do
1231 my_curr_char = my_items[curr_id_self]
1232 its_curr_char = its_items[curr_id_other]
1233
1234 if my_curr_char != its_curr_char then
1235 if my_curr_char < its_curr_char then return true
1236 return false
1237 end
1238
1239 curr_id_self += 1
1240 curr_id_other += 1
1241 end
1242
1243 return my_length < its_length
1244 end
1245
1246 redef fun +(s)
1247 do
1248 var my_length = self.length
1249 var its_length = s.length
1250
1251 var total_length = my_length + its_length
1252
1253 var target_string = new NativeString(my_length + its_length + 1)
1254
1255 self.items.copy_to(target_string, my_length, index_from, 0)
1256 if s isa FlatString then
1257 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1258 else if s isa FlatBuffer then
1259 s.items.copy_to(target_string, its_length, 0, my_length)
1260 else
1261 var curr_pos = my_length
1262 for i in [0..s.length[ do
1263 var c = s.chars[i]
1264 target_string[curr_pos] = c
1265 curr_pos += 1
1266 end
1267 end
1268
1269 target_string[total_length] = '\0'
1270
1271 return target_string.to_s_with_length(total_length)
1272 end
1273
1274 redef fun *(i)
1275 do
1276 assert i >= 0
1277
1278 var my_length = self.length
1279
1280 var final_length = my_length * i
1281
1282 var my_items = self.items
1283
1284 var target_string = new NativeString(final_length + 1)
1285
1286 target_string[final_length] = '\0'
1287
1288 var current_last = 0
1289
1290 for iteration in [1 .. i] do
1291 my_items.copy_to(target_string, my_length, 0, current_last)
1292 current_last += my_length
1293 end
1294
1295 return target_string.to_s_with_length(final_length)
1296 end
1297
1298 redef fun hash
1299 do
1300 if hash_cache == null then
1301 # djb2 hash algorithm
1302 var h = 5381
1303 var i = index_from
1304
1305 var myitems = items
1306
1307 while i <= index_to do
1308 h = h.lshift(5) + h + myitems[i].ascii
1309 i += 1
1310 end
1311
1312 hash_cache = h
1313 end
1314
1315 return hash_cache.as(not null)
1316 end
1317
1318 redef fun substrings do return new FlatSubstringsIter(self)
1319 end
1320
1321 private class FlatStringReverseIterator
1322 super IndexedIterator[Char]
1323
1324 var target: FlatString
1325
1326 var target_items: NativeString
1327
1328 var curr_pos: Int
1329
1330 init with_pos(tgt: FlatString, pos: Int)
1331 do
1332 target = tgt
1333 target_items = tgt.items
1334 curr_pos = pos + tgt.index_from
1335 end
1336
1337 redef fun is_ok do return curr_pos >= target.index_from
1338
1339 redef fun item do return target_items[curr_pos]
1340
1341 redef fun next do curr_pos -= 1
1342
1343 redef fun index do return curr_pos - target.index_from
1344
1345 end
1346
1347 private class FlatStringIterator
1348 super IndexedIterator[Char]
1349
1350 var target: FlatString
1351
1352 var target_items: NativeString
1353
1354 var curr_pos: Int
1355
1356 init with_pos(tgt: FlatString, pos: Int)
1357 do
1358 target = tgt
1359 target_items = tgt.items
1360 curr_pos = pos + target.index_from
1361 end
1362
1363 redef fun is_ok do return curr_pos <= target.index_to
1364
1365 redef fun item do return target_items[curr_pos]
1366
1367 redef fun next do curr_pos += 1
1368
1369 redef fun index do return curr_pos - target.index_from
1370
1371 end
1372
1373 private class FlatStringCharView
1374 super StringCharView
1375
1376 redef type SELFTYPE: FlatString
1377
1378 redef fun [](index)
1379 do
1380 # Check that the index (+ index_from) is not larger than indexTo
1381 # In other terms, if the index is valid
1382 assert index >= 0
1383 var target = self.target
1384 assert (index + target.index_from) <= target.index_to
1385 return target.items[index + target.index_from]
1386 end
1387
1388 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1389
1390 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1391
1392 end
1393
1394 # A mutable sequence of characters.
1395 abstract class Buffer
1396 super Text
1397
1398 redef type SELFTYPE: Buffer
1399
1400 # Specific implementations MUST set this to `true` in order to invalidate caches
1401 protected var is_dirty = true
1402
1403 # Copy-On-Write flag
1404 #
1405 # If the `Buffer` was to_s'd, the next in-place altering
1406 # operation will cause the current `Buffer` to be re-allocated.
1407 #
1408 # The flag will then be set at `false`.
1409 protected var written = false
1410
1411 # Modifies the char contained at pos `index`
1412 #
1413 # DEPRECATED : Use self.chars.[]= instead
1414 fun []=(index: Int, item: Char) is abstract
1415
1416 # Adds a char `c` at the end of self
1417 #
1418 # DEPRECATED : Use self.chars.add instead
1419 fun add(c: Char) is abstract
1420
1421 # Clears the buffer
1422 #
1423 # var b = new FlatBuffer
1424 # b.append "hello"
1425 # assert not b.is_empty
1426 # b.clear
1427 # assert b.is_empty
1428 fun clear is abstract
1429
1430 # Enlarges the subsequent array containing the chars of self
1431 fun enlarge(cap: Int) is abstract
1432
1433 # Adds the content of text `s` at the end of self
1434 #
1435 # var b = new FlatBuffer
1436 # b.append "hello"
1437 # b.append "world"
1438 # assert b == "helloworld"
1439 fun append(s: Text) is abstract
1440
1441 # `self` is appended in such a way that `self` is repeated `r` times
1442 #
1443 # var b = new FlatBuffer
1444 # b.append "hello"
1445 # b.times 3
1446 # assert b == "hellohellohello"
1447 fun times(r: Int) is abstract
1448
1449 # Reverses itself in-place
1450 #
1451 # var b = new FlatBuffer
1452 # b.append("hello")
1453 # b.reverse
1454 # assert b == "olleh"
1455 fun reverse is abstract
1456
1457 # Changes each lower-case char in `self` by its upper-case variant
1458 #
1459 # var b = new FlatBuffer
1460 # b.append("Hello World!")
1461 # b.upper
1462 # assert b == "HELLO WORLD!"
1463 fun upper is abstract
1464
1465 # Changes each upper-case char in `self` by its lower-case variant
1466 #
1467 # var b = new FlatBuffer
1468 # b.append("Hello World!")
1469 # b.lower
1470 # assert b == "hello world!"
1471 fun lower is abstract
1472
1473 # Capitalizes each word in `self`
1474 #
1475 # Letters that follow a letter are lowercased
1476 # Letters that follow a non-letter are upcased.
1477 #
1478 # SEE: `Char::is_letter` for the definition of a letter.
1479 #
1480 # var b = new FlatBuffer.from("jAVAsCriPt")
1481 # b.capitalize
1482 # assert b == "Javascript"
1483 # b = new FlatBuffer.from("i am root")
1484 # b.capitalize
1485 # assert b == "I Am Root"
1486 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1487 # b.capitalize
1488 # assert b == "Ab_C -Ab0C Ab\nC"
1489 fun capitalize do
1490 if length == 0 then return
1491 var c = self[0].to_upper
1492 self[0] = c
1493 var prev = c
1494 for i in [1 .. length[ do
1495 prev = c
1496 c = self[i]
1497 if prev.is_letter then
1498 self[i] = c.to_lower
1499 else
1500 self[i] = c.to_upper
1501 end
1502 end
1503 end
1504
1505 redef fun hash
1506 do
1507 if is_dirty then hash_cache = null
1508 return super
1509 end
1510
1511 # In Buffers, the internal sequence of character is mutable
1512 # Thus, `chars` can be used to modify the buffer.
1513 redef fun chars: Sequence[Char] is abstract
1514 end
1515
1516 # Mutable strings of characters.
1517 class FlatBuffer
1518 super FlatText
1519 super Buffer
1520
1521 redef type SELFTYPE: FlatBuffer
1522
1523 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1524
1525 private var capacity: Int = 0
1526
1527 redef fun substrings do return new FlatSubstringsIter(self)
1528
1529 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1530 #
1531 # This happens when an operation modifies the current `Buffer` and
1532 # the Copy-On-Write flag `written` is set at true.
1533 private fun reset do
1534 var nns = new NativeString(capacity)
1535 items.copy_to(nns, length, 0, 0)
1536 items = nns
1537 written = false
1538 end
1539
1540 redef fun [](index)
1541 do
1542 assert index >= 0
1543 assert index < length
1544 return items[index]
1545 end
1546
1547 redef fun []=(index, item)
1548 do
1549 is_dirty = true
1550 if index == length then
1551 add(item)
1552 return
1553 end
1554 if written then reset
1555 assert index >= 0 and index < length
1556 items[index] = item
1557 end
1558
1559 redef fun add(c)
1560 do
1561 is_dirty = true
1562 if capacity <= length then enlarge(length + 5)
1563 items[length] = c
1564 length += 1
1565 end
1566
1567 redef fun clear do
1568 is_dirty = true
1569 if written then reset
1570 length = 0
1571 end
1572
1573 redef fun empty do return new FlatBuffer
1574
1575 redef fun enlarge(cap)
1576 do
1577 var c = capacity
1578 if cap <= c then return
1579 while c <= cap do c = c * 2 + 2
1580 # The COW flag can be set at false here, since
1581 # it does a copy of the current `Buffer`
1582 written = false
1583 var a = new NativeString(c+1)
1584 if length > 0 then items.copy_to(a, length, 0, 0)
1585 items = a
1586 capacity = c
1587 end
1588
1589 redef fun to_s: String
1590 do
1591 written = true
1592 if length == 0 then items = new NativeString(1)
1593 return new FlatString.with_infos(items, length, 0, length - 1)
1594 end
1595
1596 redef fun to_cstring
1597 do
1598 if is_dirty then
1599 var new_native = new NativeString(length + 1)
1600 new_native[length] = '\0'
1601 if length > 0 then items.copy_to(new_native, length, 0, 0)
1602 real_items = new_native
1603 is_dirty = false
1604 end
1605 return real_items.as(not null)
1606 end
1607
1608 # Create a new empty string.
1609 init do end
1610
1611 # Create a new string copied from `s`.
1612 init from(s: Text)
1613 do
1614 capacity = s.length + 1
1615 length = s.length
1616 items = new NativeString(capacity)
1617 if s isa FlatString then
1618 s.items.copy_to(items, length, s.index_from, 0)
1619 else if s isa FlatBuffer then
1620 s.items.copy_to(items, length, 0, 0)
1621 else
1622 var curr_pos = 0
1623 for i in [0..s.length[ do
1624 var c = s.chars[i]
1625 items[curr_pos] = c
1626 curr_pos += 1
1627 end
1628 end
1629 end
1630
1631 # Create a new empty string with a given capacity.
1632 init with_capacity(cap: Int)
1633 do
1634 assert cap >= 0
1635 # _items = new NativeString.calloc(cap)
1636 items = new NativeString(cap+1)
1637 capacity = cap
1638 length = 0
1639 end
1640
1641 redef fun append(s)
1642 do
1643 if s.is_empty then return
1644 is_dirty = true
1645 var sl = s.length
1646 if capacity < length + sl then enlarge(length + sl)
1647 if s isa FlatString then
1648 s.items.copy_to(items, sl, s.index_from, length)
1649 else if s isa FlatBuffer then
1650 s.items.copy_to(items, sl, 0, length)
1651 else
1652 var curr_pos = self.length
1653 for i in [0..s.length[ do
1654 var c = s.chars[i]
1655 items[curr_pos] = c
1656 curr_pos += 1
1657 end
1658 end
1659 length += sl
1660 end
1661
1662 # Copies the content of self in `dest`
1663 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1664 do
1665 var self_chars = self.chars
1666 var dest_chars = dest.chars
1667 for i in [0..len-1] do
1668 dest_chars[new_start+i] = self_chars[start+i]
1669 end
1670 end
1671
1672 redef fun substring(from, count)
1673 do
1674 assert count >= 0
1675 count += from
1676 if from < 0 then from = 0
1677 if count > length then count = length
1678 if from < count then
1679 var r = new FlatBuffer.with_capacity(count - from)
1680 while from < count do
1681 r.chars.push(items[from])
1682 from += 1
1683 end
1684 return r
1685 else
1686 return new FlatBuffer
1687 end
1688 end
1689
1690 redef fun reverse
1691 do
1692 written = false
1693 var ns = new NativeString(capacity)
1694 var si = length - 1
1695 var ni = 0
1696 var it = items
1697 while si >= 0 do
1698 ns[ni] = it[si]
1699 ni += 1
1700 si -= 1
1701 end
1702 items = ns
1703 end
1704
1705 redef fun times(repeats)
1706 do
1707 var x = new FlatString.with_infos(items, length, 0, length - 1)
1708 for i in [1..repeats[ do
1709 append(x)
1710 end
1711 end
1712
1713 redef fun upper
1714 do
1715 if written then reset
1716 var it = items
1717 var id = length - 1
1718 while id >= 0 do
1719 it[id] = it[id].to_upper
1720 id -= 1
1721 end
1722 end
1723
1724 redef fun lower
1725 do
1726 if written then reset
1727 var it = items
1728 var id = length - 1
1729 while id >= 0 do
1730 it[id] = it[id].to_lower
1731 id -= 1
1732 end
1733 end
1734 end
1735
1736 private class FlatBufferReverseIterator
1737 super IndexedIterator[Char]
1738
1739 var target: FlatBuffer
1740
1741 var target_items: NativeString
1742
1743 var curr_pos: Int
1744
1745 init with_pos(tgt: FlatBuffer, pos: Int)
1746 do
1747 target = tgt
1748 if tgt.length > 0 then target_items = tgt.items
1749 curr_pos = pos
1750 end
1751
1752 redef fun index do return curr_pos
1753
1754 redef fun is_ok do return curr_pos >= 0
1755
1756 redef fun item do return target_items[curr_pos]
1757
1758 redef fun next do curr_pos -= 1
1759
1760 end
1761
1762 private class FlatBufferCharView
1763 super BufferCharView
1764
1765 redef type SELFTYPE: FlatBuffer
1766
1767 redef fun [](index) do return target.items[index]
1768
1769 redef fun []=(index, item)
1770 do
1771 assert index >= 0 and index <= length
1772 if index == length then
1773 add(item)
1774 return
1775 end
1776 target.items[index] = item
1777 end
1778
1779 redef fun push(c)
1780 do
1781 target.add(c)
1782 end
1783
1784 redef fun add(c)
1785 do
1786 target.add(c)
1787 end
1788
1789 fun enlarge(cap: Int)
1790 do
1791 target.enlarge(cap)
1792 end
1793
1794 redef fun append(s)
1795 do
1796 var s_length = s.length
1797 if target.capacity < s.length then enlarge(s_length + target.length)
1798 end
1799
1800 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1801
1802 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1803
1804 end
1805
1806 private class FlatBufferIterator
1807 super IndexedIterator[Char]
1808
1809 var target: FlatBuffer
1810
1811 var target_items: NativeString
1812
1813 var curr_pos: Int
1814
1815 init with_pos(tgt: FlatBuffer, pos: Int)
1816 do
1817 target = tgt
1818 if tgt.length > 0 then target_items = tgt.items
1819 curr_pos = pos
1820 end
1821
1822 redef fun index do return curr_pos
1823
1824 redef fun is_ok do return curr_pos < target.length
1825
1826 redef fun item do return target_items[curr_pos]
1827
1828 redef fun next do curr_pos += 1
1829
1830 end
1831
1832 ###############################################################################
1833 # Refinement #
1834 ###############################################################################
1835
1836 redef class Object
1837 # User readable representation of `self`.
1838 fun to_s: String do return inspect
1839
1840 # The class name of the object in NativeString format.
1841 private fun native_class_name: NativeString is intern
1842
1843 # The class name of the object.
1844 #
1845 # assert 5.class_name == "Int"
1846 fun class_name: String do return native_class_name.to_s
1847
1848 # Developer readable representation of `self`.
1849 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1850 fun inspect: String
1851 do
1852 return "<{inspect_head}>"
1853 end
1854
1855 # Return "CLASSNAME:#OBJECTID".
1856 # This function is mainly used with the redefinition of the inspect method
1857 protected fun inspect_head: String
1858 do
1859 return "{class_name}:#{object_id.to_hex}"
1860 end
1861 end
1862
1863 redef class Bool
1864 # assert true.to_s == "true"
1865 # assert false.to_s == "false"
1866 redef fun to_s
1867 do
1868 if self then
1869 return once "true"
1870 else
1871 return once "false"
1872 end
1873 end
1874 end
1875
1876 redef class Int
1877
1878 # Wrapper of strerror C function
1879 private fun strerror_ext: NativeString is extern `{
1880 return strerror(recv);
1881 `}
1882
1883 # Returns a string describing error number
1884 fun strerror: String do return strerror_ext.to_s
1885
1886 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1887 # assume < to_c max const of char
1888 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1889 do
1890 var n: Int
1891 # Sign
1892 if self < 0 then
1893 n = - self
1894 s.chars[0] = '-'
1895 else if self == 0 then
1896 s.chars[0] = '0'
1897 return
1898 else
1899 n = self
1900 end
1901 # Fill digits
1902 var pos = digit_count(base) - 1
1903 while pos >= 0 and n > 0 do
1904 s.chars[pos] = (n % base).to_c
1905 n = n / base # /
1906 pos -= 1
1907 end
1908 end
1909
1910 # C function to convert an nit Int to a NativeString (char*)
1911 private fun native_int_to_s: NativeString is extern "native_int_to_s"
1912
1913 # return displayable int in base 10 and signed
1914 #
1915 # assert 1.to_s == "1"
1916 # assert (-123).to_s == "-123"
1917 redef fun to_s do
1918 return native_int_to_s.to_s
1919 end
1920
1921 # return displayable int in hexadecimal
1922 #
1923 # assert 1.to_hex == "1"
1924 # assert (-255).to_hex == "-ff"
1925 fun to_hex: String do return to_base(16,false)
1926
1927 # return displayable int in base base and signed
1928 fun to_base(base: Int, signed: Bool): String
1929 do
1930 var l = digit_count(base)
1931 var s = new FlatBuffer.from(" " * l)
1932 fill_buffer(s, base, signed)
1933 return s.to_s
1934 end
1935 end
1936
1937 redef class Float
1938 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1939 #
1940 # assert 12.34.to_s == "12.34"
1941 # assert (-0120.030).to_s == "-120.03"
1942 #
1943 # see `to_precision` for a custom precision.
1944 redef fun to_s do
1945 var str = to_precision( 3 )
1946 if is_inf != 0 or is_nan then return str
1947 var len = str.length
1948 for i in [0..len-1] do
1949 var j = len-1-i
1950 var c = str.chars[j]
1951 if c == '0' then
1952 continue
1953 else if c == '.' then
1954 return str.substring( 0, j+2 )
1955 else
1956 return str.substring( 0, j+1 )
1957 end
1958 end
1959 return str
1960 end
1961
1962 # `String` representation of `self` with the given number of `decimals`
1963 #
1964 # assert 12.345.to_precision(0) == "12"
1965 # assert 12.345.to_precision(3) == "12.345"
1966 # assert (-12.345).to_precision(3) == "-12.345"
1967 # assert (-0.123).to_precision(3) == "-0.123"
1968 # assert 0.999.to_precision(2) == "1.00"
1969 # assert 0.999.to_precision(4) == "0.9990"
1970 fun to_precision(decimals: Int): String
1971 do
1972 if is_nan then return "nan"
1973
1974 var isinf = self.is_inf
1975 if isinf == 1 then
1976 return "inf"
1977 else if isinf == -1 then
1978 return "-inf"
1979 end
1980
1981 if decimals == 0 then return self.to_i.to_s
1982 var f = self
1983 for i in [0..decimals[ do f = f * 10.0
1984 if self > 0.0 then
1985 f = f + 0.5
1986 else
1987 f = f - 0.5
1988 end
1989 var i = f.to_i
1990 if i == 0 then return "0." + "0"*decimals
1991
1992 # Prepare both parts of the float, before and after the "."
1993 var s = i.abs.to_s
1994 var sl = s.length
1995 var p1
1996 var p2
1997 if sl > decimals then
1998 # Has something before the "."
1999 p1 = s.substring(0, sl-decimals)
2000 p2 = s.substring(sl-decimals, decimals)
2001 else
2002 p1 = "0"
2003 p2 = "0"*(decimals-sl) + s
2004 end
2005
2006 if i < 0 then p1 = "-" + p1
2007
2008 return p1 + "." + p2
2009 end
2010
2011 # `self` representation with `nb` digits after the '.'.
2012 #
2013 # assert 12.345.to_precision_native(1) == "12.3"
2014 # assert 12.345.to_precision_native(2) == "12.35"
2015 # assert 12.345.to_precision_native(3) == "12.345"
2016 # assert 12.345.to_precision_native(4) == "12.3450"
2017 fun to_precision_native(nb: Int): String import NativeString.to_s `{
2018 int size;
2019 char *str;
2020
2021 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
2022 str = malloc(size + 1);
2023 sprintf(str, "%.*f", (int)nb, recv );
2024
2025 return NativeString_to_s( str );
2026 `}
2027 end
2028
2029 redef class Char
2030 # assert 'x'.to_s == "x"
2031 redef fun to_s
2032 do
2033 var s = new FlatBuffer.with_capacity(1)
2034 s.chars[0] = self
2035 return s.to_s
2036 end
2037
2038 # Returns true if the char is a numerical digit
2039 #
2040 # assert '0'.is_numeric
2041 # assert '9'.is_numeric
2042 # assert not 'a'.is_numeric
2043 # assert not '?'.is_numeric
2044 fun is_numeric: Bool
2045 do
2046 return self >= '0' and self <= '9'
2047 end
2048
2049 # Returns true if the char is an alpha digit
2050 #
2051 # assert 'a'.is_alpha
2052 # assert 'Z'.is_alpha
2053 # assert not '0'.is_alpha
2054 # assert not '?'.is_alpha
2055 fun is_alpha: Bool
2056 do
2057 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2058 end
2059
2060 # Returns true if the char is an alpha or a numeric digit
2061 #
2062 # assert 'a'.is_alphanumeric
2063 # assert 'Z'.is_alphanumeric
2064 # assert '0'.is_alphanumeric
2065 # assert '9'.is_alphanumeric
2066 # assert not '?'.is_alphanumeric
2067 fun is_alphanumeric: Bool
2068 do
2069 return self.is_numeric or self.is_alpha
2070 end
2071 end
2072
2073 redef class Collection[E]
2074 # Concatenate elements.
2075 redef fun to_s
2076 do
2077 var s = new FlatBuffer
2078 for e in self do if e != null then s.append(e.to_s)
2079 return s.to_s
2080 end
2081
2082 # Concatenate and separate each elements with `sep`.
2083 #
2084 # assert [1, 2, 3].join(":") == "1:2:3"
2085 # assert [1..3].join(":") == "1:2:3"
2086 fun join(sep: Text): String
2087 do
2088 if is_empty then return ""
2089
2090 var s = new FlatBuffer # Result
2091
2092 # Concat first item
2093 var i = iterator
2094 var e = i.item
2095 if e != null then s.append(e.to_s)
2096
2097 # Concat other items
2098 i.next
2099 while i.is_ok do
2100 s.append(sep)
2101 e = i.item
2102 if e != null then s.append(e.to_s)
2103 i.next
2104 end
2105 return s.to_s
2106 end
2107 end
2108
2109 redef class Array[E]
2110
2111 # Fast implementation
2112 redef fun to_s
2113 do
2114 var l = length
2115 if l == 0 then return ""
2116 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2117 var its = _items
2118 var na = new NativeArray[String](l)
2119 var i = 0
2120 var sl = 0
2121 var mypos = 0
2122 while i < l do
2123 var itsi = its[i]
2124 if itsi == null then
2125 i += 1
2126 continue
2127 end
2128 var tmp = itsi.to_s
2129 sl += tmp.length
2130 na[mypos] = tmp
2131 i += 1
2132 mypos += 1
2133 end
2134 var ns = new NativeString(sl + 1)
2135 ns[sl] = '\0'
2136 i = 0
2137 var off = 0
2138 while i < mypos do
2139 var tmp = na[i]
2140 var tpl = tmp.length
2141 if tmp isa FlatString then
2142 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2143 off += tpl
2144 else
2145 for j in tmp.substrings do
2146 var s = j.as(FlatString)
2147 var slen = s.length
2148 s.items.copy_to(ns, slen, s.index_from, off)
2149 off += slen
2150 end
2151 end
2152 i += 1
2153 end
2154 return ns.to_s_with_length(sl)
2155 end
2156 end
2157
2158 redef class Map[K,V]
2159 # Concatenate couple of 'key value'.
2160 # key and value are separated by `couple_sep`.
2161 # each couple is separated each couple with `sep`.
2162 #
2163 # var m = new ArrayMap[Int, String]
2164 # m[1] = "one"
2165 # m[10] = "ten"
2166 # assert m.join("; ", "=") == "1=one; 10=ten"
2167 fun join(sep: String, couple_sep: String): String
2168 do
2169 if is_empty then return ""
2170
2171 var s = new FlatBuffer # Result
2172
2173 # Concat first item
2174 var i = iterator
2175 var k = i.key
2176 var e = i.item
2177 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2178
2179 # Concat other items
2180 i.next
2181 while i.is_ok do
2182 s.append(sep)
2183 k = i.key
2184 e = i.item
2185 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2186 i.next
2187 end
2188 return s.to_s
2189 end
2190 end
2191
2192 ###############################################################################
2193 # Native classes #
2194 ###############################################################################
2195
2196 # Native strings are simple C char *
2197 extern class NativeString `{ char* `}
2198 # Creates a new NativeString with a capacity of `length`
2199 new(length: Int) is intern
2200
2201 # Get char at `index`.
2202 fun [](index: Int): Char is intern
2203
2204 # Set char `item` at index.
2205 fun []=(index: Int, item: Char) is intern
2206
2207 # Copy `self` to `dest`.
2208 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2209
2210 # Position of the first nul character.
2211 fun cstring_length: Int
2212 do
2213 var l = 0
2214 while self[l] != '\0' do l += 1
2215 return l
2216 end
2217
2218 # Parse `self` as an Int.
2219 fun atoi: Int is intern
2220
2221 # Parse `self` as a Float.
2222 fun atof: Float is extern "atof"
2223
2224 redef fun to_s
2225 do
2226 return to_s_with_length(cstring_length)
2227 end
2228
2229 # Returns `self` as a String of `length`.
2230 fun to_s_with_length(length: Int): FlatString
2231 do
2232 assert length >= 0
2233 var str = new FlatString.with_infos(self, length, 0, length - 1)
2234 return str
2235 end
2236
2237 # Returns `self` as a new String.
2238 fun to_s_with_copy: FlatString
2239 do
2240 var length = cstring_length
2241 var new_self = new NativeString(length + 1)
2242 copy_to(new_self, length, 0, 0)
2243 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2244 new_self[length] = '\0'
2245 str.real_items = new_self
2246 return str
2247 end
2248 end
2249
2250 redef class Sys
2251 private var args_cache: nullable Sequence[String]
2252
2253 # The arguments of the program as given by the OS
2254 fun program_args: Sequence[String]
2255 do
2256 if _args_cache == null then init_args
2257 return _args_cache.as(not null)
2258 end
2259
2260 # The name of the program as given by the OS
2261 fun program_name: String
2262 do
2263 return native_argv(0).to_s
2264 end
2265
2266 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2267 private fun init_args
2268 do
2269 var argc = native_argc
2270 var args = new Array[String].with_capacity(0)
2271 var i = 1
2272 while i < argc do
2273 args[i-1] = native_argv(i).to_s
2274 i += 1
2275 end
2276 _args_cache = args
2277 end
2278
2279 # First argument of the main C function.
2280 private fun native_argc: Int is intern
2281
2282 # Second argument of the main C function.
2283 private fun native_argv(i: Int): NativeString is intern
2284 end
2285
2286 # Comparator that efficienlty use `to_s` to compare things
2287 #
2288 # The comparaison call `to_s` on object and use the result to order things.
2289 #
2290 # var a = [1, 2, 3, 10, 20]
2291 # (new CachedAlphaComparator).sort(a)
2292 # assert a == [1, 10, 2, 20, 3]
2293 #
2294 # Internally the result of `to_s` is cached in a HashMap to counter
2295 # uneficient implementation of `to_s`.
2296 #
2297 # Note: it caching is not usefull, see `alpha_comparator`
2298 class CachedAlphaComparator
2299 super Comparator
2300 redef type COMPARED: Object
2301
2302 private var cache = new HashMap[Object, String]
2303
2304 private fun do_to_s(a: Object): String do
2305 if cache.has_key(a) then return cache[a]
2306 var res = a.to_s
2307 cache[a] = res
2308 return res
2309 end
2310
2311 redef fun compare(a, b) do
2312 return do_to_s(a) <=> do_to_s(b)
2313 end
2314 end
2315
2316 # see `alpha_comparator`
2317 private class AlphaComparator
2318 super Comparator
2319 redef fun compare(a, b) do return a.to_s <=> b.to_s
2320 end
2321
2322 # Stateless comparator that naively use `to_s` to compare things.
2323 #
2324 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2325 # on a single instace. See `CachedAlphaComparator` as an alternative.
2326 #
2327 # var a = [1, 2, 3, 10, 20]
2328 # alpha_comparator.sort(a)
2329 # assert a == [1, 10, 2, 20, 3]
2330 fun alpha_comparator: Comparator do return once new AlphaComparator
2331
2332 # The arguments of the program as given by the OS
2333 fun args: Sequence[String]
2334 do
2335 return sys.program_args
2336 end