string: fix useless var warnings
[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 abstract class String
802 super Text
803
804 redef type SELFTYPE: String
805
806 redef fun to_s do return self
807
808 # Concatenates `o` to `self`
809 #
810 # assert "hello" + "world" == "helloworld"
811 # assert "" + "hello" + "" == "hello"
812 fun +(o: Text): SELFTYPE is abstract
813
814 # Concatenates self `i` times
815 #
816 # assert "abc" * 4 == "abcabcabcabc"
817 # assert "abc" * 1 == "abc"
818 # assert "abc" * 0 == ""
819 fun *(i: Int): SELFTYPE is abstract
820
821 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
822
823 redef fun substrings: Iterator[String] is abstract
824
825 # Returns a reversed version of self
826 #
827 # assert "hello".reversed == "olleh"
828 # assert "bob".reversed == "bob"
829 # assert "".reversed == ""
830 fun reversed: SELFTYPE is abstract
831
832 # A upper case version of `self`
833 #
834 # assert "Hello World!".to_upper == "HELLO WORLD!"
835 fun to_upper: SELFTYPE is abstract
836
837 # A lower case version of `self`
838 #
839 # assert "Hello World!".to_lower == "hello world!"
840 fun to_lower : SELFTYPE is abstract
841
842 # Takes a camel case `self` and converts it to snake case
843 #
844 # assert "randomMethodId".to_snake_case == "random_method_id"
845 #
846 # If `self` is upper, it is returned unchanged
847 #
848 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
849 #
850 # If the identifier is prefixed by an underscore, the underscore is ignored
851 #
852 # assert "_privateField".to_snake_case == "_private_field"
853 fun to_snake_case: SELFTYPE
854 do
855 if self.is_upper then return self
856
857 var new_str = new FlatBuffer.with_capacity(self.length)
858 var is_first_char = true
859
860 for i in [0..length[ do
861 var char = chars[i]
862 if is_first_char then
863 new_str.add(char.to_lower)
864 is_first_char = false
865 else if char.is_upper then
866 new_str.add('_')
867 new_str.add(char.to_lower)
868 else
869 new_str.add(char)
870 end
871 end
872
873 return new_str.to_s
874 end
875
876 # Takes a snake case `self` and converts it to camel case
877 #
878 # assert "random_method_id".to_camel_case == "randomMethodId"
879 #
880 # If the identifier is prefixed by an underscore, the underscore is ignored
881 #
882 # assert "_private_field".to_camel_case == "_privateField"
883 #
884 # If `self` is upper, it is returned unchanged
885 #
886 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
887 #
888 # If there are several consecutive underscores, they are considered as a single one
889 #
890 # assert "random__method_id".to_camel_case == "randomMethodId"
891 fun to_camel_case: SELFTYPE
892 do
893 if self.is_upper then return self
894
895 var new_str = new FlatBuffer
896 var is_first_char = true
897 var follows_us = false
898
899 for i in [0..length[ do
900 var char = chars[i]
901 if is_first_char then
902 new_str.add(char)
903 is_first_char = false
904 else if char == '_' then
905 follows_us = true
906 else if follows_us then
907 new_str.add(char.to_upper)
908 follows_us = false
909 else
910 new_str.add(char)
911 end
912 end
913
914 return new_str.to_s
915 end
916
917 # Returns a capitalized `self`
918 #
919 # Letters that follow a letter are lowercased
920 # Letters that follow a non-letter are upcased.
921 #
922 # SEE : `Char::is_letter` for the definition of letter.
923 #
924 # assert "jAVASCRIPT".capitalized == "Javascript"
925 # assert "i am root".capitalized == "I Am Root"
926 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
927 fun capitalized: SELFTYPE do
928 if length == 0 then return self
929
930 var buf = new FlatBuffer.with_capacity(length)
931
932 var curr = chars[0].to_upper
933 var prev = curr
934 buf[0] = curr
935
936 for i in [1 .. length[ do
937 prev = curr
938 curr = self[i]
939 if prev.is_letter then
940 buf[i] = curr.to_lower
941 else
942 buf[i] = curr.to_upper
943 end
944 end
945
946 return buf.to_s
947 end
948 end
949
950 private class FlatSubstringsIter
951 super Iterator[FlatText]
952
953 var tgt: nullable FlatText
954
955 redef fun item do
956 assert is_ok
957 return tgt.as(not null)
958 end
959
960 redef fun is_ok do return tgt != null
961
962 redef fun next do tgt = null
963 end
964
965 # Immutable strings of characters.
966 class FlatString
967 super FlatText
968 super String
969
970 # Index in _items of the start of the string
971 private var index_from: Int is noinit
972
973 # Indes in _items of the last item of the string
974 private var index_to: Int is noinit
975
976 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
977
978 redef fun [](index)
979 do
980 # Check that the index (+ index_from) is not larger than indexTo
981 # In other terms, if the index is valid
982 assert index >= 0
983 assert (index + index_from) <= index_to
984 return items[index + index_from]
985 end
986
987 ################################################
988 # AbstractString specific methods #
989 ################################################
990
991 redef fun reversed
992 do
993 var native = calloc_string(self.length + 1)
994 var length = self.length
995 var items = self.items
996 var pos = 0
997 var ipos = length-1
998 while pos < length do
999 native[pos] = items[ipos]
1000 pos += 1
1001 ipos -= 1
1002 end
1003 return native.to_s_with_length(self.length)
1004 end
1005
1006 redef fun substring(from, count)
1007 do
1008 assert count >= 0
1009
1010 if from < 0 then
1011 count += from
1012 if count < 0 then count = 0
1013 from = 0
1014 end
1015
1016 var realFrom = index_from + from
1017
1018 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
1019
1020 if count == 0 then return empty
1021
1022 var to = realFrom + count - 1
1023
1024 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
1025 end
1026
1027 redef fun empty do return "".as(FlatString)
1028
1029 redef fun to_upper
1030 do
1031 var outstr = calloc_string(self.length + 1)
1032 var out_index = 0
1033
1034 var myitems = self.items
1035 var index_from = self.index_from
1036 var max = self.index_to
1037
1038 while index_from <= max do
1039 outstr[out_index] = myitems[index_from].to_upper
1040 out_index += 1
1041 index_from += 1
1042 end
1043
1044 outstr[self.length] = '\0'
1045
1046 return outstr.to_s_with_length(self.length)
1047 end
1048
1049 redef fun to_lower
1050 do
1051 var outstr = calloc_string(self.length + 1)
1052 var out_index = 0
1053
1054 var myitems = self.items
1055 var index_from = self.index_from
1056 var max = self.index_to
1057
1058 while index_from <= max do
1059 outstr[out_index] = myitems[index_from].to_lower
1060 out_index += 1
1061 index_from += 1
1062 end
1063
1064 outstr[self.length] = '\0'
1065
1066 return outstr.to_s_with_length(self.length)
1067 end
1068
1069 redef fun output
1070 do
1071 var i = self.index_from
1072 var imax = self.index_to
1073 while i <= imax do
1074 items[i].output
1075 i += 1
1076 end
1077 end
1078
1079 ##################################################
1080 # String Specific Methods #
1081 ##################################################
1082
1083 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1084 do
1085 self.items = items
1086 length = len
1087 index_from = from
1088 index_to = to
1089 end
1090
1091 redef fun to_cstring: NativeString
1092 do
1093 if real_items != null then
1094 return real_items.as(not null)
1095 else
1096 var newItems = calloc_string(length + 1)
1097 self.items.copy_to(newItems, length, index_from, 0)
1098 newItems[length] = '\0'
1099 self.real_items = newItems
1100 return newItems
1101 end
1102 end
1103
1104 redef fun ==(other)
1105 do
1106 if not other isa FlatString then return super
1107
1108 if self.object_id == other.object_id then return true
1109
1110 var my_length = length
1111
1112 if other.length != my_length then return false
1113
1114 var my_index = index_from
1115 var its_index = other.index_from
1116
1117 var last_iteration = my_index + my_length
1118
1119 var itsitems = other.items
1120 var myitems = self.items
1121
1122 while my_index < last_iteration do
1123 if myitems[my_index] != itsitems[its_index] then return false
1124 my_index += 1
1125 its_index += 1
1126 end
1127
1128 return true
1129 end
1130
1131 redef fun <(other)
1132 do
1133 if not other isa FlatString then return super
1134
1135 if self.object_id == other.object_id then return false
1136
1137 var my_curr_char : Char
1138 var its_curr_char : Char
1139
1140 var curr_id_self = self.index_from
1141 var curr_id_other = other.index_from
1142
1143 var my_items = self.items
1144 var its_items = other.items
1145
1146 var my_length = self.length
1147 var its_length = other.length
1148
1149 var max_iterations = curr_id_self + my_length
1150
1151 while curr_id_self < max_iterations do
1152 my_curr_char = my_items[curr_id_self]
1153 its_curr_char = its_items[curr_id_other]
1154
1155 if my_curr_char != its_curr_char then
1156 if my_curr_char < its_curr_char then return true
1157 return false
1158 end
1159
1160 curr_id_self += 1
1161 curr_id_other += 1
1162 end
1163
1164 return my_length < its_length
1165 end
1166
1167 redef fun +(s)
1168 do
1169 var my_length = self.length
1170 var its_length = s.length
1171
1172 var total_length = my_length + its_length
1173
1174 var target_string = calloc_string(my_length + its_length + 1)
1175
1176 self.items.copy_to(target_string, my_length, index_from, 0)
1177 if s isa FlatString then
1178 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1179 else if s isa FlatBuffer then
1180 s.items.copy_to(target_string, its_length, 0, my_length)
1181 else
1182 var curr_pos = my_length
1183 for i in [0..s.length[ do
1184 var c = s.chars[i]
1185 target_string[curr_pos] = c
1186 curr_pos += 1
1187 end
1188 end
1189
1190 target_string[total_length] = '\0'
1191
1192 return target_string.to_s_with_length(total_length)
1193 end
1194
1195 redef fun *(i)
1196 do
1197 assert i >= 0
1198
1199 var my_length = self.length
1200
1201 var final_length = my_length * i
1202
1203 var my_items = self.items
1204
1205 var target_string = calloc_string((final_length) + 1)
1206
1207 target_string[final_length] = '\0'
1208
1209 var current_last = 0
1210
1211 for iteration in [1 .. i] do
1212 my_items.copy_to(target_string, my_length, 0, current_last)
1213 current_last += my_length
1214 end
1215
1216 return target_string.to_s_with_length(final_length)
1217 end
1218
1219 redef fun hash
1220 do
1221 if hash_cache == null then
1222 # djb2 hash algorithm
1223 var h = 5381
1224 var i = index_from
1225
1226 var myitems = items
1227
1228 while i <= index_to do
1229 h = h.lshift(5) + h + myitems[i].ascii
1230 i += 1
1231 end
1232
1233 hash_cache = h
1234 end
1235
1236 return hash_cache.as(not null)
1237 end
1238
1239 redef fun substrings do return new FlatSubstringsIter(self)
1240 end
1241
1242 private class FlatStringReverseIterator
1243 super IndexedIterator[Char]
1244
1245 var target: FlatString
1246
1247 var target_items: NativeString
1248
1249 var curr_pos: Int
1250
1251 init with_pos(tgt: FlatString, pos: Int)
1252 do
1253 target = tgt
1254 target_items = tgt.items
1255 curr_pos = pos + tgt.index_from
1256 end
1257
1258 redef fun is_ok do return curr_pos >= target.index_from
1259
1260 redef fun item do return target_items[curr_pos]
1261
1262 redef fun next do curr_pos -= 1
1263
1264 redef fun index do return curr_pos - target.index_from
1265
1266 end
1267
1268 private class FlatStringIterator
1269 super IndexedIterator[Char]
1270
1271 var target: FlatString
1272
1273 var target_items: NativeString
1274
1275 var curr_pos: Int
1276
1277 init with_pos(tgt: FlatString, pos: Int)
1278 do
1279 target = tgt
1280 target_items = tgt.items
1281 curr_pos = pos + target.index_from
1282 end
1283
1284 redef fun is_ok do return curr_pos <= target.index_to
1285
1286 redef fun item do return target_items[curr_pos]
1287
1288 redef fun next do curr_pos += 1
1289
1290 redef fun index do return curr_pos - target.index_from
1291
1292 end
1293
1294 private class FlatStringCharView
1295 super StringCharView
1296
1297 redef type SELFTYPE: FlatString
1298
1299 redef fun [](index)
1300 do
1301 # Check that the index (+ index_from) is not larger than indexTo
1302 # In other terms, if the index is valid
1303 assert index >= 0
1304 var target = self.target
1305 assert (index + target.index_from) <= target.index_to
1306 return target.items[index + target.index_from]
1307 end
1308
1309 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1310
1311 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1312
1313 end
1314
1315 abstract class Buffer
1316 super Text
1317
1318 redef type SELFTYPE: Buffer
1319
1320 # Specific implementations MUST set this to `true` in order to invalidate caches
1321 protected var is_dirty = true
1322
1323 # Copy-On-Write flag
1324 #
1325 # If the `Buffer` was to_s'd, the next in-place altering
1326 # operation will cause the current `Buffer` to be re-allocated.
1327 #
1328 # The flag will then be set at `false`.
1329 protected var written = false
1330
1331 # Modifies the char contained at pos `index`
1332 #
1333 # DEPRECATED : Use self.chars.[]= instead
1334 fun []=(index: Int, item: Char) is abstract
1335
1336 # Adds a char `c` at the end of self
1337 #
1338 # DEPRECATED : Use self.chars.add instead
1339 fun add(c: Char) is abstract
1340
1341 # Clears the buffer
1342 #
1343 # var b = new FlatBuffer
1344 # b.append "hello"
1345 # assert not b.is_empty
1346 # b.clear
1347 # assert b.is_empty
1348 fun clear is abstract
1349
1350 # Enlarges the subsequent array containing the chars of self
1351 fun enlarge(cap: Int) is abstract
1352
1353 # Adds the content of text `s` at the end of self
1354 #
1355 # var b = new FlatBuffer
1356 # b.append "hello"
1357 # b.append "world"
1358 # assert b == "helloworld"
1359 fun append(s: Text) is abstract
1360
1361 # `self` is appended in such a way that `self` is repeated `r` times
1362 #
1363 # var b = new FlatBuffer
1364 # b.append "hello"
1365 # b.times 3
1366 # assert b == "hellohellohello"
1367 fun times(r: Int) is abstract
1368
1369 # Reverses itself in-place
1370 #
1371 # var b = new FlatBuffer
1372 # b.append("hello")
1373 # b.reverse
1374 # assert b == "olleh"
1375 fun reverse is abstract
1376
1377 # Changes each lower-case char in `self` by its upper-case variant
1378 #
1379 # var b = new FlatBuffer
1380 # b.append("Hello World!")
1381 # b.upper
1382 # assert b == "HELLO WORLD!"
1383 fun upper is abstract
1384
1385 # Changes each upper-case char in `self` by its lower-case variant
1386 #
1387 # var b = new FlatBuffer
1388 # b.append("Hello World!")
1389 # b.lower
1390 # assert b == "hello world!"
1391 fun lower is abstract
1392
1393 # Capitalizes each word in `self`
1394 #
1395 # Letters that follow a letter are lowercased
1396 # Letters that follow a non-letter are upcased.
1397 #
1398 # SEE: `Char::is_letter` for the definition of a letter.
1399 #
1400 # var b = new FlatBuffer.from("jAVAsCriPt")"
1401 # b.capitalize
1402 # assert b == "Javascript"
1403 # b = new FlatBuffer.from("i am root")
1404 # b.capitalize
1405 # assert b == "I Am Root"
1406 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1407 # b.capitalize
1408 # assert b == "Ab_C -Ab0C Ab\nC"
1409 fun capitalize do
1410 if length == 0 then return
1411 var c = self[0].to_upper
1412 self[0] = c
1413 var prev: Char = c
1414 for i in [1 .. length[ do
1415 prev = c
1416 c = self[i]
1417 if prev.is_letter then
1418 self[i] = c.to_lower
1419 else
1420 self[i] = c.to_upper
1421 end
1422 end
1423 end
1424
1425 redef fun hash
1426 do
1427 if is_dirty then hash_cache = null
1428 return super
1429 end
1430
1431 # In Buffers, the internal sequence of character is mutable
1432 # Thus, `chars` can be used to modify the buffer.
1433 redef fun chars: Sequence[Char] is abstract
1434 end
1435
1436 # Mutable strings of characters.
1437 class FlatBuffer
1438 super FlatText
1439 super Buffer
1440
1441 redef type SELFTYPE: FlatBuffer
1442
1443 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1444
1445 private var capacity: Int = 0
1446
1447 redef fun substrings do return new FlatSubstringsIter(self)
1448
1449 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1450 #
1451 # This happens when an operation modifies the current `Buffer` and
1452 # the Copy-On-Write flag `written` is set at true.
1453 private fun reset do
1454 var nns = new NativeString(capacity)
1455 items.copy_to(nns, length, 0, 0)
1456 items = nns
1457 written = false
1458 end
1459
1460 redef fun [](index)
1461 do
1462 assert index >= 0
1463 assert index < length
1464 return items[index]
1465 end
1466
1467 redef fun []=(index, item)
1468 do
1469 is_dirty = true
1470 if index == length then
1471 add(item)
1472 return
1473 end
1474 if written then reset
1475 assert index >= 0 and index < length
1476 items[index] = item
1477 end
1478
1479 redef fun add(c)
1480 do
1481 is_dirty = true
1482 if capacity <= length then enlarge(length + 5)
1483 items[length] = c
1484 length += 1
1485 end
1486
1487 redef fun clear do
1488 is_dirty = true
1489 if written then reset
1490 length = 0
1491 end
1492
1493 redef fun empty do return new FlatBuffer
1494
1495 redef fun enlarge(cap)
1496 do
1497 var c = capacity
1498 if cap <= c then return
1499 while c <= cap do c = c * 2 + 2
1500 # The COW flag can be set at false here, since
1501 # it does a copy of the current `Buffer`
1502 written = false
1503 var a = calloc_string(c+1)
1504 if length > 0 then items.copy_to(a, length, 0, 0)
1505 items = a
1506 capacity = c
1507 end
1508
1509 redef fun to_s: String
1510 do
1511 written = true
1512 if length == 0 then items = new NativeString(1)
1513 return new FlatString.with_infos(items, length, 0, length - 1)
1514 end
1515
1516 redef fun to_cstring
1517 do
1518 if is_dirty then
1519 var new_native = calloc_string(length + 1)
1520 new_native[length] = '\0'
1521 if length > 0 then items.copy_to(new_native, length, 0, 0)
1522 real_items = new_native
1523 is_dirty = false
1524 end
1525 return real_items.as(not null)
1526 end
1527
1528 # Create a new empty string.
1529 init do end
1530
1531 init from(s: Text)
1532 do
1533 capacity = s.length + 1
1534 length = s.length
1535 items = calloc_string(capacity)
1536 if s isa FlatString then
1537 s.items.copy_to(items, length, s.index_from, 0)
1538 else if s isa FlatBuffer then
1539 s.items.copy_to(items, length, 0, 0)
1540 else
1541 var curr_pos = 0
1542 for i in [0..s.length[ do
1543 var c = s.chars[i]
1544 items[curr_pos] = c
1545 curr_pos += 1
1546 end
1547 end
1548 end
1549
1550 # Create a new empty string with a given capacity.
1551 init with_capacity(cap: Int)
1552 do
1553 assert cap >= 0
1554 # _items = new NativeString.calloc(cap)
1555 items = calloc_string(cap+1)
1556 capacity = cap
1557 length = 0
1558 end
1559
1560 redef fun append(s)
1561 do
1562 if s.is_empty then return
1563 is_dirty = true
1564 var sl = s.length
1565 if capacity < length + sl then enlarge(length + sl)
1566 if s isa FlatString then
1567 s.items.copy_to(items, sl, s.index_from, length)
1568 else if s isa FlatBuffer then
1569 s.items.copy_to(items, sl, 0, length)
1570 else
1571 var curr_pos = self.length
1572 for i in [0..s.length[ do
1573 var c = s.chars[i]
1574 items[curr_pos] = c
1575 curr_pos += 1
1576 end
1577 end
1578 length += sl
1579 end
1580
1581 # Copies the content of self in `dest`
1582 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1583 do
1584 var self_chars = self.chars
1585 var dest_chars = dest.chars
1586 for i in [0..len-1] do
1587 dest_chars[new_start+i] = self_chars[start+i]
1588 end
1589 end
1590
1591 redef fun substring(from, count)
1592 do
1593 assert count >= 0
1594 count += from
1595 if from < 0 then from = 0
1596 if count > length then count = length
1597 if from < count then
1598 var r = new FlatBuffer.with_capacity(count - from)
1599 while from < count do
1600 r.chars.push(items[from])
1601 from += 1
1602 end
1603 return r
1604 else
1605 return new FlatBuffer
1606 end
1607 end
1608
1609 redef fun reverse
1610 do
1611 written = false
1612 var ns = calloc_string(capacity)
1613 var si = length - 1
1614 var ni = 0
1615 var it = items
1616 while si >= 0 do
1617 ns[ni] = it[si]
1618 ni += 1
1619 si -= 1
1620 end
1621 items = ns
1622 end
1623
1624 redef fun times(repeats)
1625 do
1626 var x = new FlatString.with_infos(items, length, 0, length - 1)
1627 for i in [1..repeats[ do
1628 append(x)
1629 end
1630 end
1631
1632 redef fun upper
1633 do
1634 if written then reset
1635 var it = items
1636 var id = length - 1
1637 while id >= 0 do
1638 it[id] = it[id].to_upper
1639 id -= 1
1640 end
1641 end
1642
1643 redef fun lower
1644 do
1645 if written then reset
1646 var it = items
1647 var id = length - 1
1648 while id >= 0 do
1649 it[id] = it[id].to_lower
1650 id -= 1
1651 end
1652 end
1653 end
1654
1655 private class FlatBufferReverseIterator
1656 super IndexedIterator[Char]
1657
1658 var target: FlatBuffer
1659
1660 var target_items: NativeString
1661
1662 var curr_pos: Int
1663
1664 init with_pos(tgt: FlatBuffer, pos: Int)
1665 do
1666 target = tgt
1667 if tgt.length > 0 then target_items = tgt.items
1668 curr_pos = pos
1669 end
1670
1671 redef fun index do return curr_pos
1672
1673 redef fun is_ok do return curr_pos >= 0
1674
1675 redef fun item do return target_items[curr_pos]
1676
1677 redef fun next do curr_pos -= 1
1678
1679 end
1680
1681 private class FlatBufferCharView
1682 super BufferCharView
1683 super StringCapable
1684
1685 redef type SELFTYPE: FlatBuffer
1686
1687 redef fun [](index) do return target.items[index]
1688
1689 redef fun []=(index, item)
1690 do
1691 assert index >= 0 and index <= length
1692 if index == length then
1693 add(item)
1694 return
1695 end
1696 target.items[index] = item
1697 end
1698
1699 redef fun push(c)
1700 do
1701 target.add(c)
1702 end
1703
1704 redef fun add(c)
1705 do
1706 target.add(c)
1707 end
1708
1709 fun enlarge(cap: Int)
1710 do
1711 target.enlarge(cap)
1712 end
1713
1714 redef fun append(s)
1715 do
1716 var s_length = s.length
1717 if target.capacity < s.length then enlarge(s_length + target.length)
1718 end
1719
1720 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1721
1722 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1723
1724 end
1725
1726 private class FlatBufferIterator
1727 super IndexedIterator[Char]
1728
1729 var target: FlatBuffer
1730
1731 var target_items: NativeString
1732
1733 var curr_pos: Int
1734
1735 init with_pos(tgt: FlatBuffer, pos: Int)
1736 do
1737 target = tgt
1738 if tgt.length > 0 then target_items = tgt.items
1739 curr_pos = pos
1740 end
1741
1742 redef fun index do return curr_pos
1743
1744 redef fun is_ok do return curr_pos < target.length
1745
1746 redef fun item do return target_items[curr_pos]
1747
1748 redef fun next do curr_pos += 1
1749
1750 end
1751
1752 ###############################################################################
1753 # Refinement #
1754 ###############################################################################
1755
1756 redef class Object
1757 # User readable representation of `self`.
1758 fun to_s: String do return inspect
1759
1760 # The class name of the object in NativeString format.
1761 private fun native_class_name: NativeString is intern
1762
1763 # The class name of the object.
1764 #
1765 # assert 5.class_name == "Int"
1766 fun class_name: String do return native_class_name.to_s
1767
1768 # Developer readable representation of `self`.
1769 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1770 fun inspect: String
1771 do
1772 return "<{inspect_head}>"
1773 end
1774
1775 # Return "CLASSNAME:#OBJECTID".
1776 # This function is mainly used with the redefinition of the inspect method
1777 protected fun inspect_head: String
1778 do
1779 return "{class_name}:#{object_id.to_hex}"
1780 end
1781 end
1782
1783 redef class Bool
1784 # assert true.to_s == "true"
1785 # assert false.to_s == "false"
1786 redef fun to_s
1787 do
1788 if self then
1789 return once "true"
1790 else
1791 return once "false"
1792 end
1793 end
1794 end
1795
1796 redef class Int
1797
1798 # Wrapper of strerror C function
1799 private fun strerror_ext: NativeString is extern `{
1800 return strerror(recv);
1801 `}
1802
1803 # Returns a string describing error number
1804 fun strerror: String do return strerror_ext.to_s
1805
1806 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1807 # assume < to_c max const of char
1808 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1809 do
1810 var n: Int
1811 # Sign
1812 if self < 0 then
1813 n = - self
1814 s.chars[0] = '-'
1815 else if self == 0 then
1816 s.chars[0] = '0'
1817 return
1818 else
1819 n = self
1820 end
1821 # Fill digits
1822 var pos = digit_count(base) - 1
1823 while pos >= 0 and n > 0 do
1824 s.chars[pos] = (n % base).to_c
1825 n = n / base # /
1826 pos -= 1
1827 end
1828 end
1829
1830 # C function to convert an nit Int to a NativeString (char*)
1831 private fun native_int_to_s: NativeString is extern "native_int_to_s"
1832
1833 # return displayable int in base 10 and signed
1834 #
1835 # assert 1.to_s == "1"
1836 # assert (-123).to_s == "-123"
1837 redef fun to_s do
1838 return native_int_to_s.to_s
1839 end
1840
1841 # return displayable int in hexadecimal
1842 #
1843 # assert 1.to_hex == "1"
1844 # assert (-255).to_hex == "-ff"
1845 fun to_hex: String do return to_base(16,false)
1846
1847 # return displayable int in base base and signed
1848 fun to_base(base: Int, signed: Bool): String
1849 do
1850 var l = digit_count(base)
1851 var s = new FlatBuffer.from(" " * l)
1852 fill_buffer(s, base, signed)
1853 return s.to_s
1854 end
1855 end
1856
1857 redef class Float
1858 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1859 #
1860 # assert 12.34.to_s == "12.34"
1861 # assert (-0120.030).to_s == "-120.03"
1862 #
1863 # see `to_precision` for a custom precision.
1864 redef fun to_s do
1865 var str = to_precision( 3 )
1866 if is_inf != 0 or is_nan then return str
1867 var len = str.length
1868 for i in [0..len-1] do
1869 var j = len-1-i
1870 var c = str.chars[j]
1871 if c == '0' then
1872 continue
1873 else if c == '.' then
1874 return str.substring( 0, j+2 )
1875 else
1876 return str.substring( 0, j+1 )
1877 end
1878 end
1879 return str
1880 end
1881
1882 # `String` representation of `self` with the given number of `decimals`
1883 #
1884 # assert 12.345.to_precision(0) == "12"
1885 # assert 12.345.to_precision(3) == "12.345"
1886 # assert (-12.345).to_precision(3) == "-12.345"
1887 # assert (-0.123).to_precision(3) == "-0.123"
1888 # assert 0.999.to_precision(2) == "1.00"
1889 # assert 0.999.to_precision(4) == "0.9990"
1890 fun to_precision(decimals: Int): String
1891 do
1892 if is_nan then return "nan"
1893
1894 var isinf = self.is_inf
1895 if isinf == 1 then
1896 return "inf"
1897 else if isinf == -1 then
1898 return "-inf"
1899 end
1900
1901 if decimals == 0 then return self.to_i.to_s
1902 var f = self
1903 for i in [0..decimals[ do f = f * 10.0
1904 if self > 0.0 then
1905 f = f + 0.5
1906 else
1907 f = f - 0.5
1908 end
1909 var i = f.to_i
1910 if i == 0 then return "0." + "0"*decimals
1911
1912 # Prepare both parts of the float, before and after the "."
1913 var s = i.abs.to_s
1914 var sl = s.length
1915 var p1
1916 var p2
1917 if sl > decimals then
1918 # Has something before the "."
1919 p1 = s.substring(0, sl-decimals)
1920 p2 = s.substring(sl-decimals, decimals)
1921 else
1922 p1 = "0"
1923 p2 = "0"*(decimals-sl) + s
1924 end
1925
1926 if i < 0 then p1 = "-" + p1
1927
1928 return p1 + "." + p2
1929 end
1930
1931 # `self` representation with `nb` digits after the '.'.
1932 #
1933 # assert 12.345.to_precision_native(1) == "12.3"
1934 # assert 12.345.to_precision_native(2) == "12.35"
1935 # assert 12.345.to_precision_native(3) == "12.345"
1936 # assert 12.345.to_precision_native(4) == "12.3450"
1937 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1938 int size;
1939 char *str;
1940
1941 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1942 str = malloc(size + 1);
1943 sprintf(str, "%.*f", (int)nb, recv );
1944
1945 return NativeString_to_s( str );
1946 `}
1947 end
1948
1949 redef class Char
1950 # assert 'x'.to_s == "x"
1951 redef fun to_s
1952 do
1953 var s = new FlatBuffer.with_capacity(1)
1954 s.chars[0] = self
1955 return s.to_s
1956 end
1957
1958 # Returns true if the char is a numerical digit
1959 #
1960 # assert '0'.is_numeric
1961 # assert '9'.is_numeric
1962 # assert not 'a'.is_numeric
1963 # assert not '?'.is_numeric
1964 fun is_numeric: Bool
1965 do
1966 return self >= '0' and self <= '9'
1967 end
1968
1969 # Returns true if the char is an alpha digit
1970 #
1971 # assert 'a'.is_alpha
1972 # assert 'Z'.is_alpha
1973 # assert not '0'.is_alpha
1974 # assert not '?'.is_alpha
1975 fun is_alpha: Bool
1976 do
1977 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1978 end
1979
1980 # Returns true if the char is an alpha or a numeric digit
1981 #
1982 # assert 'a'.is_alphanumeric
1983 # assert 'Z'.is_alphanumeric
1984 # assert '0'.is_alphanumeric
1985 # assert '9'.is_alphanumeric
1986 # assert not '?'.is_alphanumeric
1987 fun is_alphanumeric: Bool
1988 do
1989 return self.is_numeric or self.is_alpha
1990 end
1991 end
1992
1993 redef class Collection[E]
1994 # Concatenate elements.
1995 redef fun to_s
1996 do
1997 var s = new FlatBuffer
1998 for e in self do if e != null then s.append(e.to_s)
1999 return s.to_s
2000 end
2001
2002 # Concatenate and separate each elements with `sep`.
2003 #
2004 # assert [1, 2, 3].join(":") == "1:2:3"
2005 # assert [1..3].join(":") == "1:2:3"
2006 fun join(sep: Text): String
2007 do
2008 if is_empty then return ""
2009
2010 var s = new FlatBuffer # Result
2011
2012 # Concat first item
2013 var i = iterator
2014 var e = i.item
2015 if e != null then s.append(e.to_s)
2016
2017 # Concat other items
2018 i.next
2019 while i.is_ok do
2020 s.append(sep)
2021 e = i.item
2022 if e != null then s.append(e.to_s)
2023 i.next
2024 end
2025 return s.to_s
2026 end
2027 end
2028
2029 redef class Array[E]
2030
2031 # Fast implementation
2032 redef fun to_s
2033 do
2034 var l = length
2035 if l == 0 then return ""
2036 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2037 var its = _items
2038 var na = new NativeArray[String](l)
2039 var i = 0
2040 var sl = 0
2041 var mypos = 0
2042 while i < l do
2043 var itsi = its[i]
2044 if itsi == null then
2045 i += 1
2046 continue
2047 end
2048 var tmp = itsi.to_s
2049 sl += tmp.length
2050 na[mypos] = tmp
2051 i += 1
2052 mypos += 1
2053 end
2054 var ns = new NativeString(sl + 1)
2055 ns[sl] = '\0'
2056 i = 0
2057 var off = 0
2058 while i < mypos do
2059 var tmp = na[i]
2060 var tpl = tmp.length
2061 if tmp isa FlatString then
2062 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2063 off += tpl
2064 else
2065 for j in tmp.substrings do
2066 var s = j.as(FlatString)
2067 var slen = s.length
2068 s.items.copy_to(ns, slen, s.index_from, off)
2069 off += slen
2070 end
2071 end
2072 i += 1
2073 end
2074 return ns.to_s_with_length(sl)
2075 end
2076 end
2077
2078 redef class Map[K,V]
2079 # Concatenate couple of 'key value'.
2080 # key and value are separated by `couple_sep`.
2081 # each couple is separated each couple with `sep`.
2082 #
2083 # var m = new ArrayMap[Int, String]
2084 # m[1] = "one"
2085 # m[10] = "ten"
2086 # assert m.join("; ", "=") == "1=one; 10=ten"
2087 fun join(sep: String, couple_sep: String): String
2088 do
2089 if is_empty then return ""
2090
2091 var s = new FlatBuffer # Result
2092
2093 # Concat first item
2094 var i = iterator
2095 var k = i.key
2096 var e = i.item
2097 s.append("{k}{couple_sep}{e or else "<null>"}")
2098
2099 # Concat other items
2100 i.next
2101 while i.is_ok do
2102 s.append(sep)
2103 k = i.key
2104 e = i.item
2105 s.append("{k}{couple_sep}{e or else "<null>"}")
2106 i.next
2107 end
2108 return s.to_s
2109 end
2110 end
2111
2112 ###############################################################################
2113 # Native classes #
2114 ###############################################################################
2115
2116 # Native strings are simple C char *
2117 extern class NativeString `{ char* `}
2118 super StringCapable
2119 # Creates a new NativeString with a capacity of `length`
2120 new(length: Int) is intern
2121 fun [](index: Int): Char is intern
2122 fun []=(index: Int, item: Char) is intern
2123 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2124
2125 # Position of the first nul character.
2126 fun cstring_length: Int
2127 do
2128 var l = 0
2129 while self[l] != '\0' do l += 1
2130 return l
2131 end
2132 fun atoi: Int is intern
2133 fun atof: Float is extern "atof"
2134
2135 redef fun to_s
2136 do
2137 return to_s_with_length(cstring_length)
2138 end
2139
2140 fun to_s_with_length(length: Int): FlatString
2141 do
2142 assert length >= 0
2143 var str = new FlatString.with_infos(self, length, 0, length - 1)
2144 return str
2145 end
2146
2147 fun to_s_with_copy: FlatString
2148 do
2149 var length = cstring_length
2150 var new_self = calloc_string(length + 1)
2151 copy_to(new_self, length, 0, 0)
2152 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2153 new_self[length] = '\0'
2154 str.real_items = new_self
2155 return str
2156 end
2157 end
2158
2159 # StringCapable objects can create native strings
2160 interface StringCapable
2161 protected fun calloc_string(size: Int): NativeString is intern
2162 end
2163
2164 redef class Sys
2165 private var args_cache: nullable Sequence[String]
2166
2167 # The arguments of the program as given by the OS
2168 fun program_args: Sequence[String]
2169 do
2170 if _args_cache == null then init_args
2171 return _args_cache.as(not null)
2172 end
2173
2174 # The name of the program as given by the OS
2175 fun program_name: String
2176 do
2177 return native_argv(0).to_s
2178 end
2179
2180 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2181 private fun init_args
2182 do
2183 var argc = native_argc
2184 var args = new Array[String].with_capacity(0)
2185 var i = 1
2186 while i < argc do
2187 args[i-1] = native_argv(i).to_s
2188 i += 1
2189 end
2190 _args_cache = args
2191 end
2192
2193 # First argument of the main C function.
2194 private fun native_argc: Int is intern
2195
2196 # Second argument of the main C function.
2197 private fun native_argv(i: Int): NativeString is intern
2198 end
2199
2200 # Comparator that efficienlty use `to_s` to compare things
2201 #
2202 # The comparaison call `to_s` on object and use the result to order things.
2203 #
2204 # var a = [1, 2, 3, 10, 20]
2205 # (new CachedAlphaComparator).sort(a)
2206 # assert a == [1, 10, 2, 20, 3]
2207 #
2208 # Internally the result of `to_s` is cached in a HashMap to counter
2209 # uneficient implementation of `to_s`.
2210 #
2211 # Note: it caching is not usefull, see `alpha_comparator`
2212 class CachedAlphaComparator
2213 super Comparator
2214 redef type COMPARED: Object
2215
2216 private var cache = new HashMap[Object, String]
2217
2218 private fun do_to_s(a: Object): String do
2219 if cache.has_key(a) then return cache[a]
2220 var res = a.to_s
2221 cache[a] = res
2222 return res
2223 end
2224
2225 redef fun compare(a, b) do
2226 return do_to_s(a) <=> do_to_s(b)
2227 end
2228 end
2229
2230 # see `alpha_comparator`
2231 private class AlphaComparator
2232 super Comparator
2233 redef fun compare(a, b) do return a.to_s <=> b.to_s
2234 end
2235
2236 # Stateless comparator that naively use `to_s` to compare things.
2237 #
2238 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2239 # on a single instace. See `CachedAlphaComparator` as an alternative.
2240 #
2241 # var a = [1, 2, 3, 10, 20]
2242 # alpha_comparator.sort(a)
2243 # assert a == [1, 10, 2, 20, 3]
2244 fun alpha_comparator: Comparator do return once new AlphaComparator
2245
2246 # The arguments of the program as given by the OS
2247 fun args: Sequence[String]
2248 do
2249 return sys.program_args
2250 end