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