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