29a25ff4fc911053b67b71a3c75094f3888e4278
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 var hash_cache
: nullable Int = null
43 # Gets a view on the chars of the Text object
44 fun chars
: SELFVIEW is abstract
46 # Number of characters contained in self.
47 fun length
: Int is abstract
51 # assert "abcd".substring(1, 2) == "bc"
52 # assert "abcd".substring(-1, 2) == "a"
53 # assert "abcd".substring(1, 0) == ""
54 # assert "abcd".substring(2, 5) == "cd"
56 # A `from` index < 0 will be replaced by 0.
57 # Unless a `count` value is > 0 at the same time.
58 # In this case, `from += count` and `count -= from`.
59 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
61 # Concatenates `o` to `self`
62 fun +(o
: Text): SELFTYPE is abstract
64 # Auto-concatenates self `i` times
65 fun *(i
: Int): SELFTYPE is abstract
67 # Is the current Text empty (== "")
69 # assert not "foo".is_empty
70 fun is_empty
: Bool do return self.length
== 0
72 # Returns an empty Text of the right type
73 fun empty
: SELFTYPE is abstract
75 # Gets the first char of the Text
77 # DEPRECATED : Use self.chars.first instead
78 fun first
: Char do return self.chars
[0]
80 # Access a character at `index` in the string.
82 # assert "abcd"[2] == 'c'
84 # DEPRECATED : Use self.chars.[] instead
85 fun [](index
: Int): Char do return self.chars
[index
]
87 # Gets the index of the first occurence of 'c'
89 # Returns -1 if not found
91 # DEPRECATED : Use self.chars.index_of instead
92 fun index_of
(c
: Char): Int
94 return index_of_from
(c
, 0)
97 # Gets the last char of self
99 # DEPRECATED : Use self.chars.last instead
100 fun last
: Char do return self.chars
[length-1
]
102 # Gets the index of the first occurence of ´c´ starting from ´pos´
104 # Returns -1 if not found
106 # DEPRECATED : Use self.chars.index_of_from instead
107 fun index_of_from
(c
: Char, pos
: Int): Int
109 var iter
= self.chars
.iterator_from
(pos
)
111 if iter
.item
== c
then return iter
.index
116 # Gets the last index of char ´c´
118 # Returns -1 if not found
120 # DEPRECATED : Use self.chars.last_index_of instead
121 fun last_index_of
(c
: Char): Int
123 return last_index_of_from
(c
, length
- 1)
126 # Return a null terminated char *
127 fun to_cstring
: NativeString do return flatten
.to_cstring
129 # The index of the last occurrence of an element starting from pos (in reverse order).
131 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
132 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
134 # Returns -1 if not found
136 # DEPRECATED : Use self.chars.last_index_of_from instead
137 fun last_index_of_from
(item
: Char, pos
: Int): Int
139 var iter
= self.chars
.reverse_iterator_from
(pos
)
141 if iter
.item
== item
then return iter
.index
147 # Gets an iterator on the chars of self
149 # DEPRECATED : Use self.chars.iterator instead
150 fun iterator
: Iterator[Char]
152 return self.chars
.iterator
155 # Is 'c' contained in self ?
157 # DEPRECATED : Use self.chars.has instead
158 fun has
(c
: Char): Bool
160 return self.chars
.has
(c
)
163 # Gets an Array containing the chars of self
165 # DEPRECATED : Use self.chars.to_a instead
166 fun to_a
: Array[Char] do return chars
.to_a
168 # Create a substring from `self` beginning at the `from` position
170 # assert "abcd".substring_from(1) == "bcd"
171 # assert "abcd".substring_from(-1) == "abcd"
172 # assert "abcd".substring_from(2) == "cd"
174 # As with substring, a `from` index < 0 will be replaced by 0
175 fun substring_from
(from
: Int): SELFTYPE
177 if from
> self.length
then return empty
178 if from
< 0 then from
= 0
179 return substring
(from
, length
- from
)
182 # Returns a reversed version of self
183 fun reversed
: SELFTYPE is abstract
185 # Does self have a substring `str` starting from position `pos`?
187 # assert "abcd".has_substring("bc",1) == true
188 # assert "abcd".has_substring("bc",2) == false
189 fun has_substring
(str
: String, pos
: Int): Bool
191 var myiter
= self.chars
.iterator_from
(pos
)
192 var itsiter
= str
.iterator
193 while myiter
.is_ok
and itsiter
.is_ok
do
194 if myiter
.item
!= itsiter
.item
then return false
198 if itsiter
.is_ok
then return false
202 # Is this string prefixed by `prefix`?
204 # assert "abcd".has_prefix("ab") == true
205 # assert "abcbc".has_prefix("bc") == false
206 # assert "ab".has_prefix("abcd") == false
207 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
209 # Is this string suffixed by `suffix`?
211 # assert "abcd".has_suffix("abc") == false
212 # assert "abcd".has_suffix("bcd") == true
213 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
215 # If `self` contains only digits, return the corresponding integer
217 # assert "123".to_i == 123
218 # assert "-1".to_i == -1
222 return to_s
.to_cstring
.atoi
225 # If `self` contains a float, return the corresponding float
227 # assert "123".to_f == 123.0
228 # assert "-1".to_f == -1.0
229 # assert "-1.2e-3".to_f == -0.0012
233 return to_s
.to_cstring
.atof
236 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
237 fun to_hex
: Int do return a_to
(16)
239 # If `self` contains only digits and letters, return the corresponding integer in a given base
241 # assert "120".a_to(3) == 15
242 fun a_to
(base
: Int) : Int
269 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
271 # assert "123".is_numeric == true
272 # assert "1.2".is_numeric == true
273 # assert "1,2".is_numeric == true
274 # assert "1..2".is_numeric == false
277 var has_point_or_comma
= false
282 if (i
== '.' or i
== ',') and not has_point_or_comma
284 has_point_or_comma
= true
293 # A upper case version of `self`
295 # assert "Hello World!".to_upper == "HELLO WORLD!"
296 fun to_upper
: SELFTYPE is abstract
298 # A lower case version of `self`
300 # assert "Hello World!".to_lower == "hello world!"
301 fun to_lower
: SELFTYPE is abstract
303 # Removes the whitespaces at the beginning of self
306 var iter
= self.chars
.iterator
308 if iter
.item
.ascii
> 32 then break
311 if iter
.index
== length
then return self.empty
312 return self.substring_from
(iter
.index
)
315 # Removes the whitespaces at the end of self
318 var iter
= self.chars
.reverse_iterator
320 if iter
.item
.ascii
> 32 then break
323 if iter
.index
== length
then return self.empty
324 return self.substring
(0, iter
.index
+ 1)
327 # Trims trailing and preceding white spaces
328 # A whitespace is defined as any character which ascii value is less than or equal to 32
330 # assert " Hello World ! ".trim == "Hello World !"
331 # assert "\na\nb\tc\t".trim == "a\nb\tc"
332 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
334 # Mangle a string to be a unique string only made of alphanumeric characters
335 fun to_cmangle
: String
337 var res
= new FlatBuffer
338 var underscore
= false
339 for c
in self.chars
do
340 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
346 res
.append
('_'.ascii
.to_s
)
349 if c
>= '0' and c
<= '9' then
352 else if c
== '_' then
357 res
.append
(c
.ascii
.to_s
)
365 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
367 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
368 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
369 fun escape_to_c
: String
371 var b
= new FlatBuffer
372 for c
in self.chars
do
375 else if c
== '\0' then
377 else if c
== '"' then
379 else if c == '\'' then
381 else if c == '\\
' then
383 else if c.ascii < 32 then
384 b.append("\\{c.ascii.to_base(8, false)}")
392 # Escape additionnal characters
393 # The result might no be legal in C but be used in other languages
395 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
396 fun escape_more_to_c(chars: String): String
398 var b = new FlatBuffer
399 for c in escape_to_c do
400 if chars.chars.has(c) then
408 # Escape to c plus braces
410 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
411 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
413 # Return a string where Nit escape sequences are transformed.
417 # assert s.length == 2
418 # var u = s.unescape_nit
419 # assert u.length == 1
420 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
421 fun unescape_nit
: String
423 var res
= new FlatBuffer.with_capacity
(self.length
)
424 var was_slash
= false
426 if not was_slash
then
437 else if c
== 'r' then
439 else if c
== 't' then
441 else if c
== '0' then
452 if o
== null then return false
453 if not o
isa Text then return false
454 if self.is_same_instance
(o
) then return true
455 if self.length
!= o
.length
then return false
456 return self.chars
== o
.chars
461 return self.chars
< o
.chars
464 # Flat representation of self
465 fun flatten
: FlatText is abstract
469 if hash_cache
== null then
470 # djb2 hash algorithm
474 for char
in self.chars
do
475 h
= (h
* 32) + h
+ char
.ascii
481 return hash_cache
.as(not null)
486 # All kinds of array-based text representations.
487 abstract class FlatText
490 private var items
: NativeString
492 # Real items, used as cache for to_cstring is called
493 private var real_items
: nullable NativeString = null
495 redef var length
: Int
508 redef fun flatten
do return self
511 # Abstract class for the SequenceRead compatible
512 # views on String and Buffer objects
513 abstract class StringCharView
514 super SequenceRead[Char]
519 redef type OTHER: StringCharView
521 private var target
: SELFTYPE
523 private init(tgt
: SELFTYPE)
528 redef fun is_empty
do return target
.is_empty
530 redef fun length
do return target
.length
532 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
534 # Gets a new Iterator starting at position `pos`
537 # var iter = "abcd".iterator_from(2)
538 # while iter.is_ok do
544 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
546 # Gets an iterator starting at the end and going backwards
549 # var reviter = "now step live...".reverse_iterator
550 # while reviter.is_ok do
551 # printn reviter.item
555 # Outputs : ...evil pets won
556 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
558 # Gets an iterator on the chars of self starting from `pos`
561 # var iter = "abcd".reverse_iterator_from(1)
562 # while iter.is_ok do
568 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
570 redef fun has
(c
: Char): Bool
573 if i
== c
then return true
580 if other
== null then return false
581 if not other
isa StringCharView then return false
582 var other_chars
= other
.iterator
584 if i
!= other_chars
.item
then return false
592 var self_chars
= self.iterator
593 var other_chars
= other
.iterator
595 while self_chars
.is_ok
and other_chars
.is_ok
do
596 if self_chars
.item
< other_chars
.item
then return true
597 if self_chars
.item
> other_chars
.item
then return false
602 if self_chars
.is_ok
then
610 # View on Buffer objects, extends Sequence
611 # for mutation operations
612 abstract class BufferCharView
616 redef type SELFTYPE: Buffer
620 abstract class String
623 redef type SELFTYPE: String
625 redef fun to_s
do return self
629 # Immutable strings of characters.
634 redef type SELFTYPE: FlatString
636 # Index in _items of the start of the string
637 private var index_from
: Int
639 # Indes in _items of the last item of the string
640 private var index_to
: Int
642 redef var chars
: SELFVIEW = new FlatStringCharView(self)
644 ################################################
645 # AbstractString specific methods #
646 ################################################
648 redef fun [](index
) do
650 # Check that the index (+ index_from) is not larger than indexTo
651 # In other terms, if the index is valid
652 assert (index
+ index_from
) <= index_to
653 return items
[index
+ index_from
]
658 var native
= calloc_string
(self.length
+ 1)
659 var reviter
= chars
.reverse_iterator
661 while reviter
.is_ok
do
662 native
[pos
] = reviter
.item
666 return native
.to_s_with_length
(self.length
)
669 redef fun substring
(from
, count
)
675 if count
< 0 then count
= 0
679 var realFrom
= index_from
+ from
681 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
683 if count
== 0 then return empty
685 var to
= realFrom
+ count
- 1
687 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
690 redef fun empty
do return "".as(FlatString)
694 var outstr
= calloc_string
(self.length
+ 1)
697 var myitems
= self.items
698 var index_from
= self.index_from
699 var max
= self.index_to
701 while index_from
<= max
do
702 outstr
[out_index
] = myitems
[index_from
].to_upper
707 outstr
[self.length
] = '\0'
709 return outstr
.to_s_with_length
(self.length
)
714 var outstr
= calloc_string
(self.length
+ 1)
717 var myitems
= self.items
718 var index_from
= self.index_from
719 var max
= self.index_to
721 while index_from
<= max
do
722 outstr
[out_index
] = myitems
[index_from
].to_lower
727 outstr
[self.length
] = '\0'
729 return outstr
.to_s_with_length
(self.length
)
734 var i
= self.index_from
735 var imax
= self.index_to
742 ##################################################
743 # String Specific Methods #
744 ##################################################
746 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
754 # Return a null terminated char *
755 redef fun to_cstring
: NativeString
757 if real_items
!= null then return real_items
.as(not null)
758 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
759 var newItems
= calloc_string
(length
+ 1)
760 self.items
.copy_to
(newItems
, length
, index_from
, 0)
761 newItems
[length
] = '\0'
762 self.real_items
= newItems
770 if not other
isa FlatString then return super
772 if self.object_id
== other
.object_id
then return true
774 var my_length
= length
776 if other
.length
!= my_length
then return false
778 var my_index
= index_from
779 var its_index
= other
.index_from
781 var last_iteration
= my_index
+ my_length
783 var itsitems
= other
.items
784 var myitems
= self.items
786 while my_index
< last_iteration
do
787 if myitems
[my_index
] != itsitems
[its_index
] then return false
795 # The comparison between two strings is done on a lexicographical basis
797 # assert ("aa" < "b") == true
800 if not other
isa FlatString then return super
802 if self.object_id
== other
.object_id
then return false
804 var my_curr_char
: Char
805 var its_curr_char
: Char
807 var curr_id_self
= self.index_from
808 var curr_id_other
= other
.index_from
810 var my_items
= self.items
811 var its_items
= other
.items
813 var my_length
= self.length
814 var its_length
= other
.length
816 var max_iterations
= curr_id_self
+ my_length
818 while curr_id_self
< max_iterations
do
819 my_curr_char
= my_items
[curr_id_self
]
820 its_curr_char
= its_items
[curr_id_other
]
822 if my_curr_char
!= its_curr_char
then
823 if my_curr_char
< its_curr_char
then return true
831 return my_length
< its_length
834 # The concatenation of `self` with `s`
836 # assert "hello " + "world!" == "hello world!"
839 var my_length
= self.length
840 var its_length
= s
.length
842 var total_length
= my_length
+ its_length
844 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
846 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
847 if s
isa FlatString then
848 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
849 else if s
isa FlatBuffer then
850 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
852 var curr_pos
= my_length
854 target_string
[curr_pos
] = i
859 target_string
[total_length
] = '\0'
861 return target_string
.to_s_with_length
(total_length
)
864 # assert "abc"*3 == "abcabcabc"
865 # assert "abc"*1 == "abc"
866 # assert "abc"*0 == ""
871 var my_length
= self.length
873 var final_length
= my_length
* i
875 var my_items
= self.items
877 var target_string
= calloc_string
((final_length
) + 1)
879 target_string
[final_length
] = '\0'
883 for iteration
in [1 .. i
] do
884 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
885 current_last
+= my_length
888 return target_string
.to_s_with_length
(final_length
)
893 if hash_cache
== null then
894 # djb2 hash algorythm
899 var strStart
= index_from
903 while i
>= strStart
do
904 h
= (h
* 32) + h
+ self.items
[i
].ascii
911 return hash_cache
.as(not null)
915 private class FlatStringReverseIterator
916 super IndexedIterator[Char]
918 var target
: FlatString
920 var target_items
: NativeString
924 init with_pos
(tgt
: FlatString, pos
: Int)
927 target_items
= tgt
.items
928 curr_pos
= pos
+ tgt
.index_from
931 redef fun is_ok
do return curr_pos
>= 0
933 redef fun item
do return target_items
[curr_pos
]
935 redef fun next
do curr_pos
-= 1
937 redef fun index
do return curr_pos
- target
.index_from
941 private class FlatStringIterator
942 super IndexedIterator[Char]
944 var target
: FlatString
946 var target_items
: NativeString
950 init with_pos
(tgt
: FlatString, pos
: Int)
953 target_items
= tgt
.items
954 curr_pos
= pos
+ target
.index_from
957 redef fun is_ok
do return curr_pos
<= target
.index_to
959 redef fun item
do return target_items
[curr_pos
]
961 redef fun next
do curr_pos
+= 1
963 redef fun index
do return curr_pos
- target
.index_from
967 private class FlatStringCharView
970 redef type SELFTYPE: FlatString
974 # Check that the index (+ index_from) is not larger than indexTo
975 # In other terms, if the index is valid
977 assert (index
+ target
.index_from
) <= target
.index_to
978 return target
.items
[index
+ target
.index_from
]
981 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
983 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
987 abstract class Buffer
990 redef type SELFVIEW: BufferCharView
991 redef type SELFTYPE: Buffer
995 # Modifies the char contained at pos `index`
997 # DEPRECATED : Use self.chars.[]= instead
998 fun []=(index
: Int, item
: Char) is abstract
1000 # Adds a char `c` at the end of self
1002 # DEPRECATED : Use self.chars.add instead
1003 fun add
(c
: Char) is abstract
1006 fun clear
is abstract
1008 # Enlarges the subsequent array containing the chars of self
1009 fun enlarge
(cap
: Int) is abstract
1011 # Adds the content of text `s` at the end of self
1012 fun append
(s
: Text) is abstract
1016 if is_dirty
then hash_cache
= null
1022 # Mutable strings of characters.
1027 redef type SELFTYPE: FlatBuffer
1029 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
1033 redef fun []=(index
, item
)
1036 if index
== length
then
1040 assert index
>= 0 and index
< length
1047 if capacity
<= length
then enlarge
(length
+ 5)
1057 redef fun empty
do return new FlatBuffer
1059 redef fun enlarge
(cap
)
1063 if cap
<= c
then return
1064 while c
<= cap
do c
= c
* 2 + 2
1065 var a
= calloc_string
(c
+1)
1066 items
.copy_to
(a
, length
, 0, 0)
1069 items
.copy_to
(a
, length
, 0, 0)
1072 redef fun to_s
: String
1074 return to_cstring
.to_s_with_length
(length
)
1077 redef fun to_cstring
1080 var new_native
= calloc_string
(length
+ 1)
1081 new_native
[length
] = '\0'
1082 items
.copy_to
(new_native
, length
, 0, 0)
1083 real_items
= new_native
1086 return real_items
.as(not null)
1089 # Create a new empty string.
1090 init do with_capacity
(5)
1094 capacity
= s
.length
+ 1
1096 items
= calloc_string
(capacity
)
1097 if s
isa FlatString then
1098 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1099 else if s
isa FlatBuffer then
1100 s
.items
.copy_to
(items
, length
, 0, 0)
1110 # Create a new empty string with a given capacity.
1111 init with_capacity
(cap
: Int)
1114 # _items = new NativeString.calloc(cap)
1115 items
= calloc_string
(cap
+1)
1124 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1125 if s
isa FlatString then
1126 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1127 else if s
isa FlatBuffer then
1128 s
.items
.copy_to
(items
, sl
, 0, length
)
1130 var curr_pos
= self.length
1139 # Copies the content of self in `dest`
1140 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1142 var self_chars
= self.chars
1143 var dest_chars
= dest
.chars
1144 for i
in [0..len-1
] do
1145 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1149 redef fun substring
(from
, count
)
1153 if from
< 0 then from
= 0
1154 if count
> length
then count
= length
1155 if from
< count
then
1156 var r
= new FlatBuffer.with_capacity
(count
- from
)
1157 while from
< count
do
1158 r
.chars
.push
(items
[from
])
1163 return new FlatBuffer
1169 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1170 var reviter
= self.chars
.reverse_iterator
1171 while reviter
.is_ok
do
1172 new_buf
.add
(reviter
.item
)
1180 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1181 new_buf
.append
(self)
1182 new_buf
.append
(other
)
1186 redef fun *(repeats
)
1188 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1189 for i
in [0..repeats
[ do
1190 new_buf
.append
(self)
1196 private class FlatBufferReverseIterator
1197 super IndexedIterator[Char]
1199 var target
: FlatBuffer
1201 var target_items
: NativeString
1205 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1208 target_items
= tgt
.items
1212 redef fun index
do return curr_pos
1214 redef fun is_ok
do return curr_pos
>= 0
1216 redef fun item
do return target_items
[curr_pos
]
1218 redef fun next
do curr_pos
-= 1
1222 private class FlatBufferCharView
1223 super BufferCharView
1226 redef type SELFTYPE: FlatBuffer
1228 redef fun [](index
) do return target
.items
[index
]
1230 redef fun []=(index
, item
)
1232 assert index
>= 0 and index
<= length
1233 if index
== length
then
1237 target
.items
[index
] = item
1250 fun enlarge
(cap
: Int)
1257 var my_items
= target
.items
1258 var s_length
= s
.length
1259 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1262 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1264 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1268 private class FlatBufferIterator
1269 super IndexedIterator[Char]
1271 var target
: FlatBuffer
1273 var target_items
: NativeString
1277 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1280 target_items
= tgt
.items
1284 redef fun index
do return curr_pos
1286 redef fun is_ok
do return curr_pos
< target
.length
1288 redef fun item
do return target_items
[curr_pos
]
1290 redef fun next
do curr_pos
+= 1
1294 ###############################################################################
1296 ###############################################################################
1299 # User readable representation of `self`.
1300 fun to_s
: String do return inspect
1302 # The class name of the object in NativeString format.
1303 private fun native_class_name
: NativeString is intern
1305 # The class name of the object.
1307 # assert 5.class_name == "Int"
1308 fun class_name
: String do return native_class_name
.to_s
1310 # Developer readable representation of `self`.
1311 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1314 return "<{inspect_head}>"
1317 # Return "CLASSNAME:#OBJECTID".
1318 # This function is mainly used with the redefinition of the inspect method
1319 protected fun inspect_head
: String
1321 return "{class_name}:#{object_id.to_hex}"
1324 protected fun args
: Sequence[String]
1331 # assert true.to_s == "true"
1332 # assert false.to_s == "false"
1344 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1345 # assume < to_c max const of char
1346 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1353 else if self == 0 then
1360 var pos
= digit_count
(base
) - 1
1361 while pos
>= 0 and n
> 0 do
1362 s
.chars
[pos
] = (n
% base
).to_c
1368 # C function to convert an nit Int to a NativeString (char*)
1369 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1371 # return displayable int in base 10 and signed
1373 # assert 1.to_s == "1"
1374 # assert (-123).to_s == "-123"
1376 var len
= digit_count
(10)
1377 return native_int_to_s
(len
).to_s_with_length
(len
)
1380 # return displayable int in hexadecimal (unsigned (not now))
1381 fun to_hex
: String do return to_base
(16,false)
1383 # return displayable int in base base and signed
1384 fun to_base
(base
: Int, signed
: Bool): String
1386 var l
= digit_count
(base
)
1387 var s
= new FlatBuffer.from
(" " * l
)
1388 fill_buffer
(s
, base
, signed
)
1394 # Pretty print self, print needoed decimals up to a max of 3.
1396 var str
= to_precision
( 3 )
1397 if is_inf
!= 0 or is_nan
then return str
1398 var len
= str
.length
1399 for i
in [0..len-1
] do
1401 var c
= str
.chars
[j
]
1404 else if c
== '.' then
1405 return str
.substring
( 0, j
+2 )
1407 return str
.substring
( 0, j
+1 )
1413 # `self` representation with `nb` digits after the '.'.
1414 fun to_precision
(nb
: Int): String
1416 if is_nan
then return "nan"
1418 var isinf
= self.is_inf
1421 else if isinf
== -1 then
1425 if nb
== 0 then return self.to_i
.to_s
1427 for i
in [0..nb
[ do f
= f
* 10.0
1434 if i
== 0 then return "0.0"
1438 var p1
= s
.substring
(0, s
.length-nb
)
1439 var p2
= s
.substring
(s
.length-nb
, nb
)
1440 return p1
+ "." + p2
1442 return "0." + ("0"*(nb-sl
)) + s
1446 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1450 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1451 str = malloc(size + 1);
1452 sprintf(str, "%.*f", (int)nb, recv );
1454 return NativeString_to_s( str );
1459 # assert 'x'.to_s == "x"
1462 var s
= new FlatBuffer.with_capacity
(1)
1467 # Returns true if the char is a numerical digit
1468 fun is_numeric
: Bool
1470 if self >= '0' and self <= '9'
1477 # Returns true if the char is an alpha digit
1480 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1484 # Returns true if the char is an alpha or a numeric digit
1485 fun is_alphanumeric
: Bool
1487 if self.is_numeric
or self.is_alpha
then return true
1492 redef class Collection[E
]
1493 # Concatenate elements.
1496 var s
= new FlatBuffer
1497 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1501 # Concatenate and separate each elements with `sep`.
1503 # assert [1, 2, 3].join(":") == "1:2:3"
1504 # assert [1..3].join(":") == "1:2:3"
1505 fun join
(sep
: String): String
1507 if is_empty
then return ""
1509 var s
= new FlatBuffer # Result
1514 if e
!= null then s
.append
(e
.to_s
)
1516 # Concat other items
1521 if e
!= null then s
.append
(e
.to_s
)
1528 redef class Array[E
]
1529 # Fast implementation
1532 var s
= new FlatBuffer
1537 if e
!= null then s
.append
(e
.to_s
)
1544 redef class Map[K
,V
]
1545 # Concatenate couple of 'key value'.
1546 # key and value are separated by `couple_sep`.
1547 # each couple is separated each couple with `sep`.
1549 # var m = new ArrayMap[Int, String]
1552 # assert m.join("; ", "=") == "1=one; 10=ten"
1553 fun join
(sep
: String, couple_sep
: String): String
1555 if is_empty
then return ""
1557 var s
= new FlatBuffer # Result
1563 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1565 # Concat other items
1571 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1578 ###############################################################################
1580 ###############################################################################
1582 # Native strings are simple C char *
1586 fun [](index
: Int): Char is intern
1587 fun []=(index
: Int, item
: Char) is intern
1588 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1590 # Position of the first nul character.
1591 fun cstring_length
: Int
1594 while self[l
] != '\0' do l
+= 1
1597 fun atoi
: Int is intern
1598 fun atof
: Float is extern "atof"
1602 return to_s_with_length
(cstring_length
)
1605 fun to_s_with_length
(length
: Int): FlatString
1608 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1611 fun to_s_with_copy
: FlatString
1613 var length
= cstring_length
1614 var new_self
= calloc_string
(length
+ 1)
1615 copy_to
(new_self
, length
, 0, 0)
1616 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1621 # StringCapable objects can create native strings
1622 interface StringCapable
1623 protected fun calloc_string
(size
: Int): NativeString is intern
1627 var _args_cache
: nullable Sequence[String]
1629 redef fun args
: Sequence[String]
1631 if _args_cache
== null then init_args
1632 return _args_cache
.as(not null)
1635 # The name of the program as given by the OS
1636 fun program_name
: String
1638 return native_argv
(0).to_s
1641 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1642 private fun init_args
1644 var argc
= native_argc
1645 var args
= new Array[String].with_capacity
(0)
1648 args
[i-1
] = native_argv
(i
).to_s
1654 # First argument of the main C function.
1655 private fun native_argc
: Int is intern
1657 # Second argument of the main C function.
1658 private fun native_argv
(i
: Int): NativeString is intern
1661 # Comparator that efficienlty use `to_s` to compare things
1663 # The comparaison call `to_s` on object and use the result to order things.
1665 # var a = [1, 2, 3, 10, 20]
1666 # (new CachedAlphaComparator).sort(a)
1667 # assert a == [1, 10, 2, 20, 3]
1669 # Internally the result of `to_s` is cached in a HashMap to counter
1670 # uneficient implementation of `to_s`.
1672 # Note: it caching is not usefull, see `alpha_comparator`
1673 class CachedAlphaComparator
1674 super Comparator[Object]
1676 private var cache
= new HashMap[Object, String]
1678 private fun do_to_s
(a
: Object): String do
1679 if cache
.has_key
(a
) then return cache
[a
]
1685 redef fun compare
(a
, b
) do
1686 return do_to_s
(a
) <=> do_to_s
(b
)
1690 # see `alpha_comparator`
1691 private class AlphaComparator
1692 super Comparator[Object]
1693 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1696 # Stateless comparator that naively use `to_s` to compare things.
1698 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1699 # on a single instace. See `CachedAlphaComparator` as an alternative.
1701 # var a = [1, 2, 3, 10, 20]
1702 # alpha_comparator.sort(a)
1703 # assert a == [1, 10, 2, 20, 3]
1704 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator