lib/string: document FlatString::with_infos
[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 `Reader::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): String
443 do
444 var diff = length - self.length
445 if diff <= 0 then return to_s
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: String
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 is fixed
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 new_from = index_from + from
1096
1097 if (new_from + count) > index_to then
1098 var new_len = index_to - new_from + 1
1099 if new_len <= 0 then return empty
1100 return new FlatString.with_infos(items, new_len, new_from, index_to)
1101 end
1102
1103 if count <= 0 then return empty
1104
1105 var to = new_from + count - 1
1106
1107 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1108 end
1109
1110 redef fun empty do return "".as(FlatString)
1111
1112 redef fun to_upper
1113 do
1114 var outstr = new NativeString(self.length + 1)
1115 var out_index = 0
1116
1117 var myitems = self.items
1118 var index_from = self.index_from
1119 var max = self.index_to
1120
1121 while index_from <= max do
1122 outstr[out_index] = myitems[index_from].to_upper
1123 out_index += 1
1124 index_from += 1
1125 end
1126
1127 outstr[self.length] = '\0'
1128
1129 return outstr.to_s_with_length(self.length)
1130 end
1131
1132 redef fun to_lower
1133 do
1134 var outstr = new NativeString(self.length + 1)
1135 var out_index = 0
1136
1137 var myitems = self.items
1138 var index_from = self.index_from
1139 var max = self.index_to
1140
1141 while index_from <= max do
1142 outstr[out_index] = myitems[index_from].to_lower
1143 out_index += 1
1144 index_from += 1
1145 end
1146
1147 outstr[self.length] = '\0'
1148
1149 return outstr.to_s_with_length(self.length)
1150 end
1151
1152 redef fun output
1153 do
1154 var i = self.index_from
1155 var imax = self.index_to
1156 while i <= imax do
1157 items[i].output
1158 i += 1
1159 end
1160 end
1161
1162 ##################################################
1163 # String Specific Methods #
1164 ##################################################
1165
1166 # Low-level creation of a new string with given data.
1167 #
1168 # `items` will be used as is, without copy, to retrieve the characters of the string.
1169 # Aliasing issues is the responsibility of the caller.
1170 private init with_infos(items: NativeString, length: Int, from: Int, to: Int)
1171 do
1172 self.items = items
1173 self.length = length
1174 index_from = from
1175 index_to = to
1176 end
1177
1178 redef fun to_cstring: NativeString
1179 do
1180 if real_items != null then
1181 return real_items.as(not null)
1182 else
1183 var newItems = new NativeString(length + 1)
1184 self.items.copy_to(newItems, length, index_from, 0)
1185 newItems[length] = '\0'
1186 self.real_items = newItems
1187 return newItems
1188 end
1189 end
1190
1191 redef fun ==(other)
1192 do
1193 if not other isa FlatString then return super
1194
1195 if self.object_id == other.object_id then return true
1196
1197 var my_length = length
1198
1199 if other.length != my_length then return false
1200
1201 var my_index = index_from
1202 var its_index = other.index_from
1203
1204 var last_iteration = my_index + my_length
1205
1206 var itsitems = other.items
1207 var myitems = self.items
1208
1209 while my_index < last_iteration do
1210 if myitems[my_index] != itsitems[its_index] then return false
1211 my_index += 1
1212 its_index += 1
1213 end
1214
1215 return true
1216 end
1217
1218 redef fun <(other)
1219 do
1220 if not other isa FlatString then return super
1221
1222 if self.object_id == other.object_id then return false
1223
1224 var my_curr_char : Char
1225 var its_curr_char : Char
1226
1227 var curr_id_self = self.index_from
1228 var curr_id_other = other.index_from
1229
1230 var my_items = self.items
1231 var its_items = other.items
1232
1233 var my_length = self.length
1234 var its_length = other.length
1235
1236 var max_iterations = curr_id_self + my_length
1237
1238 while curr_id_self < max_iterations do
1239 my_curr_char = my_items[curr_id_self]
1240 its_curr_char = its_items[curr_id_other]
1241
1242 if my_curr_char != its_curr_char then
1243 if my_curr_char < its_curr_char then return true
1244 return false
1245 end
1246
1247 curr_id_self += 1
1248 curr_id_other += 1
1249 end
1250
1251 return my_length < its_length
1252 end
1253
1254 redef fun +(s)
1255 do
1256 var my_length = self.length
1257 var its_length = s.length
1258
1259 var total_length = my_length + its_length
1260
1261 var target_string = new NativeString(my_length + its_length + 1)
1262
1263 self.items.copy_to(target_string, my_length, index_from, 0)
1264 if s isa FlatString then
1265 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1266 else if s isa FlatBuffer then
1267 s.items.copy_to(target_string, its_length, 0, my_length)
1268 else
1269 var curr_pos = my_length
1270 for i in [0..s.length[ do
1271 var c = s.chars[i]
1272 target_string[curr_pos] = c
1273 curr_pos += 1
1274 end
1275 end
1276
1277 target_string[total_length] = '\0'
1278
1279 return target_string.to_s_with_length(total_length)
1280 end
1281
1282 redef fun *(i)
1283 do
1284 assert i >= 0
1285
1286 var my_length = self.length
1287
1288 var final_length = my_length * i
1289
1290 var my_items = self.items
1291
1292 var target_string = new NativeString(final_length + 1)
1293
1294 target_string[final_length] = '\0'
1295
1296 var current_last = 0
1297
1298 for iteration in [1 .. i] do
1299 my_items.copy_to(target_string, my_length, 0, current_last)
1300 current_last += my_length
1301 end
1302
1303 return target_string.to_s_with_length(final_length)
1304 end
1305
1306 redef fun hash
1307 do
1308 if hash_cache == null then
1309 # djb2 hash algorithm
1310 var h = 5381
1311 var i = index_from
1312
1313 var myitems = items
1314
1315 while i <= index_to do
1316 h = h.lshift(5) + h + myitems[i].ascii
1317 i += 1
1318 end
1319
1320 hash_cache = h
1321 end
1322
1323 return hash_cache.as(not null)
1324 end
1325
1326 redef fun substrings do return new FlatSubstringsIter(self)
1327 end
1328
1329 private class FlatStringReverseIterator
1330 super IndexedIterator[Char]
1331
1332 var target: FlatString
1333
1334 var target_items: NativeString
1335
1336 var curr_pos: Int
1337
1338 init with_pos(tgt: FlatString, pos: Int)
1339 do
1340 target = tgt
1341 target_items = tgt.items
1342 curr_pos = pos + tgt.index_from
1343 end
1344
1345 redef fun is_ok do return curr_pos >= target.index_from
1346
1347 redef fun item do return target_items[curr_pos]
1348
1349 redef fun next do curr_pos -= 1
1350
1351 redef fun index do return curr_pos - target.index_from
1352
1353 end
1354
1355 private class FlatStringIterator
1356 super IndexedIterator[Char]
1357
1358 var target: FlatString
1359
1360 var target_items: NativeString
1361
1362 var curr_pos: Int
1363
1364 init with_pos(tgt: FlatString, pos: Int)
1365 do
1366 target = tgt
1367 target_items = tgt.items
1368 curr_pos = pos + target.index_from
1369 end
1370
1371 redef fun is_ok do return curr_pos <= target.index_to
1372
1373 redef fun item do return target_items[curr_pos]
1374
1375 redef fun next do curr_pos += 1
1376
1377 redef fun index do return curr_pos - target.index_from
1378
1379 end
1380
1381 private class FlatStringCharView
1382 super StringCharView
1383
1384 redef type SELFTYPE: FlatString
1385
1386 redef fun [](index)
1387 do
1388 # Check that the index (+ index_from) is not larger than indexTo
1389 # In other terms, if the index is valid
1390 assert index >= 0
1391 var target = self.target
1392 assert (index + target.index_from) <= target.index_to
1393 return target.items[index + target.index_from]
1394 end
1395
1396 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1397
1398 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1399
1400 end
1401
1402 # A mutable sequence of characters.
1403 abstract class Buffer
1404 super Text
1405
1406 redef type SELFTYPE: Buffer is fixed
1407
1408 # Specific implementations MUST set this to `true` in order to invalidate caches
1409 protected var is_dirty = true
1410
1411 # Copy-On-Write flag
1412 #
1413 # If the `Buffer` was to_s'd, the next in-place altering
1414 # operation will cause the current `Buffer` to be re-allocated.
1415 #
1416 # The flag will then be set at `false`.
1417 protected var written = false
1418
1419 # Modifies the char contained at pos `index`
1420 #
1421 # DEPRECATED : Use self.chars.[]= instead
1422 fun []=(index: Int, item: Char) is abstract
1423
1424 # Adds a char `c` at the end of self
1425 #
1426 # DEPRECATED : Use self.chars.add instead
1427 fun add(c: Char) is abstract
1428
1429 # Clears the buffer
1430 #
1431 # var b = new FlatBuffer
1432 # b.append "hello"
1433 # assert not b.is_empty
1434 # b.clear
1435 # assert b.is_empty
1436 fun clear is abstract
1437
1438 # Enlarges the subsequent array containing the chars of self
1439 fun enlarge(cap: Int) is abstract
1440
1441 # Adds the content of text `s` at the end of self
1442 #
1443 # var b = new FlatBuffer
1444 # b.append "hello"
1445 # b.append "world"
1446 # assert b == "helloworld"
1447 fun append(s: Text) is abstract
1448
1449 # `self` is appended in such a way that `self` is repeated `r` times
1450 #
1451 # var b = new FlatBuffer
1452 # b.append "hello"
1453 # b.times 3
1454 # assert b == "hellohellohello"
1455 fun times(r: Int) is abstract
1456
1457 # Reverses itself in-place
1458 #
1459 # var b = new FlatBuffer
1460 # b.append("hello")
1461 # b.reverse
1462 # assert b == "olleh"
1463 fun reverse is abstract
1464
1465 # Changes each lower-case char in `self` by its upper-case variant
1466 #
1467 # var b = new FlatBuffer
1468 # b.append("Hello World!")
1469 # b.upper
1470 # assert b == "HELLO WORLD!"
1471 fun upper is abstract
1472
1473 # Changes each upper-case char in `self` by its lower-case variant
1474 #
1475 # var b = new FlatBuffer
1476 # b.append("Hello World!")
1477 # b.lower
1478 # assert b == "hello world!"
1479 fun lower is abstract
1480
1481 # Capitalizes each word in `self`
1482 #
1483 # Letters that follow a letter are lowercased
1484 # Letters that follow a non-letter are upcased.
1485 #
1486 # SEE: `Char::is_letter` for the definition of a letter.
1487 #
1488 # var b = new FlatBuffer.from("jAVAsCriPt")
1489 # b.capitalize
1490 # assert b == "Javascript"
1491 # b = new FlatBuffer.from("i am root")
1492 # b.capitalize
1493 # assert b == "I Am Root"
1494 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1495 # b.capitalize
1496 # assert b == "Ab_C -Ab0C Ab\nC"
1497 fun capitalize do
1498 if length == 0 then return
1499 var c = self[0].to_upper
1500 self[0] = c
1501 var prev = c
1502 for i in [1 .. length[ do
1503 prev = c
1504 c = self[i]
1505 if prev.is_letter then
1506 self[i] = c.to_lower
1507 else
1508 self[i] = c.to_upper
1509 end
1510 end
1511 end
1512
1513 redef fun hash
1514 do
1515 if is_dirty then hash_cache = null
1516 return super
1517 end
1518
1519 # In Buffers, the internal sequence of character is mutable
1520 # Thus, `chars` can be used to modify the buffer.
1521 redef fun chars: Sequence[Char] is abstract
1522 end
1523
1524 # Mutable strings of characters.
1525 class FlatBuffer
1526 super FlatText
1527 super Buffer
1528
1529 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1530
1531 private var capacity: Int = 0
1532
1533 redef fun substrings do return new FlatSubstringsIter(self)
1534
1535 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1536 #
1537 # This happens when an operation modifies the current `Buffer` and
1538 # the Copy-On-Write flag `written` is set at true.
1539 private fun reset do
1540 var nns = new NativeString(capacity)
1541 items.copy_to(nns, length, 0, 0)
1542 items = nns
1543 written = false
1544 end
1545
1546 redef fun [](index)
1547 do
1548 assert index >= 0
1549 assert index < length
1550 return items[index]
1551 end
1552
1553 redef fun []=(index, item)
1554 do
1555 is_dirty = true
1556 if index == length then
1557 add(item)
1558 return
1559 end
1560 if written then reset
1561 assert index >= 0 and index < length
1562 items[index] = item
1563 end
1564
1565 redef fun add(c)
1566 do
1567 is_dirty = true
1568 if capacity <= length then enlarge(length + 5)
1569 items[length] = c
1570 length += 1
1571 end
1572
1573 redef fun clear do
1574 is_dirty = true
1575 if written then reset
1576 length = 0
1577 end
1578
1579 redef fun empty do return new FlatBuffer
1580
1581 redef fun enlarge(cap)
1582 do
1583 var c = capacity
1584 if cap <= c then return
1585 while c <= cap do c = c * 2 + 2
1586 # The COW flag can be set at false here, since
1587 # it does a copy of the current `Buffer`
1588 written = false
1589 var a = new NativeString(c+1)
1590 if length > 0 then items.copy_to(a, length, 0, 0)
1591 items = a
1592 capacity = c
1593 end
1594
1595 redef fun to_s: String
1596 do
1597 written = true
1598 if length == 0 then items = new NativeString(1)
1599 return new FlatString.with_infos(items, length, 0, length - 1)
1600 end
1601
1602 redef fun to_cstring
1603 do
1604 if is_dirty then
1605 var new_native = new NativeString(length + 1)
1606 new_native[length] = '\0'
1607 if length > 0 then items.copy_to(new_native, length, 0, 0)
1608 real_items = new_native
1609 is_dirty = false
1610 end
1611 return real_items.as(not null)
1612 end
1613
1614 # Create a new empty string.
1615 init do end
1616
1617 # Create a new string copied from `s`.
1618 init from(s: Text)
1619 do
1620 capacity = s.length + 1
1621 length = s.length
1622 items = new NativeString(capacity)
1623 if s isa FlatString then
1624 s.items.copy_to(items, length, s.index_from, 0)
1625 else if s isa FlatBuffer then
1626 s.items.copy_to(items, length, 0, 0)
1627 else
1628 var curr_pos = 0
1629 for i in [0..s.length[ do
1630 var c = s.chars[i]
1631 items[curr_pos] = c
1632 curr_pos += 1
1633 end
1634 end
1635 end
1636
1637 # Create a new empty string with a given capacity.
1638 init with_capacity(cap: Int)
1639 do
1640 assert cap >= 0
1641 # _items = new NativeString.calloc(cap)
1642 items = new NativeString(cap+1)
1643 capacity = cap
1644 length = 0
1645 end
1646
1647 redef fun append(s)
1648 do
1649 if s.is_empty then return
1650 is_dirty = true
1651 var sl = s.length
1652 if capacity < length + sl then enlarge(length + sl)
1653 if s isa FlatString then
1654 s.items.copy_to(items, sl, s.index_from, length)
1655 else if s isa FlatBuffer then
1656 s.items.copy_to(items, sl, 0, length)
1657 else
1658 var curr_pos = self.length
1659 for i in [0..s.length[ do
1660 var c = s.chars[i]
1661 items[curr_pos] = c
1662 curr_pos += 1
1663 end
1664 end
1665 length += sl
1666 end
1667
1668 # Copies the content of self in `dest`
1669 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1670 do
1671 var self_chars = self.chars
1672 var dest_chars = dest.chars
1673 for i in [0..len-1] do
1674 dest_chars[new_start+i] = self_chars[start+i]
1675 end
1676 end
1677
1678 redef fun substring(from, count)
1679 do
1680 assert count >= 0
1681 count += from
1682 if from < 0 then from = 0
1683 if count > length then count = length
1684 if from < count then
1685 var r = new FlatBuffer.with_capacity(count - from)
1686 while from < count do
1687 r.chars.push(items[from])
1688 from += 1
1689 end
1690 return r
1691 else
1692 return new FlatBuffer
1693 end
1694 end
1695
1696 redef fun reverse
1697 do
1698 written = false
1699 var ns = new NativeString(capacity)
1700 var si = length - 1
1701 var ni = 0
1702 var it = items
1703 while si >= 0 do
1704 ns[ni] = it[si]
1705 ni += 1
1706 si -= 1
1707 end
1708 items = ns
1709 end
1710
1711 redef fun times(repeats)
1712 do
1713 var x = new FlatString.with_infos(items, length, 0, length - 1)
1714 for i in [1..repeats[ do
1715 append(x)
1716 end
1717 end
1718
1719 redef fun upper
1720 do
1721 if written then reset
1722 var it = items
1723 var id = length - 1
1724 while id >= 0 do
1725 it[id] = it[id].to_upper
1726 id -= 1
1727 end
1728 end
1729
1730 redef fun lower
1731 do
1732 if written then reset
1733 var it = items
1734 var id = length - 1
1735 while id >= 0 do
1736 it[id] = it[id].to_lower
1737 id -= 1
1738 end
1739 end
1740 end
1741
1742 private class FlatBufferReverseIterator
1743 super IndexedIterator[Char]
1744
1745 var target: FlatBuffer
1746
1747 var target_items: NativeString
1748
1749 var curr_pos: Int
1750
1751 init with_pos(tgt: FlatBuffer, pos: Int)
1752 do
1753 target = tgt
1754 if tgt.length > 0 then target_items = tgt.items
1755 curr_pos = pos
1756 end
1757
1758 redef fun index do return curr_pos
1759
1760 redef fun is_ok do return curr_pos >= 0
1761
1762 redef fun item do return target_items[curr_pos]
1763
1764 redef fun next do curr_pos -= 1
1765
1766 end
1767
1768 private class FlatBufferCharView
1769 super BufferCharView
1770
1771 redef type SELFTYPE: FlatBuffer
1772
1773 redef fun [](index) do return target.items[index]
1774
1775 redef fun []=(index, item)
1776 do
1777 assert index >= 0 and index <= length
1778 if index == length then
1779 add(item)
1780 return
1781 end
1782 target.items[index] = item
1783 end
1784
1785 redef fun push(c)
1786 do
1787 target.add(c)
1788 end
1789
1790 redef fun add(c)
1791 do
1792 target.add(c)
1793 end
1794
1795 fun enlarge(cap: Int)
1796 do
1797 target.enlarge(cap)
1798 end
1799
1800 redef fun append(s)
1801 do
1802 var s_length = s.length
1803 if target.capacity < s.length then enlarge(s_length + target.length)
1804 end
1805
1806 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1807
1808 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1809
1810 end
1811
1812 private class FlatBufferIterator
1813 super IndexedIterator[Char]
1814
1815 var target: FlatBuffer
1816
1817 var target_items: NativeString
1818
1819 var curr_pos: Int
1820
1821 init with_pos(tgt: FlatBuffer, pos: Int)
1822 do
1823 target = tgt
1824 if tgt.length > 0 then target_items = tgt.items
1825 curr_pos = pos
1826 end
1827
1828 redef fun index do return curr_pos
1829
1830 redef fun is_ok do return curr_pos < target.length
1831
1832 redef fun item do return target_items[curr_pos]
1833
1834 redef fun next do curr_pos += 1
1835
1836 end
1837
1838 ###############################################################################
1839 # Refinement #
1840 ###############################################################################
1841
1842 redef class Object
1843 # User readable representation of `self`.
1844 fun to_s: String do return inspect
1845
1846 # The class name of the object in NativeString format.
1847 private fun native_class_name: NativeString is intern
1848
1849 # The class name of the object.
1850 #
1851 # assert 5.class_name == "Int"
1852 fun class_name: String do return native_class_name.to_s
1853
1854 # Developer readable representation of `self`.
1855 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1856 fun inspect: String
1857 do
1858 return "<{inspect_head}>"
1859 end
1860
1861 # Return "CLASSNAME:#OBJECTID".
1862 # This function is mainly used with the redefinition of the inspect method
1863 protected fun inspect_head: String
1864 do
1865 return "{class_name}:#{object_id.to_hex}"
1866 end
1867 end
1868
1869 redef class Bool
1870 # assert true.to_s == "true"
1871 # assert false.to_s == "false"
1872 redef fun to_s
1873 do
1874 if self then
1875 return once "true"
1876 else
1877 return once "false"
1878 end
1879 end
1880 end
1881
1882 redef class Int
1883
1884 # Wrapper of strerror C function
1885 private fun strerror_ext: NativeString is extern `{
1886 return strerror(recv);
1887 `}
1888
1889 # Returns a string describing error number
1890 fun strerror: String do return strerror_ext.to_s
1891
1892 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1893 # assume < to_c max const of char
1894 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1895 do
1896 var n: Int
1897 # Sign
1898 if self < 0 then
1899 n = - self
1900 s.chars[0] = '-'
1901 else if self == 0 then
1902 s.chars[0] = '0'
1903 return
1904 else
1905 n = self
1906 end
1907 # Fill digits
1908 var pos = digit_count(base) - 1
1909 while pos >= 0 and n > 0 do
1910 s.chars[pos] = (n % base).to_c
1911 n = n / base # /
1912 pos -= 1
1913 end
1914 end
1915
1916 # C function to calculate the length of the `NativeString` to receive `self`
1917 private fun int_to_s_len: Int is extern "native_int_length_str"
1918
1919 # C function to convert an nit Int to a NativeString (char*)
1920 private fun native_int_to_s(nstr: NativeString, strlen: Int) is extern "native_int_to_s"
1921
1922 # return displayable int in base 10 and signed
1923 #
1924 # assert 1.to_s == "1"
1925 # assert (-123).to_s == "-123"
1926 redef fun to_s do
1927 var nslen = int_to_s_len
1928 var ns = new NativeString(nslen + 1)
1929 ns[nslen] = '\0'
1930 native_int_to_s(ns, nslen + 1)
1931 return ns.to_s_with_length(nslen)
1932 end
1933
1934 # return displayable int in hexadecimal
1935 #
1936 # assert 1.to_hex == "1"
1937 # assert (-255).to_hex == "-ff"
1938 fun to_hex: String do return to_base(16,false)
1939
1940 # return displayable int in base base and signed
1941 fun to_base(base: Int, signed: Bool): String
1942 do
1943 var l = digit_count(base)
1944 var s = new FlatBuffer.from(" " * l)
1945 fill_buffer(s, base, signed)
1946 return s.to_s
1947 end
1948 end
1949
1950 redef class Float
1951 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1952 #
1953 # assert 12.34.to_s == "12.34"
1954 # assert (-0120.030).to_s == "-120.03"
1955 #
1956 # see `to_precision` for a custom precision.
1957 redef fun to_s do
1958 var str = to_precision( 3 )
1959 if is_inf != 0 or is_nan then return str
1960 var len = str.length
1961 for i in [0..len-1] do
1962 var j = len-1-i
1963 var c = str.chars[j]
1964 if c == '0' then
1965 continue
1966 else if c == '.' then
1967 return str.substring( 0, j+2 )
1968 else
1969 return str.substring( 0, j+1 )
1970 end
1971 end
1972 return str
1973 end
1974
1975 # `String` representation of `self` with the given number of `decimals`
1976 #
1977 # assert 12.345.to_precision(0) == "12"
1978 # assert 12.345.to_precision(3) == "12.345"
1979 # assert (-12.345).to_precision(3) == "-12.345"
1980 # assert (-0.123).to_precision(3) == "-0.123"
1981 # assert 0.999.to_precision(2) == "1.00"
1982 # assert 0.999.to_precision(4) == "0.9990"
1983 fun to_precision(decimals: Int): String
1984 do
1985 if is_nan then return "nan"
1986
1987 var isinf = self.is_inf
1988 if isinf == 1 then
1989 return "inf"
1990 else if isinf == -1 then
1991 return "-inf"
1992 end
1993
1994 if decimals == 0 then return self.to_i.to_s
1995 var f = self
1996 for i in [0..decimals[ do f = f * 10.0
1997 if self > 0.0 then
1998 f = f + 0.5
1999 else
2000 f = f - 0.5
2001 end
2002 var i = f.to_i
2003 if i == 0 then return "0." + "0"*decimals
2004
2005 # Prepare both parts of the float, before and after the "."
2006 var s = i.abs.to_s
2007 var sl = s.length
2008 var p1
2009 var p2
2010 if sl > decimals then
2011 # Has something before the "."
2012 p1 = s.substring(0, sl-decimals)
2013 p2 = s.substring(sl-decimals, decimals)
2014 else
2015 p1 = "0"
2016 p2 = "0"*(decimals-sl) + s
2017 end
2018
2019 if i < 0 then p1 = "-" + p1
2020
2021 return p1 + "." + p2
2022 end
2023 end
2024
2025 redef class Char
2026 # assert 'x'.to_s == "x"
2027 redef fun to_s
2028 do
2029 var s = new FlatBuffer.with_capacity(1)
2030 s.chars[0] = self
2031 return s.to_s
2032 end
2033
2034 # Returns true if the char is a numerical digit
2035 #
2036 # assert '0'.is_numeric
2037 # assert '9'.is_numeric
2038 # assert not 'a'.is_numeric
2039 # assert not '?'.is_numeric
2040 fun is_numeric: Bool
2041 do
2042 return self >= '0' and self <= '9'
2043 end
2044
2045 # Returns true if the char is an alpha digit
2046 #
2047 # assert 'a'.is_alpha
2048 # assert 'Z'.is_alpha
2049 # assert not '0'.is_alpha
2050 # assert not '?'.is_alpha
2051 fun is_alpha: Bool
2052 do
2053 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2054 end
2055
2056 # Returns true if the char is an alpha or a numeric digit
2057 #
2058 # assert 'a'.is_alphanumeric
2059 # assert 'Z'.is_alphanumeric
2060 # assert '0'.is_alphanumeric
2061 # assert '9'.is_alphanumeric
2062 # assert not '?'.is_alphanumeric
2063 fun is_alphanumeric: Bool
2064 do
2065 return self.is_numeric or self.is_alpha
2066 end
2067 end
2068
2069 redef class Collection[E]
2070 # Concatenate elements.
2071 redef fun to_s
2072 do
2073 var s = new FlatBuffer
2074 for e in self do if e != null then s.append(e.to_s)
2075 return s.to_s
2076 end
2077
2078 # Concatenate and separate each elements with `sep`.
2079 #
2080 # assert [1, 2, 3].join(":") == "1:2:3"
2081 # assert [1..3].join(":") == "1:2:3"
2082 fun join(sep: Text): String
2083 do
2084 if is_empty then return ""
2085
2086 var s = new FlatBuffer # Result
2087
2088 # Concat first item
2089 var i = iterator
2090 var e = i.item
2091 if e != null then s.append(e.to_s)
2092
2093 # Concat other items
2094 i.next
2095 while i.is_ok do
2096 s.append(sep)
2097 e = i.item
2098 if e != null then s.append(e.to_s)
2099 i.next
2100 end
2101 return s.to_s
2102 end
2103 end
2104
2105 redef class Array[E]
2106
2107 # Fast implementation
2108 redef fun to_s
2109 do
2110 var l = length
2111 if l == 0 then return ""
2112 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2113 var its = _items
2114 var na = new NativeArray[String](l)
2115 var i = 0
2116 var sl = 0
2117 var mypos = 0
2118 while i < l do
2119 var itsi = its[i]
2120 if itsi == null then
2121 i += 1
2122 continue
2123 end
2124 var tmp = itsi.to_s
2125 sl += tmp.length
2126 na[mypos] = tmp
2127 i += 1
2128 mypos += 1
2129 end
2130 var ns = new NativeString(sl + 1)
2131 ns[sl] = '\0'
2132 i = 0
2133 var off = 0
2134 while i < mypos do
2135 var tmp = na[i]
2136 var tpl = tmp.length
2137 if tmp isa FlatString then
2138 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2139 off += tpl
2140 else
2141 for j in tmp.substrings do
2142 var s = j.as(FlatString)
2143 var slen = s.length
2144 s.items.copy_to(ns, slen, s.index_from, off)
2145 off += slen
2146 end
2147 end
2148 i += 1
2149 end
2150 return ns.to_s_with_length(sl)
2151 end
2152 end
2153
2154 redef class Map[K,V]
2155 # Concatenate couple of 'key value'.
2156 # key and value are separated by `couple_sep`.
2157 # each couple is separated each couple with `sep`.
2158 #
2159 # var m = new ArrayMap[Int, String]
2160 # m[1] = "one"
2161 # m[10] = "ten"
2162 # assert m.join("; ", "=") == "1=one; 10=ten"
2163 fun join(sep: String, couple_sep: String): String
2164 do
2165 if is_empty then return ""
2166
2167 var s = new FlatBuffer # Result
2168
2169 # Concat first item
2170 var i = iterator
2171 var k = i.key
2172 var e = i.item
2173 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2174
2175 # Concat other items
2176 i.next
2177 while i.is_ok do
2178 s.append(sep)
2179 k = i.key
2180 e = i.item
2181 s.append("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2182 i.next
2183 end
2184 return s.to_s
2185 end
2186 end
2187
2188 ###############################################################################
2189 # Native classes #
2190 ###############################################################################
2191
2192 # Native strings are simple C char *
2193 extern class NativeString `{ char* `}
2194 # Creates a new NativeString with a capacity of `length`
2195 new(length: Int) is intern
2196
2197 # Get char at `index`.
2198 fun [](index: Int): Char is intern
2199
2200 # Set char `item` at index.
2201 fun []=(index: Int, item: Char) is intern
2202
2203 # Copy `self` to `dest`.
2204 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2205
2206 # Position of the first nul character.
2207 fun cstring_length: Int
2208 do
2209 var l = 0
2210 while self[l] != '\0' do l += 1
2211 return l
2212 end
2213
2214 # Parse `self` as an Int.
2215 fun atoi: Int is intern
2216
2217 # Parse `self` as a Float.
2218 fun atof: Float is extern "atof"
2219
2220 redef fun to_s
2221 do
2222 return to_s_with_length(cstring_length)
2223 end
2224
2225 # Returns `self` as a String of `length`.
2226 fun to_s_with_length(length: Int): FlatString
2227 do
2228 assert length >= 0
2229 var str = new FlatString.with_infos(self, length, 0, length - 1)
2230 return str
2231 end
2232
2233 # Returns `self` as a new String.
2234 fun to_s_with_copy: FlatString
2235 do
2236 var length = cstring_length
2237 var new_self = new NativeString(length + 1)
2238 copy_to(new_self, length, 0, 0)
2239 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2240 new_self[length] = '\0'
2241 str.real_items = new_self
2242 return str
2243 end
2244 end
2245
2246 redef class Sys
2247 private var args_cache: nullable Sequence[String]
2248
2249 # The arguments of the program as given by the OS
2250 fun program_args: Sequence[String]
2251 do
2252 if _args_cache == null then init_args
2253 return _args_cache.as(not null)
2254 end
2255
2256 # The name of the program as given by the OS
2257 fun program_name: String
2258 do
2259 return native_argv(0).to_s
2260 end
2261
2262 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2263 private fun init_args
2264 do
2265 var argc = native_argc
2266 var args = new Array[String].with_capacity(0)
2267 var i = 1
2268 while i < argc do
2269 args[i-1] = native_argv(i).to_s
2270 i += 1
2271 end
2272 _args_cache = args
2273 end
2274
2275 # First argument of the main C function.
2276 private fun native_argc: Int is intern
2277
2278 # Second argument of the main C function.
2279 private fun native_argv(i: Int): NativeString is intern
2280 end
2281
2282 # Comparator that efficienlty use `to_s` to compare things
2283 #
2284 # The comparaison call `to_s` on object and use the result to order things.
2285 #
2286 # var a = [1, 2, 3, 10, 20]
2287 # (new CachedAlphaComparator).sort(a)
2288 # assert a == [1, 10, 2, 20, 3]
2289 #
2290 # Internally the result of `to_s` is cached in a HashMap to counter
2291 # uneficient implementation of `to_s`.
2292 #
2293 # Note: it caching is not usefull, see `alpha_comparator`
2294 class CachedAlphaComparator
2295 super Comparator
2296 redef type COMPARED: Object
2297
2298 private var cache = new HashMap[Object, String]
2299
2300 private fun do_to_s(a: Object): String do
2301 if cache.has_key(a) then return cache[a]
2302 var res = a.to_s
2303 cache[a] = res
2304 return res
2305 end
2306
2307 redef fun compare(a, b) do
2308 return do_to_s(a) <=> do_to_s(b)
2309 end
2310 end
2311
2312 # see `alpha_comparator`
2313 private class AlphaComparator
2314 super Comparator
2315 redef fun compare(a, b) do return a.to_s <=> b.to_s
2316 end
2317
2318 # Stateless comparator that naively use `to_s` to compare things.
2319 #
2320 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2321 # on a single instace. See `CachedAlphaComparator` as an alternative.
2322 #
2323 # var a = [1, 2, 3, 10, 20]
2324 # alpha_comparator.sort(a)
2325 # assert a == [1, 10, 2, 20, 3]
2326 fun alpha_comparator: Comparator do return once new AlphaComparator
2327
2328 # The arguments of the program as given by the OS
2329 fun args: Sequence[String]
2330 do
2331 return sys.program_args
2332 end