lib/string: some cleaning, doc and unit tests
[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 intrude import collection # FIXME should be collection::array
19
20 `{
21 #include <stdio.h>
22 `}
23
24 ###############################################################################
25 # String #
26 ###############################################################################
27
28 # High-level abstraction for all text representations
29 abstract class Text
30 super Comparable
31 super StringCapable
32
33 redef type OTHER: Text
34
35 # Type of the view on self (.chars)
36 type SELFVIEW: StringCharView
37
38 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
39 type SELFTYPE: Text
40
41 # Gets a view on the chars of the Text object
42 #
43 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
44 fun chars: SELFVIEW is abstract
45
46 # Number of characters contained in self.
47 #
48 # assert "12345".length == 5
49 # assert "".length == 0
50 fun length: Int is abstract
51
52 # Create a substring.
53 #
54 # assert "abcd".substring(1, 2) == "bc"
55 # assert "abcd".substring(-1, 2) == "a"
56 # assert "abcd".substring(1, 0) == ""
57 # assert "abcd".substring(2, 5) == "cd"
58 #
59 # A `from` index < 0 will be replaced by 0.
60 # Unless a `count` value is > 0 at the same time.
61 # In this case, `from += count` and `count -= from`.
62 fun substring(from: Int, count: Int): SELFTYPE is abstract
63
64 # Concatenates `o` to `self`
65 #
66 # assert "hello" + "world" == "helloworld"
67 # assert "" + "hello" + "" == "hello"
68 fun +(o: Text): SELFTYPE is abstract
69
70 # Auto-concatenates self `i` times
71 #
72 # assert "abc" * 4 == "abcabcabcabc"
73 # assert "abc" * 1 == "abc"
74 # assert "abc" * 0 == ""
75 fun *(i: Int): SELFTYPE is abstract
76
77 # Is the current Text empty (== "")
78 #
79 # assert "".is_empty
80 # assert not "foo".is_empty
81 fun is_empty: Bool do return self.length == 0
82
83 # Returns an empty Text of the right type
84 #
85 # This method is used internally to get the right
86 # implementation of an empty string.
87 protected fun empty: SELFTYPE is abstract
88
89 # Gets the first char of the Text
90 #
91 # DEPRECATED : Use self.chars.first instead
92 fun first: Char do return self.chars[0]
93
94 # Access a character at `index` in the string.
95 #
96 # assert "abcd"[2] == 'c'
97 #
98 # DEPRECATED : Use self.chars.[] instead
99 fun [](index: Int): Char do return self.chars[index]
100
101 # Gets the index of the first occurence of 'c'
102 #
103 # Returns -1 if not found
104 #
105 # DEPRECATED : Use self.chars.index_of instead
106 fun index_of(c: Char): Int
107 do
108 return index_of_from(c, 0)
109 end
110
111 # Gets the last char of self
112 #
113 # DEPRECATED : Use self.chars.last instead
114 fun last: Char do return self.chars[length-1]
115
116 # Gets the index of the first occurence of ´c´ starting from ´pos´
117 #
118 # Returns -1 if not found
119 #
120 # DEPRECATED : Use self.chars.index_of_from instead
121 fun index_of_from(c: Char, pos: Int): Int
122 do
123 var iter = self.chars.iterator_from(pos)
124 while iter.is_ok do
125 if iter.item == c then return iter.index
126 end
127 return -1
128 end
129
130 # Gets the last index of char ´c´
131 #
132 # Returns -1 if not found
133 #
134 # DEPRECATED : Use self.chars.last_index_of instead
135 fun last_index_of(c: Char): Int
136 do
137 return last_index_of_from(c, length - 1)
138 end
139
140 # Return a null terminated char *
141 fun to_cstring: NativeString do return flatten.to_cstring
142
143 # The index of the last occurrence of an element starting from pos (in reverse order).
144 #
145 # var s = "/etc/bin/test/test.nit"
146 # assert s.last_index_of_from('/', s.length-1) == 13
147 # assert s.last_index_of_from('/', 12) == 8
148 #
149 # Returns -1 if not found
150 #
151 # DEPRECATED : Use self.chars.last_index_of_from instead
152 fun last_index_of_from(item: Char, pos: Int): Int
153 do
154 var iter = self.chars.reverse_iterator_from(pos)
155 while iter.is_ok do
156 if iter.item == item then return iter.index
157 iter.next
158 end
159 return -1
160 end
161
162 # Gets an iterator on the chars of self
163 #
164 # DEPRECATED : Use self.chars.iterator instead
165 fun iterator: Iterator[Char]
166 do
167 return self.chars.iterator
168 end
169
170 # Is 'c' contained in self ?
171 #
172 # DEPRECATED : Use self.chars.has instead
173 fun has(c: Char): Bool
174 do
175 return self.chars.has(c)
176 end
177
178 # Gets an Array containing the chars of self
179 #
180 # DEPRECATED : Use self.chars.to_a instead
181 fun to_a: Array[Char] do return chars.to_a
182
183 # Create a substring from `self` beginning at the `from` position
184 #
185 # assert "abcd".substring_from(1) == "bcd"
186 # assert "abcd".substring_from(-1) == "abcd"
187 # assert "abcd".substring_from(2) == "cd"
188 #
189 # As with substring, a `from` index < 0 will be replaced by 0
190 fun substring_from(from: Int): SELFTYPE
191 do
192 if from > self.length then return empty
193 if from < 0 then from = 0
194 return substring(from, length - from)
195 end
196
197 # Returns a reversed version of self
198 #
199 # assert "hello".reversed == "olleh"
200 # assert "bob".reversed == "bob"
201 # assert "".reversed == ""
202 fun reversed: SELFTYPE is abstract
203
204 # Does self have a substring `str` starting from position `pos`?
205 #
206 # assert "abcd".has_substring("bc",1) == true
207 # assert "abcd".has_substring("bc",2) == false
208 fun has_substring(str: String, pos: Int): Bool
209 do
210 var myiter = self.chars.iterator_from(pos)
211 var itsiter = str.iterator
212 while myiter.is_ok and itsiter.is_ok do
213 if myiter.item != itsiter.item then return false
214 myiter.next
215 itsiter.next
216 end
217 if itsiter.is_ok then return false
218 return true
219 end
220
221 # Is this string prefixed by `prefix`?
222 #
223 # assert "abcd".has_prefix("ab") == true
224 # assert "abcbc".has_prefix("bc") == false
225 # assert "ab".has_prefix("abcd") == false
226 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
227
228 # Is this string suffixed by `suffix`?
229 #
230 # assert "abcd".has_suffix("abc") == false
231 # assert "abcd".has_suffix("bcd") == true
232 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
233
234 # If `self` contains only digits, return the corresponding integer
235 #
236 # assert "123".to_i == 123
237 # assert "-1".to_i == -1
238 fun to_i: Int
239 do
240 # Shortcut
241 return to_s.to_cstring.atoi
242 end
243
244 # If `self` contains a float, return the corresponding float
245 #
246 # assert "123".to_f == 123.0
247 # assert "-1".to_f == -1.0
248 # assert "-1.2e-3".to_f == -0.0012
249 fun to_f: Float
250 do
251 # Shortcut
252 return to_s.to_cstring.atof
253 end
254
255 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
256 #
257 # assert "ff".to_hex == 255
258 fun to_hex: Int do return a_to(16)
259
260 # If `self` contains only digits and letters, return the corresponding integer in a given base
261 #
262 # assert "120".a_to(3) == 15
263 fun a_to(base: Int) : Int
264 do
265 var i = 0
266 var neg = false
267
268 for c in self.chars
269 do
270 var v = c.to_i
271 if v > base then
272 if neg then
273 return -i
274 else
275 return i
276 end
277 else if v < 0 then
278 neg = true
279 else
280 i = i * base + v
281 end
282 end
283 if neg then
284 return -i
285 else
286 return i
287 end
288 end
289
290 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
291 #
292 # assert "123".is_numeric == true
293 # assert "1.2".is_numeric == true
294 # assert "1,2".is_numeric == true
295 # assert "1..2".is_numeric == false
296 fun is_numeric: Bool
297 do
298 var has_point_or_comma = false
299 for i in self.chars
300 do
301 if not i.is_numeric
302 then
303 if (i == '.' or i == ',') and not has_point_or_comma
304 then
305 has_point_or_comma = true
306 else
307 return false
308 end
309 end
310 end
311 return true
312 end
313
314 # A upper case version of `self`
315 #
316 # assert "Hello World!".to_upper == "HELLO WORLD!"
317 fun to_upper: SELFTYPE is abstract
318
319 # A lower case version of `self`
320 #
321 # assert "Hello World!".to_lower == "hello world!"
322 fun to_lower : SELFTYPE is abstract
323
324 # Removes the whitespaces at the beginning of self
325 #
326 # assert " \n\thello \n\t".l_trim == "hello \n\t"
327 #
328 # A whitespace is defined as any character which ascii value is less than or equal to 32
329 fun l_trim: SELFTYPE
330 do
331 var iter = self.chars.iterator
332 while iter.is_ok do
333 if iter.item.ascii > 32 then break
334 iter.next
335 end
336 if iter.index == length then return self.empty
337 return self.substring_from(iter.index)
338 end
339
340 # Removes the whitespaces at the end of self
341 #
342 # assert " \n\thello \n\t".r_trim == " \n\thello"
343 #
344 # A whitespace is defined as any character which ascii value is less than or equal to 32
345 fun r_trim: SELFTYPE
346 do
347 var iter = self.chars.reverse_iterator
348 while iter.is_ok do
349 if iter.item.ascii > 32 then break
350 iter.next
351 end
352 if iter.index == length then return self.empty
353 return self.substring(0, iter.index + 1)
354 end
355
356 # Trims trailing and preceding white spaces
357 # A whitespace is defined as any character which ascii value is less than or equal to 32
358 #
359 # assert " Hello World ! ".trim == "Hello World !"
360 # assert "\na\nb\tc\t".trim == "a\nb\tc"
361 fun trim: SELFTYPE do return (self.l_trim).r_trim
362
363 # Mangle a string to be a unique string only made of alphanumeric characters
364 fun to_cmangle: String
365 do
366 var res = new FlatBuffer
367 var underscore = false
368 for c in self.chars do
369 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
370 res.add(c)
371 underscore = false
372 continue
373 end
374 if underscore then
375 res.append('_'.ascii.to_s)
376 res.add('d')
377 end
378 if c >= '0' and c <= '9' then
379 res.add(c)
380 underscore = false
381 else if c == '_' then
382 res.add(c)
383 underscore = true
384 else
385 res.add('_')
386 res.append(c.ascii.to_s)
387 res.add('d')
388 underscore = false
389 end
390 end
391 return res.to_s
392 end
393
394 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
395 #
396 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
397 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
398 fun escape_to_c: String
399 do
400 var b = new FlatBuffer
401 for c in self.chars do
402 if c == '\n' then
403 b.append("\\n")
404 else if c == '\0' then
405 b.append("\\0")
406 else if c == '"' then
407 b.append("\\\"")
408 else if c == '\'' then
409 b.append("\\\'")
410 else if c == '\\' then
411 b.append("\\\\")
412 else if c.ascii < 32 then
413 b.append("\\{c.ascii.to_base(8, false)}")
414 else
415 b.add(c)
416 end
417 end
418 return b.to_s
419 end
420
421 # Escape additionnal characters
422 # The result might no be legal in C but be used in other languages
423 #
424 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
425 fun escape_more_to_c(chars: String): String
426 do
427 var b = new FlatBuffer
428 for c in escape_to_c do
429 if chars.chars.has(c) then
430 b.add('\\')
431 end
432 b.add(c)
433 end
434 return b.to_s
435 end
436
437 # Escape to C plus braces
438 #
439 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
440 fun escape_to_nit: String do return escape_more_to_c("\{\}")
441
442 # Return a string where Nit escape sequences are transformed.
443 #
444 # var s = "\\n"
445 # assert s.length == 2
446 # var u = s.unescape_nit
447 # assert u.length == 1
448 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
449 fun unescape_nit: String
450 do
451 var res = new FlatBuffer.with_capacity(self.length)
452 var was_slash = false
453 for c in self do
454 if not was_slash then
455 if c == '\\' then
456 was_slash = true
457 else
458 res.add(c)
459 end
460 continue
461 end
462 was_slash = false
463 if c == 'n' then
464 res.add('\n')
465 else if c == 'r' then
466 res.add('\r')
467 else if c == 't' then
468 res.add('\t')
469 else if c == '0' then
470 res.add('\0')
471 else
472 res.add(c)
473 end
474 end
475 return res.to_s
476 end
477
478 # Equality of text
479 # Two pieces of text are equals if thez have the same characters in the same order.
480 #
481 # assert "hello" == "hello"
482 # assert "hello" != "HELLO"
483 # assert "hello" == "hel"+"lo"
484 #
485 # Things that are not Text are not equal.
486 #
487 # assert "9" != '9'
488 # assert "9" != ['9']
489 # assert "9" != 9
490 #
491 # assert "9".chars.first == '9' # equality of Char
492 # assert "9".chars == ['9'] # equality of Sequence
493 # assert "9".to_i == 9 # equality of Int
494 redef fun ==(o)
495 do
496 if o == null then return false
497 if not o isa Text then return false
498 if self.is_same_instance(o) then return true
499 if self.length != o.length then return false
500 return self.chars == o.chars
501 end
502
503 # Lexicographical comparaison
504 #
505 # assert "abc" < "xy"
506 # assert "ABC" < "abc"
507 redef fun <(o)
508 do
509 return self.chars < o.chars
510 end
511
512 # Flat representation of self
513 fun flatten: FlatText is abstract
514
515 private var hash_cache: nullable Int = null
516
517 redef fun hash
518 do
519 if hash_cache == null then
520 # djb2 hash algorithm
521 var h = 5381
522 var i = length - 1
523
524 for char in self.chars do
525 h = (h * 32) + h + char.ascii
526 i -= 1
527 end
528
529 hash_cache = h
530 end
531 return hash_cache.as(not null)
532 end
533
534 end
535
536 # All kinds of array-based text representations.
537 abstract class FlatText
538 super Text
539
540 private var items: NativeString
541
542 # Real items, used as cache for to_cstring is called
543 private var real_items: nullable NativeString = null
544
545 redef var length: Int
546
547 init do end
548
549 redef fun output
550 do
551 var i = 0
552 while i < length do
553 items[i].output
554 i += 1
555 end
556 end
557
558 redef fun flatten do return self
559 end
560
561 # Abstract class for the SequenceRead compatible
562 # views on String and Buffer objects
563 abstract class StringCharView
564 super SequenceRead[Char]
565 super Comparable
566
567 type SELFTYPE: Text
568
569 redef type OTHER: StringCharView
570
571 private var target: SELFTYPE
572
573 private init(tgt: SELFTYPE)
574 do
575 target = tgt
576 end
577
578 redef fun is_empty do return target.is_empty
579
580 redef fun length do return target.length
581
582 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
583
584 # Gets a new Iterator starting at position `pos`
585 #
586 # var iter = "abcd".chars.iterator_from(2)
587 # assert iter.to_a == ['c', 'd']
588 fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
589
590 # Gets an iterator starting at the end and going backwards
591 #
592 # var reviter = "hello".chars.reverse_iterator
593 # assert reviter.to_a == ['o', 'l', 'l', 'e', 'h']
594 fun reverse_iterator: IndexedIterator[Char] do return self.reverse_iterator_from(self.length - 1)
595
596 # Gets an iterator on the chars of self starting from `pos`
597 #
598 # var reviter = "hello".chars.reverse_iterator_from(2)
599 # assert reviter.to_a == ['l', 'e', 'h']
600 fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
601
602 redef fun has(c: Char): Bool
603 do
604 for i in self do
605 if i == c then return true
606 end
607 return false
608 end
609
610 redef fun ==(other)
611 do
612 if other == null then return false
613 if not other isa StringCharView then return false
614 var other_chars = other.iterator
615 for i in self do
616 if i != other_chars.item then return false
617 other_chars.next
618 end
619 return true
620 end
621
622 redef fun <(other)
623 do
624 var self_chars = self.iterator
625 var other_chars = other.iterator
626
627 while self_chars.is_ok and other_chars.is_ok do
628 if self_chars.item < other_chars.item then return true
629 if self_chars.item > other_chars.item then return false
630 self_chars.next
631 other_chars.next
632 end
633
634 if self_chars.is_ok then
635 return false
636 else
637 return true
638 end
639 end
640 end
641
642 # View on Buffer objects, extends Sequence
643 # for mutation operations
644 abstract class BufferCharView
645 super StringCharView
646 super Sequence[Char]
647
648 redef type SELFTYPE: Buffer
649
650 end
651
652 abstract class String
653 super Text
654
655 redef type SELFTYPE: String
656
657 redef fun to_s do return self
658
659 end
660
661 # Immutable strings of characters.
662 class FlatString
663 super FlatText
664 super String
665
666 redef type SELFTYPE: FlatString
667
668 # Index in _items of the start of the string
669 private var index_from: Int
670
671 # Indes in _items of the last item of the string
672 private var index_to: Int
673
674 redef var chars: SELFVIEW = new FlatStringCharView(self)
675
676 ################################################
677 # AbstractString specific methods #
678 ################################################
679
680 redef fun [](index) do
681 assert index >= 0
682 # Check that the index (+ index_from) is not larger than indexTo
683 # In other terms, if the index is valid
684 assert (index + index_from) <= index_to
685 return items[index + index_from]
686 end
687
688 redef fun reversed
689 do
690 var native = calloc_string(self.length + 1)
691 var reviter = chars.reverse_iterator
692 var pos = 0
693 while reviter.is_ok do
694 native[pos] = reviter.item
695 pos += 1
696 reviter.next
697 end
698 return native.to_s_with_length(self.length)
699 end
700
701 redef fun substring(from, count)
702 do
703 assert count >= 0
704
705 if from < 0 then
706 count += from
707 if count < 0 then count = 0
708 from = 0
709 end
710
711 var realFrom = index_from + from
712
713 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
714
715 if count == 0 then return empty
716
717 var to = realFrom + count - 1
718
719 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
720 end
721
722 redef fun empty do return "".as(FlatString)
723
724 redef fun to_upper
725 do
726 var outstr = calloc_string(self.length + 1)
727 var out_index = 0
728
729 var myitems = self.items
730 var index_from = self.index_from
731 var max = self.index_to
732
733 while index_from <= max do
734 outstr[out_index] = myitems[index_from].to_upper
735 out_index += 1
736 index_from += 1
737 end
738
739 outstr[self.length] = '\0'
740
741 return outstr.to_s_with_length(self.length)
742 end
743
744 redef fun to_lower
745 do
746 var outstr = calloc_string(self.length + 1)
747 var out_index = 0
748
749 var myitems = self.items
750 var index_from = self.index_from
751 var max = self.index_to
752
753 while index_from <= max do
754 outstr[out_index] = myitems[index_from].to_lower
755 out_index += 1
756 index_from += 1
757 end
758
759 outstr[self.length] = '\0'
760
761 return outstr.to_s_with_length(self.length)
762 end
763
764 redef fun output
765 do
766 var i = self.index_from
767 var imax = self.index_to
768 while i <= imax do
769 items[i].output
770 i += 1
771 end
772 end
773
774 ##################################################
775 # String Specific Methods #
776 ##################################################
777
778 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
779 do
780 self.items = items
781 length = len
782 index_from = from
783 index_to = to
784 end
785
786 redef fun to_cstring: NativeString
787 do
788 if real_items != null then return real_items.as(not null)
789 if index_from > 0 or index_to != items.cstring_length - 1 then
790 var newItems = calloc_string(length + 1)
791 self.items.copy_to(newItems, length, index_from, 0)
792 newItems[length] = '\0'
793 self.real_items = newItems
794 return newItems
795 end
796 return items
797 end
798
799 redef fun ==(other)
800 do
801 if not other isa FlatString then return super
802
803 if self.object_id == other.object_id then return true
804
805 var my_length = length
806
807 if other.length != my_length then return false
808
809 var my_index = index_from
810 var its_index = other.index_from
811
812 var last_iteration = my_index + my_length
813
814 var itsitems = other.items
815 var myitems = self.items
816
817 while my_index < last_iteration do
818 if myitems[my_index] != itsitems[its_index] then return false
819 my_index += 1
820 its_index += 1
821 end
822
823 return true
824 end
825
826 redef fun <(other)
827 do
828 if not other isa FlatString then return super
829
830 if self.object_id == other.object_id then return false
831
832 var my_curr_char : Char
833 var its_curr_char : Char
834
835 var curr_id_self = self.index_from
836 var curr_id_other = other.index_from
837
838 var my_items = self.items
839 var its_items = other.items
840
841 var my_length = self.length
842 var its_length = other.length
843
844 var max_iterations = curr_id_self + my_length
845
846 while curr_id_self < max_iterations do
847 my_curr_char = my_items[curr_id_self]
848 its_curr_char = its_items[curr_id_other]
849
850 if my_curr_char != its_curr_char then
851 if my_curr_char < its_curr_char then return true
852 return false
853 end
854
855 curr_id_self += 1
856 curr_id_other += 1
857 end
858
859 return my_length < its_length
860 end
861
862 redef fun +(s)
863 do
864 var my_length = self.length
865 var its_length = s.length
866
867 var total_length = my_length + its_length
868
869 var target_string = calloc_string(my_length + its_length + 1)
870
871 self.items.copy_to(target_string, my_length, index_from, 0)
872 if s isa FlatString then
873 s.items.copy_to(target_string, its_length, s.index_from, my_length)
874 else if s isa FlatBuffer then
875 s.items.copy_to(target_string, its_length, 0, my_length)
876 else
877 var curr_pos = my_length
878 for i in s.chars do
879 target_string[curr_pos] = i
880 curr_pos += 1
881 end
882 end
883
884 target_string[total_length] = '\0'
885
886 return target_string.to_s_with_length(total_length)
887 end
888
889 redef fun *(i)
890 do
891 assert i >= 0
892
893 var my_length = self.length
894
895 var final_length = my_length * i
896
897 var my_items = self.items
898
899 var target_string = calloc_string((final_length) + 1)
900
901 target_string[final_length] = '\0'
902
903 var current_last = 0
904
905 for iteration in [1 .. i] do
906 my_items.copy_to(target_string, my_length, 0, current_last)
907 current_last += my_length
908 end
909
910 return target_string.to_s_with_length(final_length)
911 end
912
913 redef fun hash
914 do
915 if hash_cache == null then
916 # djb2 hash algorythm
917 var h = 5381
918 var i = length - 1
919
920 var myitems = items
921 var strStart = index_from
922
923 i += strStart
924
925 while i >= strStart do
926 h = (h * 32) + h + self.items[i].ascii
927 i -= 1
928 end
929
930 hash_cache = h
931 end
932
933 return hash_cache.as(not null)
934 end
935 end
936
937 private class FlatStringReverseIterator
938 super IndexedIterator[Char]
939
940 var target: FlatString
941
942 var target_items: NativeString
943
944 var curr_pos: Int
945
946 init with_pos(tgt: FlatString, pos: Int)
947 do
948 target = tgt
949 target_items = tgt.items
950 curr_pos = pos + tgt.index_from
951 end
952
953 redef fun is_ok do return curr_pos >= 0
954
955 redef fun item do return target_items[curr_pos]
956
957 redef fun next do curr_pos -= 1
958
959 redef fun index do return curr_pos - target.index_from
960
961 end
962
963 private class FlatStringIterator
964 super IndexedIterator[Char]
965
966 var target: FlatString
967
968 var target_items: NativeString
969
970 var curr_pos: Int
971
972 init with_pos(tgt: FlatString, pos: Int)
973 do
974 target = tgt
975 target_items = tgt.items
976 curr_pos = pos + target.index_from
977 end
978
979 redef fun is_ok do return curr_pos <= target.index_to
980
981 redef fun item do return target_items[curr_pos]
982
983 redef fun next do curr_pos += 1
984
985 redef fun index do return curr_pos - target.index_from
986
987 end
988
989 private class FlatStringCharView
990 super StringCharView
991
992 redef type SELFTYPE: FlatString
993
994 redef fun [](index)
995 do
996 # Check that the index (+ index_from) is not larger than indexTo
997 # In other terms, if the index is valid
998 assert index >= 0
999 assert (index + target.index_from) <= target.index_to
1000 return target.items[index + target.index_from]
1001 end
1002
1003 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1004
1005 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1006
1007 end
1008
1009 abstract class Buffer
1010 super Text
1011
1012 redef type SELFVIEW: BufferCharView
1013 redef type SELFTYPE: Buffer
1014
1015 # Specific implementations MUST set this to `true` in order to invalidate caches
1016 protected var is_dirty = true
1017
1018 # Modifies the char contained at pos `index`
1019 #
1020 # DEPRECATED : Use self.chars.[]= instead
1021 fun []=(index: Int, item: Char) is abstract
1022
1023 # Adds a char `c` at the end of self
1024 #
1025 # DEPRECATED : Use self.chars.add instead
1026 fun add(c: Char) is abstract
1027
1028 # Clears the buffer
1029 #
1030 # var b = new FlatBuffer
1031 # b.append "hello"
1032 # assert not b.is_empty
1033 # b.clear
1034 # assert b.is_empty
1035 fun clear is abstract
1036
1037 # Enlarges the subsequent array containing the chars of self
1038 fun enlarge(cap: Int) is abstract
1039
1040 # Adds the content of text `s` at the end of self
1041 #
1042 # var b = new FlatBuffer
1043 # b.append "hello"
1044 # b.append "world"
1045 # assert b == "helloworld"
1046 fun append(s: Text) is abstract
1047
1048 redef fun hash
1049 do
1050 if is_dirty then hash_cache = null
1051 return super
1052 end
1053
1054 end
1055
1056 # Mutable strings of characters.
1057 class FlatBuffer
1058 super FlatText
1059 super Buffer
1060
1061 redef type SELFTYPE: FlatBuffer
1062
1063 redef var chars: SELFVIEW = new FlatBufferCharView(self)
1064
1065 private var capacity: Int
1066
1067 redef fun []=(index, item)
1068 do
1069 is_dirty = true
1070 if index == length then
1071 add(item)
1072 return
1073 end
1074 assert index >= 0 and index < length
1075 items[index] = item
1076 end
1077
1078 redef fun add(c)
1079 do
1080 is_dirty = true
1081 if capacity <= length then enlarge(length + 5)
1082 items[length] = c
1083 length += 1
1084 end
1085
1086 redef fun clear do
1087 is_dirty = true
1088 length = 0
1089 end
1090
1091 redef fun empty do return new FlatBuffer
1092
1093 redef fun enlarge(cap)
1094 do
1095 is_dirty = true
1096 var c = capacity
1097 if cap <= c then return
1098 while c <= cap do c = c * 2 + 2
1099 var a = calloc_string(c+1)
1100 items.copy_to(a, length, 0, 0)
1101 items = a
1102 capacity = c
1103 items.copy_to(a, length, 0, 0)
1104 end
1105
1106 redef fun to_s: String
1107 do
1108 return to_cstring.to_s_with_length(length)
1109 end
1110
1111 redef fun to_cstring
1112 do
1113 if is_dirty then
1114 var new_native = calloc_string(length + 1)
1115 new_native[length] = '\0'
1116 items.copy_to(new_native, length, 0, 0)
1117 real_items = new_native
1118 is_dirty = false
1119 end
1120 return real_items.as(not null)
1121 end
1122
1123 # Create a new empty string.
1124 init do with_capacity(5)
1125
1126 init from(s: Text)
1127 do
1128 capacity = s.length + 1
1129 length = s.length
1130 items = calloc_string(capacity)
1131 if s isa FlatString then
1132 s.items.copy_to(items, length, s.index_from, 0)
1133 else if s isa FlatBuffer then
1134 s.items.copy_to(items, length, 0, 0)
1135 else
1136 var curr_pos = 0
1137 for i in s.chars do
1138 items[curr_pos] = i
1139 curr_pos += 1
1140 end
1141 end
1142 end
1143
1144 # Create a new empty string with a given capacity.
1145 init with_capacity(cap: Int)
1146 do
1147 assert cap >= 0
1148 # _items = new NativeString.calloc(cap)
1149 items = calloc_string(cap+1)
1150 capacity = cap
1151 length = 0
1152 end
1153
1154 redef fun append(s)
1155 do
1156 is_dirty = true
1157 var sl = s.length
1158 if capacity < length + sl then enlarge(length + sl)
1159 if s isa FlatString then
1160 s.items.copy_to(items, sl, s.index_from, length)
1161 else if s isa FlatBuffer then
1162 s.items.copy_to(items, sl, 0, length)
1163 else
1164 var curr_pos = self.length
1165 for i in s.chars do
1166 items[curr_pos] = i
1167 curr_pos += 1
1168 end
1169 end
1170 length += sl
1171 end
1172
1173 # Copies the content of self in `dest`
1174 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1175 do
1176 var self_chars = self.chars
1177 var dest_chars = dest.chars
1178 for i in [0..len-1] do
1179 dest_chars[new_start+i] = self_chars[start+i]
1180 end
1181 end
1182
1183 redef fun substring(from, count)
1184 do
1185 assert count >= 0
1186 count += from
1187 if from < 0 then from = 0
1188 if count > length then count = length
1189 if from < count then
1190 var r = new FlatBuffer.with_capacity(count - from)
1191 while from < count do
1192 r.chars.push(items[from])
1193 from += 1
1194 end
1195 return r
1196 else
1197 return new FlatBuffer
1198 end
1199 end
1200
1201 redef fun reversed
1202 do
1203 var new_buf = new FlatBuffer.with_capacity(self.length)
1204 var reviter = self.chars.reverse_iterator
1205 while reviter.is_ok do
1206 new_buf.add(reviter.item)
1207 reviter.next
1208 end
1209 return new_buf
1210 end
1211
1212 redef fun +(other)
1213 do
1214 var new_buf = new FlatBuffer.with_capacity(self.length + other.length)
1215 new_buf.append(self)
1216 new_buf.append(other)
1217 return new_buf
1218 end
1219
1220 redef fun *(repeats)
1221 do
1222 var new_buf = new FlatBuffer.with_capacity(self.length * repeats)
1223 for i in [0..repeats[ do
1224 new_buf.append(self)
1225 end
1226 return new_buf
1227 end
1228 end
1229
1230 private class FlatBufferReverseIterator
1231 super IndexedIterator[Char]
1232
1233 var target: FlatBuffer
1234
1235 var target_items: NativeString
1236
1237 var curr_pos: Int
1238
1239 init with_pos(tgt: FlatBuffer, pos: Int)
1240 do
1241 target = tgt
1242 target_items = tgt.items
1243 curr_pos = pos
1244 end
1245
1246 redef fun index do return curr_pos
1247
1248 redef fun is_ok do return curr_pos >= 0
1249
1250 redef fun item do return target_items[curr_pos]
1251
1252 redef fun next do curr_pos -= 1
1253
1254 end
1255
1256 private class FlatBufferCharView
1257 super BufferCharView
1258 super StringCapable
1259
1260 redef type SELFTYPE: FlatBuffer
1261
1262 redef fun [](index) do return target.items[index]
1263
1264 redef fun []=(index, item)
1265 do
1266 assert index >= 0 and index <= length
1267 if index == length then
1268 add(item)
1269 return
1270 end
1271 target.items[index] = item
1272 end
1273
1274 redef fun push(c)
1275 do
1276 target.add(c)
1277 end
1278
1279 redef fun add(c)
1280 do
1281 target.add(c)
1282 end
1283
1284 fun enlarge(cap: Int)
1285 do
1286 target.enlarge(cap)
1287 end
1288
1289 redef fun append(s)
1290 do
1291 var my_items = target.items
1292 var s_length = s.length
1293 if target.capacity < s.length then enlarge(s_length + target.length)
1294 end
1295
1296 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1297
1298 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1299
1300 end
1301
1302 private class FlatBufferIterator
1303 super IndexedIterator[Char]
1304
1305 var target: FlatBuffer
1306
1307 var target_items: NativeString
1308
1309 var curr_pos: Int
1310
1311 init with_pos(tgt: FlatBuffer, pos: Int)
1312 do
1313 target = tgt
1314 target_items = tgt.items
1315 curr_pos = pos
1316 end
1317
1318 redef fun index do return curr_pos
1319
1320 redef fun is_ok do return curr_pos < target.length
1321
1322 redef fun item do return target_items[curr_pos]
1323
1324 redef fun next do curr_pos += 1
1325
1326 end
1327
1328 ###############################################################################
1329 # Refinement #
1330 ###############################################################################
1331
1332 redef class Object
1333 # User readable representation of `self`.
1334 fun to_s: String do return inspect
1335
1336 # The class name of the object in NativeString format.
1337 private fun native_class_name: NativeString is intern
1338
1339 # The class name of the object.
1340 #
1341 # assert 5.class_name == "Int"
1342 fun class_name: String do return native_class_name.to_s
1343
1344 # Developer readable representation of `self`.
1345 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1346 fun inspect: String
1347 do
1348 return "<{inspect_head}>"
1349 end
1350
1351 # Return "CLASSNAME:#OBJECTID".
1352 # This function is mainly used with the redefinition of the inspect method
1353 protected fun inspect_head: String
1354 do
1355 return "{class_name}:#{object_id.to_hex}"
1356 end
1357
1358 protected fun args: Sequence[String]
1359 do
1360 return sys.args
1361 end
1362 end
1363
1364 redef class Bool
1365 # assert true.to_s == "true"
1366 # assert false.to_s == "false"
1367 redef fun to_s
1368 do
1369 if self then
1370 return once "true"
1371 else
1372 return once "false"
1373 end
1374 end
1375 end
1376
1377 redef class Int
1378 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1379 # assume < to_c max const of char
1380 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1381 do
1382 var n: Int
1383 # Sign
1384 if self < 0 then
1385 n = - self
1386 s.chars[0] = '-'
1387 else if self == 0 then
1388 s.chars[0] = '0'
1389 return
1390 else
1391 n = self
1392 end
1393 # Fill digits
1394 var pos = digit_count(base) - 1
1395 while pos >= 0 and n > 0 do
1396 s.chars[pos] = (n % base).to_c
1397 n = n / base # /
1398 pos -= 1
1399 end
1400 end
1401
1402 # C function to convert an nit Int to a NativeString (char*)
1403 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1404
1405 # return displayable int in base 10 and signed
1406 #
1407 # assert 1.to_s == "1"
1408 # assert (-123).to_s == "-123"
1409 redef fun to_s do
1410 var len = digit_count(10)
1411 return native_int_to_s(len).to_s_with_length(len)
1412 end
1413
1414 # return displayable int in hexadecimal
1415 #
1416 # assert 1.to_hex == "1"
1417 # assert (-255).to_hex == "-ff"
1418 fun to_hex: String do return to_base(16,false)
1419
1420 # return displayable int in base base and signed
1421 fun to_base(base: Int, signed: Bool): String
1422 do
1423 var l = digit_count(base)
1424 var s = new FlatBuffer.from(" " * l)
1425 fill_buffer(s, base, signed)
1426 return s.to_s
1427 end
1428 end
1429
1430 redef class Float
1431 # Pretty print self, print needoed decimals up to a max of 3.
1432 #
1433 # assert 12.34.to_s == "12.34"
1434 # assert (-0120.03450).to_s == "-120.035"
1435 #
1436 # see `to_precision` for a different precision.
1437 redef fun to_s do
1438 var str = to_precision( 3 )
1439 if is_inf != 0 or is_nan then return str
1440 var len = str.length
1441 for i in [0..len-1] do
1442 var j = len-1-i
1443 var c = str.chars[j]
1444 if c == '0' then
1445 continue
1446 else if c == '.' then
1447 return str.substring( 0, j+2 )
1448 else
1449 return str.substring( 0, j+1 )
1450 end
1451 end
1452 return str
1453 end
1454
1455 # `self` representation with `nb` digits after the '.'.
1456 #
1457 # assert 12.345.to_precision(1) == "12.3"
1458 # assert 12.345.to_precision(2) == "12.35"
1459 # assert 12.345.to_precision(3) == "12.345"
1460 # assert 12.345.to_precision(4) == "12.3450"
1461 fun to_precision(nb: Int): String
1462 do
1463 if is_nan then return "nan"
1464
1465 var isinf = self.is_inf
1466 if isinf == 1 then
1467 return "inf"
1468 else if isinf == -1 then
1469 return "-inf"
1470 end
1471
1472 if nb == 0 then return self.to_i.to_s
1473 var f = self
1474 for i in [0..nb[ do f = f * 10.0
1475 if self > 0.0 then
1476 f = f + 0.5
1477 else
1478 f = f - 0.5
1479 end
1480 var i = f.to_i
1481 if i == 0 then return "0.0"
1482 var s = i.to_s
1483 var sl = s.length
1484 if sl > nb then
1485 var p1 = s.substring(0, s.length-nb)
1486 var p2 = s.substring(s.length-nb, nb)
1487 return p1 + "." + p2
1488 else
1489 return "0." + ("0"*(nb-sl)) + s
1490 end
1491 end
1492
1493 # `self` representation with `nb` digits after the '.'.
1494 #
1495 # assert 12.345.to_precision_native(1) == "12.3"
1496 # assert 12.345.to_precision_native(2) == "12.35"
1497 # assert 12.345.to_precision_native(3) == "12.345"
1498 # assert 12.345.to_precision_native(4) == "12.3450"
1499 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1500 int size;
1501 char *str;
1502
1503 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1504 str = malloc(size + 1);
1505 sprintf(str, "%.*f", (int)nb, recv );
1506
1507 return NativeString_to_s( str );
1508 `}
1509 end
1510
1511 redef class Char
1512 # assert 'x'.to_s == "x"
1513 redef fun to_s
1514 do
1515 var s = new FlatBuffer.with_capacity(1)
1516 s.chars[0] = self
1517 return s.to_s
1518 end
1519
1520 # Returns true if the char is a numerical digit
1521 #
1522 # assert '0'.is_numeric
1523 # assert '9'.is_numeric
1524 # assert not 'a'.is_numeric
1525 # assert not '?'.is_numeric
1526 fun is_numeric: Bool
1527 do
1528 return self >= '0' and self <= '9'
1529 end
1530
1531 # Returns true if the char is an alpha digit
1532 #
1533 # assert 'a'.is_alpha
1534 # assert 'Z'.is_alpha
1535 # assert not '0'.is_alpha
1536 # assert not '?'.is_alpha
1537 fun is_alpha: Bool
1538 do
1539 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1540 end
1541
1542 # Returns true if the char is an alpha or a numeric digit
1543 #
1544 # assert 'a'.is_alphanumeric
1545 # assert 'Z'.is_alphanumeric
1546 # assert '0'.is_alphanumeric
1547 # assert '9'.is_alphanumeric
1548 # assert not '?'.is_alphanumeric
1549 fun is_alphanumeric: Bool
1550 do
1551 return self.is_numeric or self.is_alpha
1552 end
1553 end
1554
1555 redef class Collection[E]
1556 # Concatenate elements.
1557 redef fun to_s
1558 do
1559 var s = new FlatBuffer
1560 for e in self do if e != null then s.append(e.to_s)
1561 return s.to_s
1562 end
1563
1564 # Concatenate and separate each elements with `sep`.
1565 #
1566 # assert [1, 2, 3].join(":") == "1:2:3"
1567 # assert [1..3].join(":") == "1:2:3"
1568 fun join(sep: String): String
1569 do
1570 if is_empty then return ""
1571
1572 var s = new FlatBuffer # Result
1573
1574 # Concat first item
1575 var i = iterator
1576 var e = i.item
1577 if e != null then s.append(e.to_s)
1578
1579 # Concat other items
1580 i.next
1581 while i.is_ok do
1582 s.append(sep)
1583 e = i.item
1584 if e != null then s.append(e.to_s)
1585 i.next
1586 end
1587 return s.to_s
1588 end
1589 end
1590
1591 redef class Array[E]
1592 # Fast implementation
1593 redef fun to_s
1594 do
1595 var s = new FlatBuffer
1596 var i = 0
1597 var l = length
1598 while i < l do
1599 var e = self[i]
1600 if e != null then s.append(e.to_s)
1601 i += 1
1602 end
1603 return s.to_s
1604 end
1605 end
1606
1607 redef class Map[K,V]
1608 # Concatenate couple of 'key value'.
1609 # key and value are separated by `couple_sep`.
1610 # each couple is separated each couple with `sep`.
1611 #
1612 # var m = new ArrayMap[Int, String]
1613 # m[1] = "one"
1614 # m[10] = "ten"
1615 # assert m.join("; ", "=") == "1=one; 10=ten"
1616 fun join(sep: String, couple_sep: String): String
1617 do
1618 if is_empty then return ""
1619
1620 var s = new FlatBuffer # Result
1621
1622 # Concat first item
1623 var i = iterator
1624 var k = i.key
1625 var e = i.item
1626 s.append("{k}{couple_sep}{e or else "<null>"}")
1627
1628 # Concat other items
1629 i.next
1630 while i.is_ok do
1631 s.append(sep)
1632 k = i.key
1633 e = i.item
1634 s.append("{k}{couple_sep}{e or else "<null>"}")
1635 i.next
1636 end
1637 return s.to_s
1638 end
1639 end
1640
1641 ###############################################################################
1642 # Native classes #
1643 ###############################################################################
1644
1645 # Native strings are simple C char *
1646 class NativeString
1647 super StringCapable
1648
1649 fun [](index: Int): Char is intern
1650 fun []=(index: Int, item: Char) is intern
1651 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1652
1653 # Position of the first nul character.
1654 fun cstring_length: Int
1655 do
1656 var l = 0
1657 while self[l] != '\0' do l += 1
1658 return l
1659 end
1660 fun atoi: Int is intern
1661 fun atof: Float is extern "atof"
1662
1663 redef fun to_s
1664 do
1665 return to_s_with_length(cstring_length)
1666 end
1667
1668 fun to_s_with_length(length: Int): FlatString
1669 do
1670 assert length >= 0
1671 return new FlatString.with_infos(self, length, 0, length - 1)
1672 end
1673
1674 fun to_s_with_copy: FlatString
1675 do
1676 var length = cstring_length
1677 var new_self = calloc_string(length + 1)
1678 copy_to(new_self, length, 0, 0)
1679 return new FlatString.with_infos(new_self, length, 0, length - 1)
1680 end
1681
1682 end
1683
1684 # StringCapable objects can create native strings
1685 interface StringCapable
1686 protected fun calloc_string(size: Int): NativeString is intern
1687 end
1688
1689 redef class Sys
1690 var _args_cache: nullable Sequence[String]
1691
1692 redef fun args: Sequence[String]
1693 do
1694 if _args_cache == null then init_args
1695 return _args_cache.as(not null)
1696 end
1697
1698 # The name of the program as given by the OS
1699 fun program_name: String
1700 do
1701 return native_argv(0).to_s
1702 end
1703
1704 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1705 private fun init_args
1706 do
1707 var argc = native_argc
1708 var args = new Array[String].with_capacity(0)
1709 var i = 1
1710 while i < argc do
1711 args[i-1] = native_argv(i).to_s
1712 i += 1
1713 end
1714 _args_cache = args
1715 end
1716
1717 # First argument of the main C function.
1718 private fun native_argc: Int is intern
1719
1720 # Second argument of the main C function.
1721 private fun native_argv(i: Int): NativeString is intern
1722 end
1723
1724 # Comparator that efficienlty use `to_s` to compare things
1725 #
1726 # The comparaison call `to_s` on object and use the result to order things.
1727 #
1728 # var a = [1, 2, 3, 10, 20]
1729 # (new CachedAlphaComparator).sort(a)
1730 # assert a == [1, 10, 2, 20, 3]
1731 #
1732 # Internally the result of `to_s` is cached in a HashMap to counter
1733 # uneficient implementation of `to_s`.
1734 #
1735 # Note: it caching is not usefull, see `alpha_comparator`
1736 class CachedAlphaComparator
1737 super Comparator[Object]
1738
1739 private var cache = new HashMap[Object, String]
1740
1741 private fun do_to_s(a: Object): String do
1742 if cache.has_key(a) then return cache[a]
1743 var res = a.to_s
1744 cache[a] = res
1745 return res
1746 end
1747
1748 redef fun compare(a, b) do
1749 return do_to_s(a) <=> do_to_s(b)
1750 end
1751 end
1752
1753 # see `alpha_comparator`
1754 private class AlphaComparator
1755 super Comparator[Object]
1756 redef fun compare(a, b) do return a.to_s <=> b.to_s
1757 end
1758
1759 # Stateless comparator that naively use `to_s` to compare things.
1760 #
1761 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1762 # on a single instace. See `CachedAlphaComparator` as an alternative.
1763 #
1764 # var a = [1, 2, 3, 10, 20]
1765 # alpha_comparator.sort(a)
1766 # assert a == [1, 10, 2, 20, 3]
1767 fun alpha_comparator: Comparator[Object] do return once new AlphaComparator