11dece3569707b88ce798d9274e8471a08f43a3d
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
24 ###############################################################################
26 ###############################################################################
28 # High-level abstraction for all text representations
33 redef type OTHER: Text
35 # Type of the view on self (.chars)
36 type SELFVIEW: StringCharView
38 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
41 # Gets a view on the chars of the Text object
42 fun chars
: SELFVIEW is abstract
44 # Number of characters contained in self.
45 fun length
: Int is abstract
49 # assert "abcd".substring(1, 2) == "bc"
50 # assert "abcd".substring(-1, 2) == "a"
51 # assert "abcd".substring(1, 0) == ""
52 # assert "abcd".substring(2, 5) == "cd"
54 # A `from` index < 0 will be replaced by 0.
55 # Unless a `count` value is > 0 at the same time.
56 # In this case, `from += count` and `count -= from`.
57 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
59 # Concatenates `o` to `self`
60 fun +(o
: Text): SELFTYPE is abstract
62 # Auto-concatenates self `i` times
63 fun *(i
: Int): SELFTYPE is abstract
65 # Is the current Text empty (== "")
67 # assert not "foo".is_empty
68 fun is_empty
: Bool do return self.length
== 0
70 # Returns an empty Text of the right type
71 fun empty
: SELFTYPE is abstract
73 # Gets the first char of the Text
75 # DEPRECATED : Use self.chars.first instead
76 fun first
: Char do return self.chars
[0]
78 # Access a character at `index` in the string.
80 # assert "abcd"[2] == 'c'
82 # DEPRECATED : Use self.chars.[] instead
83 fun [](index
: Int): Char do return self.chars
[index
]
85 # Gets the index of the first occurence of 'c'
87 # Returns -1 if not found
89 # DEPRECATED : Use self.chars.index_of instead
90 fun index_of
(c
: Char): Int
92 return index_of_from
(c
, 0)
95 # Gets the last char of self
97 # DEPRECATED : Use self.chars.last instead
98 fun last
: Char do return self.chars
[length-1
]
100 # Gets the index of the first occurence of ´c´ starting from ´pos´
102 # Returns -1 if not found
104 # DEPRECATED : Use self.chars.index_of_from instead
105 fun index_of_from
(c
: Char, pos
: Int): Int
107 var iter
= self.chars
.iterator_from
(pos
)
109 if iter
.item
== c
then return iter
.index
114 # Gets the last index of char ´c´
116 # Returns -1 if not found
118 # DEPRECATED : Use self.chars.last_index_of instead
119 fun last_index_of
(c
: Char): Int
121 return last_index_of_from
(c
, length
- 1)
124 # Return a null terminated char *
125 fun to_cstring
: NativeString do return flatten
.to_cstring
127 # The index of the last occurrence of an element starting from pos (in reverse order).
129 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
130 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
132 # Returns -1 if not found
134 # DEPRECATED : Use self.chars.last_index_of_from instead
135 fun last_index_of_from
(item
: Char, pos
: Int): Int
137 var iter
= self.chars
.reverse_iterator_from
(pos
)
139 if iter
.item
== item
then return iter
.index
145 # Gets an iterator on the chars of self
147 # DEPRECATED : Use self.chars.iterator instead
148 fun iterator
: Iterator[Char]
150 return self.chars
.iterator
153 # Is 'c' contained in self ?
155 # DEPRECATED : Use self.chars.has instead
156 fun has
(c
: Char): Bool
158 return self.chars
.has
(c
)
161 # Gets an Array containing the chars of self
163 # DEPRECATED : Use self.chars.to_a instead
164 fun to_a
: Array[Char] do return chars
.to_a
166 # Create a substring from `self` beginning at the `from` position
168 # assert "abcd".substring_from(1) == "bcd"
169 # assert "abcd".substring_from(-1) == "abcd"
170 # assert "abcd".substring_from(2) == "cd"
172 # As with substring, a `from` index < 0 will be replaced by 0
173 fun substring_from
(from
: Int): SELFTYPE
175 if from
> self.length
then return empty
176 if from
< 0 then from
= 0
177 return substring
(from
, length
- from
)
180 # Returns a reversed version of self
181 fun reversed
: SELFTYPE is abstract
183 # Does self have a substring `str` starting from position `pos`?
185 # assert "abcd".has_substring("bc",1) == true
186 # assert "abcd".has_substring("bc",2) == false
187 fun has_substring
(str
: String, pos
: Int): Bool
189 var myiter
= self.chars
.iterator_from
(pos
)
190 var itsiter
= str
.iterator
191 while myiter
.is_ok
and itsiter
.is_ok
do
192 if myiter
.item
!= itsiter
.item
then return false
196 if itsiter
.is_ok
then return false
200 # Is this string prefixed by `prefix`?
202 # assert "abcd".has_prefix("ab") == true
203 # assert "abcbc".has_prefix("bc") == false
204 # assert "ab".has_prefix("abcd") == false
205 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
207 # Is this string suffixed by `suffix`?
209 # assert "abcd".has_suffix("abc") == false
210 # assert "abcd".has_suffix("bcd") == true
211 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
213 # If `self` contains only digits, return the corresponding integer
215 # assert "123".to_i == 123
216 # assert "-1".to_i == -1
220 return to_s
.to_cstring
.atoi
223 # If `self` contains a float, return the corresponding float
225 # assert "123".to_f == 123.0
226 # assert "-1".to_f == -1.0
227 # assert "-1.2e-3".to_f == -0.0012
231 return to_s
.to_cstring
.atof
234 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
235 fun to_hex
: Int do return a_to
(16)
237 # If `self` contains only digits and letters, return the corresponding integer in a given base
239 # assert "120".a_to(3) == 15
240 fun a_to
(base
: Int) : Int
267 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
269 # assert "123".is_numeric == true
270 # assert "1.2".is_numeric == true
271 # assert "1,2".is_numeric == true
272 # assert "1..2".is_numeric == false
275 var has_point_or_comma
= false
280 if (i
== '.' or i
== ',') and not has_point_or_comma
282 has_point_or_comma
= true
291 # A upper case version of `self`
293 # assert "Hello World!".to_upper == "HELLO WORLD!"
294 fun to_upper
: SELFTYPE is abstract
296 # A lower case version of `self`
298 # assert "Hello World!".to_lower == "hello world!"
299 fun to_lower
: SELFTYPE is abstract
301 # Removes the whitespaces at the beginning of self
304 var iter
= self.chars
.iterator
306 if iter
.item
.ascii
> 32 then break
309 if iter
.index
== length
then return self.empty
310 return self.substring_from
(iter
.index
)
313 # Removes the whitespaces at the end of self
316 var iter
= self.chars
.reverse_iterator
318 if iter
.item
.ascii
> 32 then break
321 if iter
.index
== length
then return self.empty
322 return self.substring
(0, iter
.index
+ 1)
325 # Trims trailing and preceding white spaces
326 # A whitespace is defined as any character which ascii value is less than or equal to 32
328 # assert " Hello World ! ".trim == "Hello World !"
329 # assert "\na\nb\tc\t".trim == "a\nb\tc"
330 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
332 # Mangle a string to be a unique string only made of alphanumeric characters
333 fun to_cmangle
: String
335 var res
= new FlatBuffer
336 var underscore
= false
337 for c
in self.chars
do
338 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
344 res
.append
('_'.ascii
.to_s
)
347 if c
>= '0' and c
<= '9' then
350 else if c
== '_' then
355 res
.append
(c
.ascii
.to_s
)
363 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
365 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
366 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
367 fun escape_to_c
: String
369 var b
= new FlatBuffer
370 for c
in self.chars
do
373 else if c
== '\0' then
375 else if c
== '"' then
377 else if c == '\'' then
379 else if c == '\\
' then
381 else if c.ascii < 32 then
382 b.append("\\{c.ascii.to_base(8, false)}")
390 # Escape additionnal characters
391 # The result might no be legal in C but be used in other languages
393 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
394 fun escape_more_to_c(chars: String): String
396 var b = new FlatBuffer
397 for c in escape_to_c do
398 if chars.chars.has(c) then
406 # Escape to c plus braces
408 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
409 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
411 # Return a string where Nit escape sequences are transformed.
415 # assert s.length == 2
416 # var u = s.unescape_nit
417 # assert u.length == 1
418 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
419 fun unescape_nit
: String
421 var res
= new FlatBuffer.with_capacity
(self.length
)
422 var was_slash
= false
424 if not was_slash
then
435 else if c
== 'r' then
437 else if c
== 't' then
439 else if c
== '0' then
450 if o
== null then return false
451 if not o
isa Text then return false
452 if self.is_same_instance
(o
) then return true
453 if self.length
!= o
.length
then return false
454 return self.chars
== o
.chars
459 return self.chars
< o
.chars
462 # Flat representation of self
463 fun flatten
: FlatText is abstract
467 # All kinds of array-based text representations.
468 abstract class FlatText
471 private var items
: NativeString
473 redef var length
: Int
486 redef fun flatten
do return self
489 # Abstract class for the SequenceRead compatible
490 # views on String and Buffer objects
491 abstract class StringCharView
492 super SequenceRead[Char]
497 redef type OTHER: StringCharView
499 private var target
: SELFTYPE
501 private init(tgt
: SELFTYPE)
506 redef fun is_empty
do return target
.is_empty
508 redef fun length
do return target
.length
510 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
512 # Gets a new Iterator starting at position `pos`
515 # var iter = "abcd".iterator_from(2)
516 # while iter.is_ok do
522 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
524 # Gets an iterator starting at the end and going backwards
527 # var reviter = "now step live...".reverse_iterator
528 # while reviter.is_ok do
529 # printn reviter.item
533 # Outputs : ...evil pets won
534 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
536 # Gets an iterator on the chars of self starting from `pos`
539 # var iter = "abcd".reverse_iterator_from(1)
540 # while iter.is_ok do
546 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
548 redef fun has
(c
: Char): Bool
551 if i
== c
then return true
558 if other
== null then return false
559 if not other
isa StringCharView then return false
560 var other_chars
= other
.iterator
562 if i
!= other_chars
.item
then return false
570 var self_chars
= self.iterator
571 var other_chars
= other
.iterator
573 while self_chars
.is_ok
and other_chars
.is_ok
do
574 if self_chars
.item
< other_chars
.item
then return true
575 if self_chars
.item
> other_chars
.item
then return false
580 if self_chars
.is_ok
then
588 # View on Buffer objects, extends Sequence
589 # for mutation operations
590 abstract class BufferCharView
594 redef type SELFTYPE: Buffer
598 abstract class String
601 redef type SELFTYPE: String
603 redef fun to_s
do return self
607 # Immutable strings of characters.
612 redef type SELFTYPE: FlatString
613 redef type SELFVIEW: FlatStringCharView
615 # Index in _items of the start of the string
616 private var index_from
: Int
618 # Indes in _items of the last item of the string
619 private var index_to
: Int
621 redef var chars
: SELFVIEW = new FlatStringCharView(self)
623 ################################################
624 # AbstractString specific methods #
625 ################################################
627 redef fun [](index
) do
629 # Check that the index (+ index_from) is not larger than indexTo
630 # In other terms, if the index is valid
631 assert (index
+ index_from
) <= index_to
632 return items
[index
+ index_from
]
637 var native
= calloc_string
(self.length
+ 1)
638 var reviter
= chars
.reverse_iterator
640 while reviter
.is_ok
do
641 native
[pos
] = reviter
.item
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 # Return a null terminated char *
734 redef fun to_cstring
: NativeString
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'
747 if not other
isa FlatString then return super
749 if self.object_id
== other
.object_id
then return true
751 var my_length
= length
753 if other
.length
!= my_length
then return false
755 var my_index
= index_from
756 var its_index
= other
.index_from
758 var last_iteration
= my_index
+ my_length
760 var itsitems
= other
.items
761 var myitems
= self.items
763 while my_index
< last_iteration
do
764 if myitems
[my_index
] != itsitems
[its_index
] then return false
772 # The comparison between two strings is done on a lexicographical basis
774 # assert ("aa" < "b") == true
777 if not other
isa FlatString then return super
779 if self.object_id
== other
.object_id
then return false
781 var my_curr_char
: Char
782 var its_curr_char
: Char
784 var curr_id_self
= self.index_from
785 var curr_id_other
= other
.index_from
787 var my_items
= self.items
788 var its_items
= other
.items
790 var my_length
= self.length
791 var its_length
= other
.length
793 var max_iterations
= curr_id_self
+ my_length
795 while curr_id_self
< max_iterations
do
796 my_curr_char
= my_items
[curr_id_self
]
797 its_curr_char
= its_items
[curr_id_other
]
799 if my_curr_char
!= its_curr_char
then
800 if my_curr_char
< its_curr_char
then return true
808 return my_length
< its_length
811 # The concatenation of `self` with `s`
813 # assert "hello " + "world!" == "hello world!"
816 var my_length
= self.length
817 var its_length
= s
.length
819 var total_length
= my_length
+ its_length
821 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
823 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
824 if s
isa FlatString then
825 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
826 else if s
isa FlatBuffer then
827 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
829 var curr_pos
= my_length
831 target_string
[curr_pos
] = i
836 target_string
[total_length
] = '\0'
838 return target_string
.to_s_with_length
(total_length
)
841 # assert "abc"*3 == "abcabcabc"
842 # assert "abc"*1 == "abc"
843 # assert "abc"*0 == ""
848 var my_length
= self.length
850 var final_length
= my_length
* i
852 var my_items
= self.items
854 var target_string
= calloc_string
((final_length
) + 1)
856 target_string
[final_length
] = '\0'
860 for iteration
in [1 .. i
] do
861 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
862 current_last
+= my_length
865 return target_string
.to_s_with_length
(final_length
)
870 # djb2 hash algorythm
875 var strStart
= index_from
879 while i
>= strStart
do
880 h
= (h
* 32) + h
+ self.items
[i
].ascii
888 private class FlatStringReverseIterator
889 super IndexedIterator[Char]
891 var target
: FlatString
893 var target_items
: NativeString
897 init with_pos
(tgt
: FlatString, pos
: Int)
900 target_items
= tgt
.items
901 curr_pos
= pos
+ tgt
.index_from
904 redef fun is_ok
do return curr_pos
>= 0
906 redef fun item
do return target_items
[curr_pos
]
908 redef fun next
do curr_pos
-= 1
910 redef fun index
do return curr_pos
- target
.index_from
914 private class FlatStringIterator
915 super IndexedIterator[Char]
917 var target
: FlatString
919 var target_items
: NativeString
923 init with_pos
(tgt
: FlatString, pos
: Int)
926 target_items
= tgt
.items
927 curr_pos
= pos
+ target
.index_from
930 redef fun is_ok
do return curr_pos
<= target
.index_to
932 redef fun item
do return target_items
[curr_pos
]
934 redef fun next
do curr_pos
+= 1
936 redef fun index
do return curr_pos
- target
.index_from
940 private class FlatStringCharView
943 redef type SELFTYPE: FlatString
947 # Check that the index (+ index_from) is not larger than indexTo
948 # In other terms, if the index is valid
950 assert (index
+ target
.index_from
) <= target
.index_to
951 return target
.items
[index
+ target
.index_from
]
954 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
956 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
960 abstract class Buffer
963 redef type SELFVIEW: BufferCharView
964 redef type SELFTYPE: Buffer
966 # Modifies the char contained at pos `index`
968 # DEPRECATED : Use self.chars.[]= instead
969 fun []=(index
: Int, item
: Char) is abstract
971 # Adds a char `c` at the end of self
973 # DEPRECATED : Use self.chars.add instead
974 fun add
(c
: Char) is abstract
977 fun clear
is abstract
979 # Enlarges the subsequent array containing the chars of self
980 fun enlarge
(cap
: Int) is abstract
982 # Adds the content of text `s` at the end of self
983 fun append
(s
: Text) is abstract
987 # Mutable strings of characters.
992 redef type SELFVIEW: FlatBufferCharView
993 redef type SELFTYPE: FlatBuffer
995 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
999 redef fun []=(index
, item
)
1001 if index
== length
then
1005 assert index
>= 0 and index
< length
1011 if capacity
<= length
then enlarge
(length
+ 5)
1016 redef fun clear
do length
= 0
1018 redef fun empty
do return new FlatBuffer
1020 redef fun enlarge
(cap
)
1023 if cap
<= c
then return
1024 while c
<= cap
do c
= c
* 2 + 2
1025 var a
= calloc_string
(c
+1)
1026 items
.copy_to
(a
, length
, 0, 0)
1029 items
.copy_to
(a
, length
, 0, 0)
1032 redef fun to_s
: String
1035 var a
= calloc_string
(l
+1)
1036 items
.copy_to
(a
, l
, 0, 0)
1038 # Ensure the afterlast byte is '\0' to nul-terminated char *
1041 return a
.to_s_with_length
(length
)
1044 redef fun to_cstring
1046 var new_native
= calloc_string
(length
+ 1)
1047 new_native
[length
] = '\0'
1048 items
.copy_to
(new_native
, length
, 0, 0)
1052 # Create a new empty string.
1060 capacity
= s
.length
+ 1
1062 items
= calloc_string
(capacity
)
1063 if s
isa FlatString then
1064 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1065 else if s
isa FlatBuffer then
1066 s
.items
.copy_to
(items
, length
, 0, 0)
1076 # Create a new empty string with a given capacity.
1077 init with_capacity
(cap
: Int)
1080 # _items = new NativeString.calloc(cap)
1081 items
= calloc_string
(cap
+1)
1089 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1090 if s
isa FlatString then
1091 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1092 else if s
isa FlatBuffer then
1093 s
.items
.copy_to
(items
, sl
, 0, length
)
1095 var curr_pos
= self.length
1104 # Copies the content of self in `dest`
1105 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1107 var self_chars
= self.chars
1108 var dest_chars
= dest
.chars
1109 for i
in [0..len-1
] do
1110 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1114 redef fun substring
(from
, count
)
1118 if from
< 0 then from
= 0
1119 if count
> length
then count
= length
1120 if from
< count
then
1121 var r
= new FlatBuffer.with_capacity
(count
- from
)
1122 while from
< count
do
1123 r
.chars
.push
(items
[from
])
1128 return new FlatBuffer
1134 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1135 var reviter
= self.chars
.reverse_iterator
1136 while reviter
.is_ok
do
1137 new_buf
.add
(reviter
.item
)
1145 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1146 new_buf
.append
(self)
1147 new_buf
.append
(other
)
1151 redef fun *(repeats
)
1153 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1154 for i
in [0..repeats
[ do
1155 new_buf
.append
(self)
1161 private class FlatBufferReverseIterator
1162 super IndexedIterator[Char]
1164 var target
: FlatBuffer
1166 var target_items
: NativeString
1170 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1173 target_items
= tgt
.items
1177 redef fun index
do return curr_pos
1179 redef fun is_ok
do return curr_pos
>= 0
1181 redef fun item
do return target_items
[curr_pos
]
1183 redef fun next
do curr_pos
-= 1
1187 private class FlatBufferCharView
1188 super BufferCharView
1191 redef type SELFTYPE: FlatBuffer
1193 redef fun [](index
) do return target
.items
[index
]
1195 redef fun []=(index
, item
)
1197 assert index
>= 0 and index
<= length
1198 if index
== length
then
1202 target
.items
[index
] = item
1215 fun enlarge
(cap
: Int)
1222 var my_items
= target
.items
1223 var s_length
= s
.length
1224 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1227 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1229 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1233 private class FlatBufferIterator
1234 super IndexedIterator[Char]
1236 var target
: FlatBuffer
1238 var target_items
: NativeString
1242 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1245 target_items
= tgt
.items
1249 redef fun index
do return curr_pos
1251 redef fun is_ok
do return curr_pos
< target
.length
1253 redef fun item
do return target_items
[curr_pos
]
1255 redef fun next
do curr_pos
+= 1
1259 ###############################################################################
1261 ###############################################################################
1264 # User readable representation of `self`.
1265 fun to_s
: String do return inspect
1267 # The class name of the object in NativeString format.
1268 private fun native_class_name
: NativeString is intern
1270 # The class name of the object.
1272 # assert 5.class_name == "Int"
1273 fun class_name
: String do return native_class_name
.to_s
1275 # Developer readable representation of `self`.
1276 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1279 return "<{inspect_head}>"
1282 # Return "CLASSNAME:#OBJECTID".
1283 # This function is mainly used with the redefinition of the inspect method
1284 protected fun inspect_head
: String
1286 return "{class_name}:#{object_id.to_hex}"
1289 protected fun args
: Sequence[String]
1296 # assert true.to_s == "true"
1297 # assert false.to_s == "false"
1309 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1310 # assume < to_c max const of char
1311 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1318 else if self == 0 then
1325 var pos
= digit_count
(base
) - 1
1326 while pos
>= 0 and n
> 0 do
1327 s
.chars
[pos
] = (n
% base
).to_c
1333 # C function to convert an nit Int to a NativeString (char*)
1334 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1336 # return displayable int in base 10 and signed
1338 # assert 1.to_s == "1"
1339 # assert (-123).to_s == "-123"
1341 var len
= digit_count
(10)
1342 return native_int_to_s
(len
).to_s_with_length
(len
)
1345 # return displayable int in hexadecimal (unsigned (not now))
1346 fun to_hex
: String do return to_base
(16,false)
1348 # return displayable int in base base and signed
1349 fun to_base
(base
: Int, signed
: Bool): String
1351 var l
= digit_count
(base
)
1352 var s
= new FlatBuffer.from
(" " * l
)
1353 fill_buffer
(s
, base
, signed
)
1359 # Pretty print self, print needoed decimals up to a max of 3.
1361 var str
= to_precision
( 3 )
1362 if is_inf
!= 0 or is_nan
then return str
1363 var len
= str
.length
1364 for i
in [0..len-1
] do
1366 var c
= str
.chars
[j
]
1369 else if c
== '.' then
1370 return str
.substring
( 0, j
+2 )
1372 return str
.substring
( 0, j
+1 )
1378 # `self` representation with `nb` digits after the '.'.
1379 fun to_precision
(nb
: Int): String
1381 if is_nan
then return "nan"
1383 var isinf
= self.is_inf
1386 else if isinf
== -1 then
1390 if nb
== 0 then return self.to_i
.to_s
1392 for i
in [0..nb
[ do f
= f
* 10.0
1399 if i
== 0 then return "0.0"
1403 var p1
= s
.substring
(0, s
.length-nb
)
1404 var p2
= s
.substring
(s
.length-nb
, nb
)
1405 return p1
+ "." + p2
1407 return "0." + ("0"*(nb-sl
)) + s
1411 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1415 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1416 str = malloc(size + 1);
1417 sprintf(str, "%.*f", (int)nb, recv );
1419 return NativeString_to_s( str );
1424 # assert 'x'.to_s == "x"
1427 var s
= new FlatBuffer.with_capacity
(1)
1432 # Returns true if the char is a numerical digit
1433 fun is_numeric
: Bool
1435 if self >= '0' and self <= '9'
1442 # Returns true if the char is an alpha digit
1445 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1449 # Returns true if the char is an alpha or a numeric digit
1450 fun is_alphanumeric
: Bool
1452 if self.is_numeric
or self.is_alpha
then return true
1457 redef class Collection[E
]
1458 # Concatenate elements.
1461 var s
= new FlatBuffer
1462 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1466 # Concatenate and separate each elements with `sep`.
1468 # assert [1, 2, 3].join(":") == "1:2:3"
1469 # assert [1..3].join(":") == "1:2:3"
1470 fun join
(sep
: String): String
1472 if is_empty
then return ""
1474 var s
= new FlatBuffer # Result
1479 if e
!= null then s
.append
(e
.to_s
)
1481 # Concat other items
1486 if e
!= null then s
.append
(e
.to_s
)
1493 redef class Array[E
]
1494 # Fast implementation
1497 var s
= new FlatBuffer
1502 if e
!= null then s
.append
(e
.to_s
)
1509 redef class Map[K
,V
]
1510 # Concatenate couple of 'key value'.
1511 # key and value are separated by `couple_sep`.
1512 # each couple is separated each couple with `sep`.
1514 # var m = new ArrayMap[Int, String]
1517 # assert m.join("; ", "=") == "1=one; 10=ten"
1518 fun join
(sep
: String, couple_sep
: String): String
1520 if is_empty
then return ""
1522 var s
= new FlatBuffer # Result
1528 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1530 # Concat other items
1536 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1543 ###############################################################################
1545 ###############################################################################
1547 # Native strings are simple C char *
1551 fun [](index
: Int): Char is intern
1552 fun []=(index
: Int, item
: Char) is intern
1553 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1555 # Position of the first nul character.
1556 fun cstring_length
: Int
1559 while self[l
] != '\0' do l
+= 1
1562 fun atoi
: Int is intern
1563 fun atof
: Float is extern "atof"
1567 return to_s_with_length
(cstring_length
)
1570 fun to_s_with_length
(length
: Int): FlatString
1573 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1576 fun to_s_with_copy
: FlatString
1578 var length
= cstring_length
1579 var new_self
= calloc_string
(length
+ 1)
1580 copy_to
(new_self
, length
, 0, 0)
1581 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1586 # StringCapable objects can create native strings
1587 interface StringCapable
1588 protected fun calloc_string
(size
: Int): NativeString is intern
1592 var _args_cache
: nullable Sequence[String]
1594 redef fun args
: Sequence[String]
1596 if _args_cache
== null then init_args
1597 return _args_cache
.as(not null)
1600 # The name of the program as given by the OS
1601 fun program_name
: String
1603 return native_argv
(0).to_s
1606 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1607 private fun init_args
1609 var argc
= native_argc
1610 var args
= new Array[String].with_capacity
(0)
1613 args
[i-1
] = native_argv
(i
).to_s
1619 # First argument of the main C function.
1620 private fun native_argc
: Int is intern
1622 # Second argument of the main C function.
1623 private fun native_argv
(i
: Int): NativeString is intern