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