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