1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
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
14 # Basic manipulations of strings of characters
18 intrude import collection
# FIXME should be collection::array
25 ###############################################################################
27 ###############################################################################
29 # High-level abstraction for all text representations
34 redef type OTHER: Text
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
39 # Gets a view on the chars of the Text object
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars
: SequenceRead[Char] is abstract
44 # Number of characters contained in self.
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length
: Int is abstract
52 # assert "abcd".substring(1, 2) == "bc"
53 # assert "abcd".substring(-1, 2) == "a"
54 # assert "abcd".substring(1, 0) == ""
55 # assert "abcd".substring(2, 5) == "cd"
57 # A `from` index < 0 will be replaced by 0.
58 # Unless a `count` value is > 0 at the same time.
59 # In this case, `from += count` and `count -= from`.
60 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
62 # Concatenates `o` to `self`
64 # assert "hello" + "world" == "helloworld"
65 # assert "" + "hello" + "" == "hello"
66 fun +(o
: Text): SELFTYPE is abstract
68 # Auto-concatenates self `i` times
70 # assert "abc" * 4 == "abcabcabcabc"
71 # assert "abc" * 1 == "abc"
72 # assert "abc" * 0 == ""
73 fun *(i
: Int): SELFTYPE is abstract
75 # Is the current Text empty (== "")
78 # assert not "foo".is_empty
79 fun is_empty
: Bool do return self.length
== 0
81 # Returns an empty Text of the right type
83 # This method is used internally to get the right
84 # implementation of an empty string.
85 protected fun empty
: SELFTYPE is abstract
87 # Gets the first char of the Text
89 # DEPRECATED : Use self.chars.first instead
90 fun first
: Char do return self.chars
[0]
92 # Access a character at `index` in the string.
94 # assert "abcd"[2] == 'c'
96 # DEPRECATED : Use self.chars.[] instead
97 fun [](index
: Int): Char do return self.chars
[index
]
99 # Gets the index of the first occurence of 'c'
101 # Returns -1 if not found
103 # DEPRECATED : Use self.chars.index_of instead
104 fun index_of
(c
: Char): Int
106 return index_of_from
(c
, 0)
109 # Gets the last char of self
111 # DEPRECATED : Use self.chars.last instead
112 fun last
: Char do return self.chars
[length-1
]
114 # Gets the index of the first occurence of ´c´ starting from ´pos´
116 # Returns -1 if not found
118 # DEPRECATED : Use self.chars.index_of_from instead
119 fun index_of_from
(c
: Char, pos
: Int): Int
121 var iter
= self.chars
.iterator_from
(pos
)
123 if iter
.item
== c
then return iter
.index
129 # Gets the last index of char ´c´
131 # Returns -1 if not found
133 # DEPRECATED : Use self.chars.last_index_of instead
134 fun last_index_of
(c
: Char): Int
136 return last_index_of_from
(c
, length
- 1)
139 # Return a null terminated char *
140 fun to_cstring
: NativeString do return flatten
.to_cstring
142 # The index of the last occurrence of an element starting from pos (in reverse order).
144 # var s = "/etc/bin/test/test.nit"
145 # assert s.last_index_of_from('/', s.length-1) == 13
146 # assert s.last_index_of_from('/', 12) == 8
148 # Returns -1 if not found
150 # DEPRECATED : Use self.chars.last_index_of_from instead
151 fun last_index_of_from
(item
: Char, pos
: Int): Int
153 var iter
= self.chars
.reverse_iterator_from
(pos
)
155 if iter
.item
== item
then return iter
.index
161 # Gets an iterator on the chars of self
163 # DEPRECATED : Use self.chars.iterator instead
164 fun iterator
: Iterator[Char]
166 return self.chars
.iterator
169 # Is 'c' contained in self ?
171 # DEPRECATED : Use self.chars.has instead
172 fun has
(c
: Char): Bool
174 return self.chars
.has
(c
)
177 # Gets an Array containing the chars of self
179 # DEPRECATED : Use self.chars.to_a instead
180 fun to_a
: Array[Char] do return chars
.to_a
182 # Create a substring from `self` beginning at the `from` position
184 # assert "abcd".substring_from(1) == "bcd"
185 # assert "abcd".substring_from(-1) == "abcd"
186 # assert "abcd".substring_from(2) == "cd"
188 # As with substring, a `from` index < 0 will be replaced by 0
189 fun substring_from
(from
: Int): SELFTYPE
191 if from
> self.length
then return empty
192 if from
< 0 then from
= 0
193 return substring
(from
, length
- from
)
196 # Returns a reversed version of self
198 # assert "hello".reversed == "olleh"
199 # assert "bob".reversed == "bob"
200 # assert "".reversed == ""
201 fun reversed
: SELFTYPE is abstract
203 # Does self have a substring `str` starting from position `pos`?
205 # assert "abcd".has_substring("bc",1) == true
206 # assert "abcd".has_substring("bc",2) == false
207 fun has_substring
(str
: String, pos
: Int): Bool
209 var myiter
= self.chars
.iterator_from
(pos
)
210 var itsiter
= str
.chars
.iterator
211 while myiter
.is_ok
and itsiter
.is_ok
do
212 if myiter
.item
!= itsiter
.item
then return false
216 if itsiter
.is_ok
then return false
220 # Is this string prefixed by `prefix`?
222 # assert "abcd".has_prefix("ab") == true
223 # assert "abcbc".has_prefix("bc") == false
224 # assert "ab".has_prefix("abcd") == false
225 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
227 # Is this string suffixed by `suffix`?
229 # assert "abcd".has_suffix("abc") == false
230 # assert "abcd".has_suffix("bcd") == true
231 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
233 # If `self` contains only digits, return the corresponding integer
235 # assert "123".to_i == 123
236 # assert "-1".to_i == -1
240 return to_s
.to_cstring
.atoi
243 # If `self` contains a float, return the corresponding float
245 # assert "123".to_f == 123.0
246 # assert "-1".to_f == -1.0
247 # assert "-1.2e-3".to_f == -0.0012
251 return to_s
.to_cstring
.atof
254 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
256 # assert "ff".to_hex == 255
257 fun to_hex
: Int do return a_to
(16)
259 # If `self` contains only digits and letters, return the corresponding integer in a given base
261 # assert "120".a_to(3) == 15
262 fun a_to
(base
: Int) : Int
289 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
291 # assert "123".is_numeric == true
292 # assert "1.2".is_numeric == true
293 # assert "1,2".is_numeric == true
294 # assert "1..2".is_numeric == false
297 var has_point_or_comma
= false
302 if (i
== '.' or i
== ',') and not has_point_or_comma
304 has_point_or_comma
= true
313 # A upper case version of `self`
315 # assert "Hello World!".to_upper == "HELLO WORLD!"
316 fun to_upper
: SELFTYPE is abstract
318 # A lower case version of `self`
320 # assert "Hello World!".to_lower == "hello world!"
321 fun to_lower
: SELFTYPE is abstract
323 # Removes the whitespaces at the beginning of self
325 # assert " \n\thello \n\t".l_trim == "hello \n\t"
327 # A whitespace is defined as any character which ascii value is less than or equal to 32
330 var iter
= self.chars
.iterator
332 if iter
.item
.ascii
> 32 then break
335 if iter
.index
== length
then return self.empty
336 return self.substring_from
(iter
.index
)
339 # Removes the whitespaces at the end of self
341 # assert " \n\thello \n\t".r_trim == " \n\thello"
343 # A whitespace is defined as any character which ascii value is less than or equal to 32
346 var iter
= self.chars
.reverse_iterator
348 if iter
.item
.ascii
> 32 then break
351 if iter
.index
== length
then return self.empty
352 return self.substring
(0, iter
.index
+ 1)
355 # Trims trailing and preceding white spaces
356 # A whitespace is defined as any character which ascii value is less than or equal to 32
358 # assert " Hello World ! ".trim == "Hello World !"
359 # assert "\na\nb\tc\t".trim == "a\nb\tc"
360 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
362 # Mangle a string to be a unique string only made of alphanumeric characters
363 fun to_cmangle
: String
365 var res
= new FlatBuffer
366 var underscore
= false
367 for c
in self.chars
do
368 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
374 res
.append
('_'.ascii
.to_s
)
377 if c
>= '0' and c
<= '9' then
380 else if c
== '_' then
385 res
.append
(c
.ascii
.to_s
)
393 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
395 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
396 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
397 fun escape_to_c
: String
399 var b
= new FlatBuffer
400 for c
in self.chars
do
403 else if c
== '\0' then
405 else if c
== '"' then
407 else if c == '\'' then
409 else if c == '\\
' then
411 else if c.ascii < 32 then
412 b.append("\\{c.ascii.to_base(8, false)}")
420 # Escape additionnal characters
421 # The result might no be legal in C but be used in other languages
423 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
424 fun escape_more_to_c(chars: String): String
426 var b = new FlatBuffer
427 for c in escape_to_c.chars do
428 if chars.chars.has(c) then
436 # Escape to C plus braces
438 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
439 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
441 # Return a string where Nit escape sequences are transformed.
444 # assert s.length == 2
445 # var u = s.unescape_nit
446 # assert u.length == 1
447 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
448 fun unescape_nit
: String
450 var res
= new FlatBuffer.with_capacity
(self.length
)
451 var was_slash
= false
453 if not was_slash
then
464 else if c
== 'r' then
466 else if c
== 't' then
468 else if c
== '0' then
478 # Two pieces of text are equals if thez have the same characters in the same order.
480 # assert "hello" == "hello"
481 # assert "hello" != "HELLO"
482 # assert "hello" == "hel"+"lo"
484 # Things that are not Text are not equal.
487 # assert "9" != ['9']
490 # assert "9".chars.first == '9' # equality of Char
491 # assert "9".chars == ['9'] # equality of Sequence
492 # assert "9".to_i == 9 # equality of Int
495 if o
== null then return false
496 if not o
isa Text then return false
497 if self.is_same_instance
(o
) then return true
498 if self.length
!= o
.length
then return false
499 return self.chars
== o
.chars
502 # Lexicographical comparaison
504 # assert "abc" < "xy"
505 # assert "ABC" < "abc"
508 var self_chars
= self.chars
.iterator
509 var other_chars
= other
.chars
.iterator
511 while self_chars
.is_ok
and other_chars
.is_ok
do
512 if self_chars
.item
< other_chars
.item
then return true
513 if self_chars
.item
> other_chars
.item
then return false
518 if self_chars
.is_ok
then
525 # Flat representation of self
526 fun flatten
: FlatText is abstract
528 private var hash_cache
: nullable Int = null
532 if hash_cache
== null then
533 # djb2 hash algorithm
536 for char
in self.chars
do
537 h
= h
.lshift
(5) + h
+ char
.ascii
542 return hash_cache
.as(not null)
547 # All kinds of array-based text representations.
548 abstract class FlatText
551 private var items
: NativeString
553 # Real items, used as cache for to_cstring is called
554 private var real_items
: nullable NativeString = null
556 redef var length
: Int = 0
569 redef fun flatten
do return self
572 # Abstract class for the SequenceRead compatible
573 # views on String and Buffer objects
574 private abstract class StringCharView
575 super SequenceRead[Char]
579 private var target
: SELFTYPE
581 private init(tgt
: SELFTYPE)
586 redef fun is_empty
do return target
.is_empty
588 redef fun length
do return target
.length
590 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
592 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
595 # View on Buffer objects, extends Sequence
596 # for mutation operations
597 private abstract class BufferCharView
601 redef type SELFTYPE: Buffer
605 abstract class String
608 redef type SELFTYPE: String
610 redef fun to_s
do return self
614 # Immutable strings of characters.
619 redef type SELFTYPE: FlatString
621 # Index in _items of the start of the string
622 private var index_from
: Int
624 # Indes in _items of the last item of the string
625 private var index_to
: Int
627 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
629 ################################################
630 # AbstractString specific methods #
631 ################################################
635 var native
= calloc_string
(self.length
+ 1)
636 var length
= self.length
637 var items
= self.items
640 while pos
< length
do
641 native
[pos
] = items
[ipos
]
645 return native
.to_s_with_length
(self.length
)
648 redef fun substring
(from
, count
)
654 if count
< 0 then count
= 0
658 var realFrom
= index_from
+ from
660 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
662 if count
== 0 then return empty
664 var to
= realFrom
+ count
- 1
666 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
669 redef fun empty
do return "".as(FlatString)
673 var outstr
= calloc_string
(self.length
+ 1)
676 var myitems
= self.items
677 var index_from
= self.index_from
678 var max
= self.index_to
680 while index_from
<= max
do
681 outstr
[out_index
] = myitems
[index_from
].to_upper
686 outstr
[self.length
] = '\0'
688 return outstr
.to_s_with_length
(self.length
)
693 var outstr
= calloc_string
(self.length
+ 1)
696 var myitems
= self.items
697 var index_from
= self.index_from
698 var max
= self.index_to
700 while index_from
<= max
do
701 outstr
[out_index
] = myitems
[index_from
].to_lower
706 outstr
[self.length
] = '\0'
708 return outstr
.to_s_with_length
(self.length
)
713 var i
= self.index_from
714 var imax
= self.index_to
721 ##################################################
722 # String Specific Methods #
723 ##################################################
725 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
733 redef fun to_cstring
: NativeString
735 if real_items
!= null then return real_items
.as(not null)
736 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
737 var newItems
= calloc_string
(length
+ 1)
738 self.items
.copy_to
(newItems
, length
, index_from
, 0)
739 newItems
[length
] = '\0'
740 self.real_items
= newItems
748 if not other
isa FlatString then return super
750 if self.object_id
== other
.object_id
then return true
752 var my_length
= length
754 if other
.length
!= my_length
then return false
756 var my_index
= index_from
757 var its_index
= other
.index_from
759 var last_iteration
= my_index
+ my_length
761 var itsitems
= other
.items
762 var myitems
= self.items
764 while my_index
< last_iteration
do
765 if myitems
[my_index
] != itsitems
[its_index
] then return false
775 if not other
isa FlatString then return super
777 if self.object_id
== other
.object_id
then return false
779 var my_curr_char
: Char
780 var its_curr_char
: Char
782 var curr_id_self
= self.index_from
783 var curr_id_other
= other
.index_from
785 var my_items
= self.items
786 var its_items
= other
.items
788 var my_length
= self.length
789 var its_length
= other
.length
791 var max_iterations
= curr_id_self
+ my_length
793 while curr_id_self
< max_iterations
do
794 my_curr_char
= my_items
[curr_id_self
]
795 its_curr_char
= its_items
[curr_id_other
]
797 if my_curr_char
!= its_curr_char
then
798 if my_curr_char
< its_curr_char
then return true
806 return my_length
< its_length
811 var my_length
= self.length
812 var its_length
= s
.length
814 var total_length
= my_length
+ its_length
816 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
818 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
819 if s
isa FlatString then
820 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
821 else if s
isa FlatBuffer then
822 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
824 var curr_pos
= my_length
826 target_string
[curr_pos
] = i
831 target_string
[total_length
] = '\0'
833 return target_string
.to_s_with_length
(total_length
)
840 var my_length
= self.length
842 var final_length
= my_length
* i
844 var my_items
= self.items
846 var target_string
= calloc_string
((final_length
) + 1)
848 target_string
[final_length
] = '\0'
852 for iteration
in [1 .. i
] do
853 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
854 current_last
+= my_length
857 return target_string
.to_s_with_length
(final_length
)
862 if hash_cache
== null then
863 # djb2 hash algorithm
869 while i
<= index_to
do
870 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
877 return hash_cache
.as(not null)
881 private class FlatStringReverseIterator
882 super IndexedIterator[Char]
884 var target
: FlatString
886 var target_items
: NativeString
890 init with_pos
(tgt
: FlatString, pos
: Int)
893 target_items
= tgt
.items
894 curr_pos
= pos
+ tgt
.index_from
897 redef fun is_ok
do return curr_pos
>= 0
899 redef fun item
do return target_items
[curr_pos
]
901 redef fun next
do curr_pos
-= 1
903 redef fun index
do return curr_pos
- target
.index_from
907 private class FlatStringIterator
908 super IndexedIterator[Char]
910 var target
: FlatString
912 var target_items
: NativeString
916 init with_pos
(tgt
: FlatString, pos
: Int)
919 target_items
= tgt
.items
920 curr_pos
= pos
+ target
.index_from
923 redef fun is_ok
do return curr_pos
<= target
.index_to
925 redef fun item
do return target_items
[curr_pos
]
927 redef fun next
do curr_pos
+= 1
929 redef fun index
do return curr_pos
- target
.index_from
933 private class FlatStringCharView
936 redef type SELFTYPE: FlatString
940 # Check that the index (+ index_from) is not larger than indexTo
941 # In other terms, if the index is valid
943 var target
= self.target
944 assert (index
+ target
.index_from
) <= target
.index_to
945 return target
.items
[index
+ target
.index_from
]
948 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
950 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
954 abstract class Buffer
957 redef type SELFTYPE: Buffer
959 # Specific implementations MUST set this to `true` in order to invalidate caches
960 protected var is_dirty
= true
962 # Modifies the char contained at pos `index`
964 # DEPRECATED : Use self.chars.[]= instead
965 fun []=(index
: Int, item
: Char) is abstract
967 # Adds a char `c` at the end of self
969 # DEPRECATED : Use self.chars.add instead
970 fun add
(c
: Char) is abstract
974 # var b = new FlatBuffer
976 # assert not b.is_empty
979 fun clear
is abstract
981 # Enlarges the subsequent array containing the chars of self
982 fun enlarge
(cap
: Int) is abstract
984 # Adds the content of text `s` at the end of self
986 # var b = new FlatBuffer
989 # assert b == "helloworld"
990 fun append
(s
: Text) is abstract
994 if is_dirty
then hash_cache
= null
998 # In Buffers, the internal sequence of character is mutable
999 # Thus, `chars` can be used to modify the buffer.
1000 redef fun chars
: Sequence[Char] is abstract
1003 # Mutable strings of characters.
1008 redef type SELFTYPE: FlatBuffer
1010 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1012 private var capacity
: Int = 0
1014 redef fun []=(index
, item
)
1017 if index
== length
then
1021 assert index
>= 0 and index
< length
1028 if capacity
<= length
then enlarge
(length
+ 5)
1038 redef fun empty
do return new FlatBuffer
1040 redef fun enlarge
(cap
)
1043 if cap
<= c
then return
1044 while c
<= cap
do c
= c
* 2 + 2
1045 var a
= calloc_string
(c
+1)
1046 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1051 redef fun to_s
: String
1053 return to_cstring
.to_s_with_length
(length
)
1056 redef fun to_cstring
1059 var new_native
= calloc_string
(length
+ 1)
1060 new_native
[length
] = '\0'
1061 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1062 real_items
= new_native
1065 return real_items
.as(not null)
1068 # Create a new empty string.
1073 capacity
= s
.length
+ 1
1075 items
= calloc_string
(capacity
)
1076 if s
isa FlatString then
1077 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1078 else if s
isa FlatBuffer then
1079 s
.items
.copy_to
(items
, length
, 0, 0)
1089 # Create a new empty string with a given capacity.
1090 init with_capacity
(cap
: Int)
1093 # _items = new NativeString.calloc(cap)
1094 items
= calloc_string
(cap
+1)
1101 if s
.is_empty
then return
1104 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1105 if s
isa FlatString then
1106 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1107 else if s
isa FlatBuffer then
1108 s
.items
.copy_to
(items
, sl
, 0, length
)
1110 var curr_pos
= self.length
1119 # Copies the content of self in `dest`
1120 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1122 var self_chars
= self.chars
1123 var dest_chars
= dest
.chars
1124 for i
in [0..len-1
] do
1125 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1129 redef fun substring
(from
, count
)
1133 if from
< 0 then from
= 0
1134 if count
> length
then count
= length
1135 if from
< count
then
1136 var r
= new FlatBuffer.with_capacity
(count
- from
)
1137 while from
< count
do
1138 r
.chars
.push
(items
[from
])
1143 return new FlatBuffer
1149 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1150 var reviter
= self.chars
.reverse_iterator
1151 while reviter
.is_ok
do
1152 new_buf
.add
(reviter
.item
)
1160 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1161 new_buf
.append
(self)
1162 new_buf
.append
(other
)
1166 redef fun *(repeats
)
1168 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1169 for i
in [0..repeats
[ do
1170 new_buf
.append
(self)
1177 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1178 for i
in self.chars
do
1179 new_buf
.add
(i
.to_upper
)
1186 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1187 for i
in self.chars
do
1188 new_buf
.add
(i
.to_lower
)
1194 private class FlatBufferReverseIterator
1195 super IndexedIterator[Char]
1197 var target
: FlatBuffer
1199 var target_items
: NativeString
1203 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1206 if tgt
.length
> 0 then target_items
= tgt
.items
1210 redef fun index
do return curr_pos
1212 redef fun is_ok
do return curr_pos
>= 0
1214 redef fun item
do return target_items
[curr_pos
]
1216 redef fun next
do curr_pos
-= 1
1220 private class FlatBufferCharView
1221 super BufferCharView
1224 redef type SELFTYPE: FlatBuffer
1226 redef fun [](index
) do return target
.items
[index
]
1228 redef fun []=(index
, item
)
1230 assert index
>= 0 and index
<= length
1231 if index
== length
then
1235 target
.items
[index
] = item
1248 fun enlarge
(cap
: Int)
1255 var my_items
= target
.items
1256 var s_length
= s
.length
1257 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1260 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1262 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1266 private class FlatBufferIterator
1267 super IndexedIterator[Char]
1269 var target
: FlatBuffer
1271 var target_items
: NativeString
1275 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1278 if tgt
.length
> 0 then target_items
= tgt
.items
1282 redef fun index
do return curr_pos
1284 redef fun is_ok
do return curr_pos
< target
.length
1286 redef fun item
do return target_items
[curr_pos
]
1288 redef fun next
do curr_pos
+= 1
1292 ###############################################################################
1294 ###############################################################################
1297 # User readable representation of `self`.
1298 fun to_s
: String do return inspect
1300 # The class name of the object in NativeString format.
1301 private fun native_class_name
: NativeString is intern
1303 # The class name of the object.
1305 # assert 5.class_name == "Int"
1306 fun class_name
: String do return native_class_name
.to_s
1308 # Developer readable representation of `self`.
1309 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1312 return "<{inspect_head}>"
1315 # Return "CLASSNAME:#OBJECTID".
1316 # This function is mainly used with the redefinition of the inspect method
1317 protected fun inspect_head
: String
1319 return "{class_name}:#{object_id.to_hex}"
1322 protected fun args
: Sequence[String]
1329 # assert true.to_s == "true"
1330 # assert false.to_s == "false"
1343 # Wrapper of strerror C function
1344 private fun strerror_ext
: NativeString is extern `{
1345 return strerror(recv);
1348 # Returns a string describing error number
1349 fun strerror
: String do return strerror_ext
.to_s
1351 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1352 # assume < to_c max const of char
1353 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1360 else if self == 0 then
1367 var pos
= digit_count
(base
) - 1
1368 while pos
>= 0 and n
> 0 do
1369 s
.chars
[pos
] = (n
% base
).to_c
1375 # C function to convert an nit Int to a NativeString (char*)
1376 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1378 # return displayable int in base 10 and signed
1380 # assert 1.to_s == "1"
1381 # assert (-123).to_s == "-123"
1383 var len
= digit_count
(10)
1384 return native_int_to_s
(len
).to_s_with_length
(len
)
1387 # return displayable int in hexadecimal
1389 # assert 1.to_hex == "1"
1390 # assert (-255).to_hex == "-ff"
1391 fun to_hex
: String do return to_base
(16,false)
1393 # return displayable int in base base and signed
1394 fun to_base
(base
: Int, signed
: Bool): String
1396 var l
= digit_count
(base
)
1397 var s
= new FlatBuffer.from
(" " * l
)
1398 fill_buffer
(s
, base
, signed
)
1404 # Pretty print self, print needoed decimals up to a max of 3.
1406 # assert 12.34.to_s == "12.34"
1407 # assert (-0120.03450).to_s == "-120.035"
1409 # see `to_precision` for a different precision.
1411 var str
= to_precision
( 3 )
1412 if is_inf
!= 0 or is_nan
then return str
1413 var len
= str
.length
1414 for i
in [0..len-1
] do
1416 var c
= str
.chars
[j
]
1419 else if c
== '.' then
1420 return str
.substring
( 0, j
+2 )
1422 return str
.substring
( 0, j
+1 )
1428 # `self` representation with `nb` digits after the '.'.
1430 # assert 12.345.to_precision(1) == "12.3"
1431 # assert 12.345.to_precision(2) == "12.35"
1432 # assert 12.345.to_precision(3) == "12.345"
1433 # assert 12.345.to_precision(4) == "12.3450"
1434 fun to_precision
(nb
: Int): String
1436 if is_nan
then return "nan"
1438 var isinf
= self.is_inf
1441 else if isinf
== -1 then
1445 if nb
== 0 then return self.to_i
.to_s
1447 for i
in [0..nb
[ do f
= f
* 10.0
1454 if i
== 0 then return "0.0"
1458 var p1
= s
.substring
(0, s
.length-nb
)
1459 var p2
= s
.substring
(s
.length-nb
, nb
)
1460 return p1
+ "." + p2
1462 return "0." + ("0"*(nb-sl
)) + s
1466 # `self` representation with `nb` digits after the '.'.
1468 # assert 12.345.to_precision_native(1) == "12.3"
1469 # assert 12.345.to_precision_native(2) == "12.35"
1470 # assert 12.345.to_precision_native(3) == "12.345"
1471 # assert 12.345.to_precision_native(4) == "12.3450"
1472 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1476 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1477 str = malloc(size + 1);
1478 sprintf(str, "%.*f", (int)nb, recv );
1480 return NativeString_to_s( str );
1485 # assert 'x'.to_s == "x"
1488 var s
= new FlatBuffer.with_capacity
(1)
1493 # Returns true if the char is a numerical digit
1495 # assert '0'.is_numeric
1496 # assert '9'.is_numeric
1497 # assert not 'a'.is_numeric
1498 # assert not '?'.is_numeric
1499 fun is_numeric
: Bool
1501 return self >= '0' and self <= '9'
1504 # Returns true if the char is an alpha digit
1506 # assert 'a'.is_alpha
1507 # assert 'Z'.is_alpha
1508 # assert not '0'.is_alpha
1509 # assert not '?'.is_alpha
1512 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1515 # Returns true if the char is an alpha or a numeric digit
1517 # assert 'a'.is_alphanumeric
1518 # assert 'Z'.is_alphanumeric
1519 # assert '0'.is_alphanumeric
1520 # assert '9'.is_alphanumeric
1521 # assert not '?'.is_alphanumeric
1522 fun is_alphanumeric
: Bool
1524 return self.is_numeric
or self.is_alpha
1528 redef class Collection[E
]
1529 # Concatenate elements.
1532 var s
= new FlatBuffer
1533 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1537 # Concatenate and separate each elements with `sep`.
1539 # assert [1, 2, 3].join(":") == "1:2:3"
1540 # assert [1..3].join(":") == "1:2:3"
1541 fun join
(sep
: Text): String
1543 if is_empty
then return ""
1545 var s
= new FlatBuffer # Result
1550 if e
!= null then s
.append
(e
.to_s
)
1552 # Concat other items
1557 if e
!= null then s
.append
(e
.to_s
)
1564 redef class Array[E
]
1565 # Fast implementation
1568 var s
= new FlatBuffer
1573 if e
!= null then s
.append
(e
.to_s
)
1580 redef class Map[K
,V
]
1581 # Concatenate couple of 'key value'.
1582 # key and value are separated by `couple_sep`.
1583 # each couple is separated each couple with `sep`.
1585 # var m = new ArrayMap[Int, String]
1588 # assert m.join("; ", "=") == "1=one; 10=ten"
1589 fun join
(sep
: String, couple_sep
: String): String
1591 if is_empty
then return ""
1593 var s
= new FlatBuffer # Result
1599 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1601 # Concat other items
1607 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1614 ###############################################################################
1616 ###############################################################################
1618 # Native strings are simple C char *
1622 fun [](index
: Int): Char is intern
1623 fun []=(index
: Int, item
: Char) is intern
1624 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1626 # Position of the first nul character.
1627 fun cstring_length
: Int
1630 while self[l
] != '\0' do l
+= 1
1633 fun atoi
: Int is intern
1634 fun atof
: Float is extern "atof"
1638 return to_s_with_length
(cstring_length
)
1641 fun to_s_with_length
(length
: Int): FlatString
1644 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1647 fun to_s_with_copy
: FlatString
1649 var length
= cstring_length
1650 var new_self
= calloc_string
(length
+ 1)
1651 copy_to
(new_self
, length
, 0, 0)
1652 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1657 # StringCapable objects can create native strings
1658 interface StringCapable
1659 protected fun calloc_string
(size
: Int): NativeString is intern
1663 var _args_cache
: nullable Sequence[String]
1665 redef fun args
: Sequence[String]
1667 if _args_cache
== null then init_args
1668 return _args_cache
.as(not null)
1671 # The name of the program as given by the OS
1672 fun program_name
: String
1674 return native_argv
(0).to_s
1677 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1678 private fun init_args
1680 var argc
= native_argc
1681 var args
= new Array[String].with_capacity
(0)
1684 args
[i-1
] = native_argv
(i
).to_s
1690 # First argument of the main C function.
1691 private fun native_argc
: Int is intern
1693 # Second argument of the main C function.
1694 private fun native_argv
(i
: Int): NativeString is intern
1697 # Comparator that efficienlty use `to_s` to compare things
1699 # The comparaison call `to_s` on object and use the result to order things.
1701 # var a = [1, 2, 3, 10, 20]
1702 # (new CachedAlphaComparator).sort(a)
1703 # assert a == [1, 10, 2, 20, 3]
1705 # Internally the result of `to_s` is cached in a HashMap to counter
1706 # uneficient implementation of `to_s`.
1708 # Note: it caching is not usefull, see `alpha_comparator`
1709 class CachedAlphaComparator
1710 super Comparator[Object]
1712 private var cache
= new HashMap[Object, String]
1714 private fun do_to_s
(a
: Object): String do
1715 if cache
.has_key
(a
) then return cache
[a
]
1721 redef fun compare
(a
, b
) do
1722 return do_to_s
(a
) <=> do_to_s
(b
)
1726 # see `alpha_comparator`
1727 private class AlphaComparator
1728 super Comparator[Object]
1729 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1732 # Stateless comparator that naively use `to_s` to compare things.
1734 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1735 # on a single instace. See `CachedAlphaComparator` as an alternative.
1737 # var a = [1, 2, 3, 10, 20]
1738 # alpha_comparator.sort(a)
1739 # assert a == [1, 10, 2, 20, 3]
1740 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator