lib/strings: remove redefinition `FlatString#[]`
[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.chars.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.chars 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.chars[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 chars 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 <(other)
508 do
509 var self_chars = self.chars.iterator
510 var other_chars = other.chars.iterator
511
512 while self_chars.is_ok and other_chars.is_ok do
513 if self_chars.item < other_chars.item then return true
514 if self_chars.item > other_chars.item then return false
515 self_chars.next
516 other_chars.next
517 end
518
519 if self_chars.is_ok then
520 return false
521 else
522 return true
523 end
524 end
525
526 # Flat representation of self
527 fun flatten: FlatText is abstract
528
529 private var hash_cache: nullable Int = null
530
531 redef fun hash
532 do
533 if hash_cache == null then
534 # djb2 hash algorithm
535 var h = 5381
536 var i = length - 1
537
538 for char in self.chars do
539 h = (h * 32) + h + char.ascii
540 i -= 1
541 end
542
543 hash_cache = h
544 end
545 return hash_cache.as(not null)
546 end
547
548 end
549
550 # All kinds of array-based text representations.
551 abstract class FlatText
552 super Text
553
554 private var items: NativeString
555
556 # Real items, used as cache for to_cstring is called
557 private var real_items: nullable NativeString = null
558
559 redef var length: Int
560
561 init do end
562
563 redef fun output
564 do
565 var i = 0
566 while i < length do
567 items[i].output
568 i += 1
569 end
570 end
571
572 redef fun flatten do return self
573 end
574
575 # Abstract class for the SequenceRead compatible
576 # views on String and Buffer objects
577 abstract class StringCharView
578 super SequenceRead[Char]
579
580 type SELFTYPE: Text
581
582 private var target: SELFTYPE
583
584 private init(tgt: SELFTYPE)
585 do
586 target = tgt
587 end
588
589 redef fun is_empty do return target.is_empty
590
591 redef fun length do return target.length
592
593 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
594
595 # Gets a new Iterator starting at position `pos`
596 #
597 # var iter = "abcd".chars.iterator_from(2)
598 # assert iter.to_a == ['c', 'd']
599 fun iterator_from(pos: Int): IndexedIterator[Char] is abstract
600
601 # Gets an iterator starting at the end and going backwards
602 #
603 # var reviter = "hello".chars.reverse_iterator
604 # assert reviter.to_a == ['o', 'l', 'l', 'e', 'h']
605 fun reverse_iterator: IndexedIterator[Char] do return self.reverse_iterator_from(self.length - 1)
606
607 # Gets an iterator on the chars of self starting from `pos`
608 #
609 # var reviter = "hello".chars.reverse_iterator_from(2)
610 # assert reviter.to_a == ['l', 'e', 'h']
611 fun reverse_iterator_from(pos: Int): IndexedIterator[Char] is abstract
612
613 redef fun has(c: Char): Bool
614 do
615 for i in self do
616 if i == c then return true
617 end
618 return false
619 end
620
621 redef fun ==(other)
622 do
623 if other == null then return false
624 if not other isa StringCharView then return false
625 var other_chars = other.iterator
626 for i in self do
627 if i != other_chars.item then return false
628 other_chars.next
629 end
630 return true
631 end
632 end
633
634 # View on Buffer objects, extends Sequence
635 # for mutation operations
636 abstract class BufferCharView
637 super StringCharView
638 super Sequence[Char]
639
640 redef type SELFTYPE: Buffer
641
642 end
643
644 abstract class String
645 super Text
646
647 redef type SELFTYPE: String
648
649 redef fun to_s do return self
650
651 end
652
653 # Immutable strings of characters.
654 class FlatString
655 super FlatText
656 super String
657
658 redef type SELFTYPE: FlatString
659
660 # Index in _items of the start of the string
661 private var index_from: Int
662
663 # Indes in _items of the last item of the string
664 private var index_to: Int
665
666 redef var chars: SELFVIEW = new FlatStringCharView(self)
667
668 ################################################
669 # AbstractString specific methods #
670 ################################################
671
672 redef fun reversed
673 do
674 var native = calloc_string(self.length + 1)
675 var length = self.length
676 var items = self.items
677 var pos = 0
678 var ipos = length-1
679 while pos < length do
680 native[pos] = items[ipos]
681 pos += 1
682 ipos -= 1
683 end
684 return native.to_s_with_length(self.length)
685 end
686
687 redef fun substring(from, count)
688 do
689 assert count >= 0
690
691 if from < 0 then
692 count += from
693 if count < 0 then count = 0
694 from = 0
695 end
696
697 var realFrom = index_from + from
698
699 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
700
701 if count == 0 then return empty
702
703 var to = realFrom + count - 1
704
705 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
706 end
707
708 redef fun empty do return "".as(FlatString)
709
710 redef fun to_upper
711 do
712 var outstr = calloc_string(self.length + 1)
713 var out_index = 0
714
715 var myitems = self.items
716 var index_from = self.index_from
717 var max = self.index_to
718
719 while index_from <= max do
720 outstr[out_index] = myitems[index_from].to_upper
721 out_index += 1
722 index_from += 1
723 end
724
725 outstr[self.length] = '\0'
726
727 return outstr.to_s_with_length(self.length)
728 end
729
730 redef fun to_lower
731 do
732 var outstr = calloc_string(self.length + 1)
733 var out_index = 0
734
735 var myitems = self.items
736 var index_from = self.index_from
737 var max = self.index_to
738
739 while index_from <= max do
740 outstr[out_index] = myitems[index_from].to_lower
741 out_index += 1
742 index_from += 1
743 end
744
745 outstr[self.length] = '\0'
746
747 return outstr.to_s_with_length(self.length)
748 end
749
750 redef fun output
751 do
752 var i = self.index_from
753 var imax = self.index_to
754 while i <= imax do
755 items[i].output
756 i += 1
757 end
758 end
759
760 ##################################################
761 # String Specific Methods #
762 ##################################################
763
764 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
765 do
766 self.items = items
767 length = len
768 index_from = from
769 index_to = to
770 end
771
772 redef fun to_cstring: NativeString
773 do
774 if real_items != null then return real_items.as(not null)
775 if index_from > 0 or index_to != items.cstring_length - 1 then
776 var newItems = calloc_string(length + 1)
777 self.items.copy_to(newItems, length, index_from, 0)
778 newItems[length] = '\0'
779 self.real_items = newItems
780 return newItems
781 end
782 return items
783 end
784
785 redef fun ==(other)
786 do
787 if not other isa FlatString then return super
788
789 if self.object_id == other.object_id then return true
790
791 var my_length = length
792
793 if other.length != my_length then return false
794
795 var my_index = index_from
796 var its_index = other.index_from
797
798 var last_iteration = my_index + my_length
799
800 var itsitems = other.items
801 var myitems = self.items
802
803 while my_index < last_iteration do
804 if myitems[my_index] != itsitems[its_index] then return false
805 my_index += 1
806 its_index += 1
807 end
808
809 return true
810 end
811
812 redef fun <(other)
813 do
814 if not other isa FlatString then return super
815
816 if self.object_id == other.object_id then return false
817
818 var my_curr_char : Char
819 var its_curr_char : Char
820
821 var curr_id_self = self.index_from
822 var curr_id_other = other.index_from
823
824 var my_items = self.items
825 var its_items = other.items
826
827 var my_length = self.length
828 var its_length = other.length
829
830 var max_iterations = curr_id_self + my_length
831
832 while curr_id_self < max_iterations do
833 my_curr_char = my_items[curr_id_self]
834 its_curr_char = its_items[curr_id_other]
835
836 if my_curr_char != its_curr_char then
837 if my_curr_char < its_curr_char then return true
838 return false
839 end
840
841 curr_id_self += 1
842 curr_id_other += 1
843 end
844
845 return my_length < its_length
846 end
847
848 redef fun +(s)
849 do
850 var my_length = self.length
851 var its_length = s.length
852
853 var total_length = my_length + its_length
854
855 var target_string = calloc_string(my_length + its_length + 1)
856
857 self.items.copy_to(target_string, my_length, index_from, 0)
858 if s isa FlatString then
859 s.items.copy_to(target_string, its_length, s.index_from, my_length)
860 else if s isa FlatBuffer then
861 s.items.copy_to(target_string, its_length, 0, my_length)
862 else
863 var curr_pos = my_length
864 for i in s.chars do
865 target_string[curr_pos] = i
866 curr_pos += 1
867 end
868 end
869
870 target_string[total_length] = '\0'
871
872 return target_string.to_s_with_length(total_length)
873 end
874
875 redef fun *(i)
876 do
877 assert i >= 0
878
879 var my_length = self.length
880
881 var final_length = my_length * i
882
883 var my_items = self.items
884
885 var target_string = calloc_string((final_length) + 1)
886
887 target_string[final_length] = '\0'
888
889 var current_last = 0
890
891 for iteration in [1 .. i] do
892 my_items.copy_to(target_string, my_length, 0, current_last)
893 current_last += my_length
894 end
895
896 return target_string.to_s_with_length(final_length)
897 end
898
899 redef fun hash
900 do
901 if hash_cache == null then
902 # djb2 hash algorythm
903 var h = 5381
904 var i = length - 1
905
906 var myitems = items
907 var strStart = index_from
908
909 i += strStart
910
911 while i >= strStart do
912 h = (h * 32) + h + self.items[i].ascii
913 i -= 1
914 end
915
916 hash_cache = h
917 end
918
919 return hash_cache.as(not null)
920 end
921 end
922
923 private class FlatStringReverseIterator
924 super IndexedIterator[Char]
925
926 var target: FlatString
927
928 var target_items: NativeString
929
930 var curr_pos: Int
931
932 init with_pos(tgt: FlatString, pos: Int)
933 do
934 target = tgt
935 target_items = tgt.items
936 curr_pos = pos + tgt.index_from
937 end
938
939 redef fun is_ok do return curr_pos >= 0
940
941 redef fun item do return target_items[curr_pos]
942
943 redef fun next do curr_pos -= 1
944
945 redef fun index do return curr_pos - target.index_from
946
947 end
948
949 private class FlatStringIterator
950 super IndexedIterator[Char]
951
952 var target: FlatString
953
954 var target_items: NativeString
955
956 var curr_pos: Int
957
958 init with_pos(tgt: FlatString, pos: Int)
959 do
960 target = tgt
961 target_items = tgt.items
962 curr_pos = pos + target.index_from
963 end
964
965 redef fun is_ok do return curr_pos <= target.index_to
966
967 redef fun item do return target_items[curr_pos]
968
969 redef fun next do curr_pos += 1
970
971 redef fun index do return curr_pos - target.index_from
972
973 end
974
975 private class FlatStringCharView
976 super StringCharView
977
978 redef type SELFTYPE: FlatString
979
980 redef fun [](index)
981 do
982 # Check that the index (+ index_from) is not larger than indexTo
983 # In other terms, if the index is valid
984 assert index >= 0
985 var target = self.target
986 assert (index + target.index_from) <= target.index_to
987 return target.items[index + target.index_from]
988 end
989
990 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
991
992 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
993
994 end
995
996 abstract class Buffer
997 super Text
998
999 redef type SELFVIEW: BufferCharView
1000 redef type SELFTYPE: Buffer
1001
1002 # Specific implementations MUST set this to `true` in order to invalidate caches
1003 protected var is_dirty = true
1004
1005 # Modifies the char contained at pos `index`
1006 #
1007 # DEPRECATED : Use self.chars.[]= instead
1008 fun []=(index: Int, item: Char) is abstract
1009
1010 # Adds a char `c` at the end of self
1011 #
1012 # DEPRECATED : Use self.chars.add instead
1013 fun add(c: Char) is abstract
1014
1015 # Clears the buffer
1016 #
1017 # var b = new FlatBuffer
1018 # b.append "hello"
1019 # assert not b.is_empty
1020 # b.clear
1021 # assert b.is_empty
1022 fun clear is abstract
1023
1024 # Enlarges the subsequent array containing the chars of self
1025 fun enlarge(cap: Int) is abstract
1026
1027 # Adds the content of text `s` at the end of self
1028 #
1029 # var b = new FlatBuffer
1030 # b.append "hello"
1031 # b.append "world"
1032 # assert b == "helloworld"
1033 fun append(s: Text) is abstract
1034
1035 redef fun hash
1036 do
1037 if is_dirty then hash_cache = null
1038 return super
1039 end
1040
1041 end
1042
1043 # Mutable strings of characters.
1044 class FlatBuffer
1045 super FlatText
1046 super Buffer
1047
1048 redef type SELFTYPE: FlatBuffer
1049
1050 redef var chars: SELFVIEW = new FlatBufferCharView(self)
1051
1052 private var capacity: Int
1053
1054 redef fun []=(index, item)
1055 do
1056 is_dirty = true
1057 if index == length then
1058 add(item)
1059 return
1060 end
1061 assert index >= 0 and index < length
1062 items[index] = item
1063 end
1064
1065 redef fun add(c)
1066 do
1067 is_dirty = true
1068 if capacity <= length then enlarge(length + 5)
1069 items[length] = c
1070 length += 1
1071 end
1072
1073 redef fun clear do
1074 is_dirty = true
1075 length = 0
1076 end
1077
1078 redef fun empty do return new FlatBuffer
1079
1080 redef fun enlarge(cap)
1081 do
1082 is_dirty = true
1083 var c = capacity
1084 if cap <= c then return
1085 while c <= cap do c = c * 2 + 2
1086 var a = calloc_string(c+1)
1087 items.copy_to(a, length, 0, 0)
1088 items = a
1089 capacity = c
1090 items.copy_to(a, length, 0, 0)
1091 end
1092
1093 redef fun to_s: String
1094 do
1095 return to_cstring.to_s_with_length(length)
1096 end
1097
1098 redef fun to_cstring
1099 do
1100 if is_dirty then
1101 var new_native = calloc_string(length + 1)
1102 new_native[length] = '\0'
1103 items.copy_to(new_native, length, 0, 0)
1104 real_items = new_native
1105 is_dirty = false
1106 end
1107 return real_items.as(not null)
1108 end
1109
1110 # Create a new empty string.
1111 init do with_capacity(5)
1112
1113 init from(s: Text)
1114 do
1115 capacity = s.length + 1
1116 length = s.length
1117 items = calloc_string(capacity)
1118 if s isa FlatString then
1119 s.items.copy_to(items, length, s.index_from, 0)
1120 else if s isa FlatBuffer then
1121 s.items.copy_to(items, length, 0, 0)
1122 else
1123 var curr_pos = 0
1124 for i in s.chars do
1125 items[curr_pos] = i
1126 curr_pos += 1
1127 end
1128 end
1129 end
1130
1131 # Create a new empty string with a given capacity.
1132 init with_capacity(cap: Int)
1133 do
1134 assert cap >= 0
1135 # _items = new NativeString.calloc(cap)
1136 items = calloc_string(cap+1)
1137 capacity = cap
1138 length = 0
1139 end
1140
1141 redef fun append(s)
1142 do
1143 is_dirty = true
1144 var sl = s.length
1145 if capacity < length + sl then enlarge(length + sl)
1146 if s isa FlatString then
1147 s.items.copy_to(items, sl, s.index_from, length)
1148 else if s isa FlatBuffer then
1149 s.items.copy_to(items, sl, 0, length)
1150 else
1151 var curr_pos = self.length
1152 for i in s.chars do
1153 items[curr_pos] = i
1154 curr_pos += 1
1155 end
1156 end
1157 length += sl
1158 end
1159
1160 # Copies the content of self in `dest`
1161 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1162 do
1163 var self_chars = self.chars
1164 var dest_chars = dest.chars
1165 for i in [0..len-1] do
1166 dest_chars[new_start+i] = self_chars[start+i]
1167 end
1168 end
1169
1170 redef fun substring(from, count)
1171 do
1172 assert count >= 0
1173 count += from
1174 if from < 0 then from = 0
1175 if count > length then count = length
1176 if from < count then
1177 var r = new FlatBuffer.with_capacity(count - from)
1178 while from < count do
1179 r.chars.push(items[from])
1180 from += 1
1181 end
1182 return r
1183 else
1184 return new FlatBuffer
1185 end
1186 end
1187
1188 redef fun reversed
1189 do
1190 var new_buf = new FlatBuffer.with_capacity(self.length)
1191 var reviter = self.chars.reverse_iterator
1192 while reviter.is_ok do
1193 new_buf.add(reviter.item)
1194 reviter.next
1195 end
1196 return new_buf
1197 end
1198
1199 redef fun +(other)
1200 do
1201 var new_buf = new FlatBuffer.with_capacity(self.length + other.length)
1202 new_buf.append(self)
1203 new_buf.append(other)
1204 return new_buf
1205 end
1206
1207 redef fun *(repeats)
1208 do
1209 var new_buf = new FlatBuffer.with_capacity(self.length * repeats)
1210 for i in [0..repeats[ do
1211 new_buf.append(self)
1212 end
1213 return new_buf
1214 end
1215 end
1216
1217 private class FlatBufferReverseIterator
1218 super IndexedIterator[Char]
1219
1220 var target: FlatBuffer
1221
1222 var target_items: NativeString
1223
1224 var curr_pos: Int
1225
1226 init with_pos(tgt: FlatBuffer, pos: Int)
1227 do
1228 target = tgt
1229 target_items = tgt.items
1230 curr_pos = pos
1231 end
1232
1233 redef fun index do return curr_pos
1234
1235 redef fun is_ok do return curr_pos >= 0
1236
1237 redef fun item do return target_items[curr_pos]
1238
1239 redef fun next do curr_pos -= 1
1240
1241 end
1242
1243 private class FlatBufferCharView
1244 super BufferCharView
1245 super StringCapable
1246
1247 redef type SELFTYPE: FlatBuffer
1248
1249 redef fun [](index) do return target.items[index]
1250
1251 redef fun []=(index, item)
1252 do
1253 assert index >= 0 and index <= length
1254 if index == length then
1255 add(item)
1256 return
1257 end
1258 target.items[index] = item
1259 end
1260
1261 redef fun push(c)
1262 do
1263 target.add(c)
1264 end
1265
1266 redef fun add(c)
1267 do
1268 target.add(c)
1269 end
1270
1271 fun enlarge(cap: Int)
1272 do
1273 target.enlarge(cap)
1274 end
1275
1276 redef fun append(s)
1277 do
1278 var my_items = target.items
1279 var s_length = s.length
1280 if target.capacity < s.length then enlarge(s_length + target.length)
1281 end
1282
1283 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1284
1285 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1286
1287 end
1288
1289 private class FlatBufferIterator
1290 super IndexedIterator[Char]
1291
1292 var target: FlatBuffer
1293
1294 var target_items: NativeString
1295
1296 var curr_pos: Int
1297
1298 init with_pos(tgt: FlatBuffer, pos: Int)
1299 do
1300 target = tgt
1301 target_items = tgt.items
1302 curr_pos = pos
1303 end
1304
1305 redef fun index do return curr_pos
1306
1307 redef fun is_ok do return curr_pos < target.length
1308
1309 redef fun item do return target_items[curr_pos]
1310
1311 redef fun next do curr_pos += 1
1312
1313 end
1314
1315 ###############################################################################
1316 # Refinement #
1317 ###############################################################################
1318
1319 redef class Object
1320 # User readable representation of `self`.
1321 fun to_s: String do return inspect
1322
1323 # The class name of the object in NativeString format.
1324 private fun native_class_name: NativeString is intern
1325
1326 # The class name of the object.
1327 #
1328 # assert 5.class_name == "Int"
1329 fun class_name: String do return native_class_name.to_s
1330
1331 # Developer readable representation of `self`.
1332 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1333 fun inspect: String
1334 do
1335 return "<{inspect_head}>"
1336 end
1337
1338 # Return "CLASSNAME:#OBJECTID".
1339 # This function is mainly used with the redefinition of the inspect method
1340 protected fun inspect_head: String
1341 do
1342 return "{class_name}:#{object_id.to_hex}"
1343 end
1344
1345 protected fun args: Sequence[String]
1346 do
1347 return sys.args
1348 end
1349 end
1350
1351 redef class Bool
1352 # assert true.to_s == "true"
1353 # assert false.to_s == "false"
1354 redef fun to_s
1355 do
1356 if self then
1357 return once "true"
1358 else
1359 return once "false"
1360 end
1361 end
1362 end
1363
1364 redef class Int
1365 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1366 # assume < to_c max const of char
1367 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1368 do
1369 var n: Int
1370 # Sign
1371 if self < 0 then
1372 n = - self
1373 s.chars[0] = '-'
1374 else if self == 0 then
1375 s.chars[0] = '0'
1376 return
1377 else
1378 n = self
1379 end
1380 # Fill digits
1381 var pos = digit_count(base) - 1
1382 while pos >= 0 and n > 0 do
1383 s.chars[pos] = (n % base).to_c
1384 n = n / base # /
1385 pos -= 1
1386 end
1387 end
1388
1389 # C function to convert an nit Int to a NativeString (char*)
1390 private fun native_int_to_s(len: Int): NativeString is extern "native_int_to_s"
1391
1392 # return displayable int in base 10 and signed
1393 #
1394 # assert 1.to_s == "1"
1395 # assert (-123).to_s == "-123"
1396 redef fun to_s do
1397 var len = digit_count(10)
1398 return native_int_to_s(len).to_s_with_length(len)
1399 end
1400
1401 # return displayable int in hexadecimal
1402 #
1403 # assert 1.to_hex == "1"
1404 # assert (-255).to_hex == "-ff"
1405 fun to_hex: String do return to_base(16,false)
1406
1407 # return displayable int in base base and signed
1408 fun to_base(base: Int, signed: Bool): String
1409 do
1410 var l = digit_count(base)
1411 var s = new FlatBuffer.from(" " * l)
1412 fill_buffer(s, base, signed)
1413 return s.to_s
1414 end
1415 end
1416
1417 redef class Float
1418 # Pretty print self, print needoed decimals up to a max of 3.
1419 #
1420 # assert 12.34.to_s == "12.34"
1421 # assert (-0120.03450).to_s == "-120.035"
1422 #
1423 # see `to_precision` for a different precision.
1424 redef fun to_s do
1425 var str = to_precision( 3 )
1426 if is_inf != 0 or is_nan then return str
1427 var len = str.length
1428 for i in [0..len-1] do
1429 var j = len-1-i
1430 var c = str.chars[j]
1431 if c == '0' then
1432 continue
1433 else if c == '.' then
1434 return str.substring( 0, j+2 )
1435 else
1436 return str.substring( 0, j+1 )
1437 end
1438 end
1439 return str
1440 end
1441
1442 # `self` representation with `nb` digits after the '.'.
1443 #
1444 # assert 12.345.to_precision(1) == "12.3"
1445 # assert 12.345.to_precision(2) == "12.35"
1446 # assert 12.345.to_precision(3) == "12.345"
1447 # assert 12.345.to_precision(4) == "12.3450"
1448 fun to_precision(nb: Int): String
1449 do
1450 if is_nan then return "nan"
1451
1452 var isinf = self.is_inf
1453 if isinf == 1 then
1454 return "inf"
1455 else if isinf == -1 then
1456 return "-inf"
1457 end
1458
1459 if nb == 0 then return self.to_i.to_s
1460 var f = self
1461 for i in [0..nb[ do f = f * 10.0
1462 if self > 0.0 then
1463 f = f + 0.5
1464 else
1465 f = f - 0.5
1466 end
1467 var i = f.to_i
1468 if i == 0 then return "0.0"
1469 var s = i.to_s
1470 var sl = s.length
1471 if sl > nb then
1472 var p1 = s.substring(0, s.length-nb)
1473 var p2 = s.substring(s.length-nb, nb)
1474 return p1 + "." + p2
1475 else
1476 return "0." + ("0"*(nb-sl)) + s
1477 end
1478 end
1479
1480 # `self` representation with `nb` digits after the '.'.
1481 #
1482 # assert 12.345.to_precision_native(1) == "12.3"
1483 # assert 12.345.to_precision_native(2) == "12.35"
1484 # assert 12.345.to_precision_native(3) == "12.345"
1485 # assert 12.345.to_precision_native(4) == "12.3450"
1486 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1487 int size;
1488 char *str;
1489
1490 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1491 str = malloc(size + 1);
1492 sprintf(str, "%.*f", (int)nb, recv );
1493
1494 return NativeString_to_s( str );
1495 `}
1496 end
1497
1498 redef class Char
1499 # assert 'x'.to_s == "x"
1500 redef fun to_s
1501 do
1502 var s = new FlatBuffer.with_capacity(1)
1503 s.chars[0] = self
1504 return s.to_s
1505 end
1506
1507 # Returns true if the char is a numerical digit
1508 #
1509 # assert '0'.is_numeric
1510 # assert '9'.is_numeric
1511 # assert not 'a'.is_numeric
1512 # assert not '?'.is_numeric
1513 fun is_numeric: Bool
1514 do
1515 return self >= '0' and self <= '9'
1516 end
1517
1518 # Returns true if the char is an alpha digit
1519 #
1520 # assert 'a'.is_alpha
1521 # assert 'Z'.is_alpha
1522 # assert not '0'.is_alpha
1523 # assert not '?'.is_alpha
1524 fun is_alpha: Bool
1525 do
1526 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1527 end
1528
1529 # Returns true if the char is an alpha or a numeric digit
1530 #
1531 # assert 'a'.is_alphanumeric
1532 # assert 'Z'.is_alphanumeric
1533 # assert '0'.is_alphanumeric
1534 # assert '9'.is_alphanumeric
1535 # assert not '?'.is_alphanumeric
1536 fun is_alphanumeric: Bool
1537 do
1538 return self.is_numeric or self.is_alpha
1539 end
1540 end
1541
1542 redef class Collection[E]
1543 # Concatenate elements.
1544 redef fun to_s
1545 do
1546 var s = new FlatBuffer
1547 for e in self do if e != null then s.append(e.to_s)
1548 return s.to_s
1549 end
1550
1551 # Concatenate and separate each elements with `sep`.
1552 #
1553 # assert [1, 2, 3].join(":") == "1:2:3"
1554 # assert [1..3].join(":") == "1:2:3"
1555 fun join(sep: String): String
1556 do
1557 if is_empty then return ""
1558
1559 var s = new FlatBuffer # Result
1560
1561 # Concat first item
1562 var i = iterator
1563 var e = i.item
1564 if e != null then s.append(e.to_s)
1565
1566 # Concat other items
1567 i.next
1568 while i.is_ok do
1569 s.append(sep)
1570 e = i.item
1571 if e != null then s.append(e.to_s)
1572 i.next
1573 end
1574 return s.to_s
1575 end
1576 end
1577
1578 redef class Array[E]
1579 # Fast implementation
1580 redef fun to_s
1581 do
1582 var s = new FlatBuffer
1583 var i = 0
1584 var l = length
1585 while i < l do
1586 var e = self[i]
1587 if e != null then s.append(e.to_s)
1588 i += 1
1589 end
1590 return s.to_s
1591 end
1592 end
1593
1594 redef class Map[K,V]
1595 # Concatenate couple of 'key value'.
1596 # key and value are separated by `couple_sep`.
1597 # each couple is separated each couple with `sep`.
1598 #
1599 # var m = new ArrayMap[Int, String]
1600 # m[1] = "one"
1601 # m[10] = "ten"
1602 # assert m.join("; ", "=") == "1=one; 10=ten"
1603 fun join(sep: String, couple_sep: String): String
1604 do
1605 if is_empty then return ""
1606
1607 var s = new FlatBuffer # Result
1608
1609 # Concat first item
1610 var i = iterator
1611 var k = i.key
1612 var e = i.item
1613 s.append("{k}{couple_sep}{e or else "<null>"}")
1614
1615 # Concat other items
1616 i.next
1617 while i.is_ok do
1618 s.append(sep)
1619 k = i.key
1620 e = i.item
1621 s.append("{k}{couple_sep}{e or else "<null>"}")
1622 i.next
1623 end
1624 return s.to_s
1625 end
1626 end
1627
1628 ###############################################################################
1629 # Native classes #
1630 ###############################################################################
1631
1632 # Native strings are simple C char *
1633 class NativeString
1634 super StringCapable
1635
1636 fun [](index: Int): Char is intern
1637 fun []=(index: Int, item: Char) is intern
1638 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1639
1640 # Position of the first nul character.
1641 fun cstring_length: Int
1642 do
1643 var l = 0
1644 while self[l] != '\0' do l += 1
1645 return l
1646 end
1647 fun atoi: Int is intern
1648 fun atof: Float is extern "atof"
1649
1650 redef fun to_s
1651 do
1652 return to_s_with_length(cstring_length)
1653 end
1654
1655 fun to_s_with_length(length: Int): FlatString
1656 do
1657 assert length >= 0
1658 return new FlatString.with_infos(self, length, 0, length - 1)
1659 end
1660
1661 fun to_s_with_copy: FlatString
1662 do
1663 var length = cstring_length
1664 var new_self = calloc_string(length + 1)
1665 copy_to(new_self, length, 0, 0)
1666 return new FlatString.with_infos(new_self, length, 0, length - 1)
1667 end
1668
1669 end
1670
1671 # StringCapable objects can create native strings
1672 interface StringCapable
1673 protected fun calloc_string(size: Int): NativeString is intern
1674 end
1675
1676 redef class Sys
1677 var _args_cache: nullable Sequence[String]
1678
1679 redef fun args: Sequence[String]
1680 do
1681 if _args_cache == null then init_args
1682 return _args_cache.as(not null)
1683 end
1684
1685 # The name of the program as given by the OS
1686 fun program_name: String
1687 do
1688 return native_argv(0).to_s
1689 end
1690
1691 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1692 private fun init_args
1693 do
1694 var argc = native_argc
1695 var args = new Array[String].with_capacity(0)
1696 var i = 1
1697 while i < argc do
1698 args[i-1] = native_argv(i).to_s
1699 i += 1
1700 end
1701 _args_cache = args
1702 end
1703
1704 # First argument of the main C function.
1705 private fun native_argc: Int is intern
1706
1707 # Second argument of the main C function.
1708 private fun native_argv(i: Int): NativeString is intern
1709 end
1710
1711 # Comparator that efficienlty use `to_s` to compare things
1712 #
1713 # The comparaison call `to_s` on object and use the result to order things.
1714 #
1715 # var a = [1, 2, 3, 10, 20]
1716 # (new CachedAlphaComparator).sort(a)
1717 # assert a == [1, 10, 2, 20, 3]
1718 #
1719 # Internally the result of `to_s` is cached in a HashMap to counter
1720 # uneficient implementation of `to_s`.
1721 #
1722 # Note: it caching is not usefull, see `alpha_comparator`
1723 class CachedAlphaComparator
1724 super Comparator[Object]
1725
1726 private var cache = new HashMap[Object, String]
1727
1728 private fun do_to_s(a: Object): String do
1729 if cache.has_key(a) then return cache[a]
1730 var res = a.to_s
1731 cache[a] = res
1732 return res
1733 end
1734
1735 redef fun compare(a, b) do
1736 return do_to_s(a) <=> do_to_s(b)
1737 end
1738 end
1739
1740 # see `alpha_comparator`
1741 private class AlphaComparator
1742 super Comparator[Object]
1743 redef fun compare(a, b) do return a.to_s <=> b.to_s
1744 end
1745
1746 # Stateless comparator that naively use `to_s` to compare things.
1747 #
1748 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1749 # on a single instace. See `CachedAlphaComparator` as an alternative.
1750 #
1751 # var a = [1, 2, 3, 10, 20]
1752 # alpha_comparator.sort(a)
1753 # assert a == [1, 10, 2, 20, 3]
1754 fun alpha_comparator: Comparator[Object] do return once new AlphaComparator