ecf7cf1f544ef6de39a7f6ea8b0f315f8f219ee9
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 # Real items, used as cache for to_cstring is called
474 private var real_items
: nullable NativeString = null
476 redef var length
: Int
489 redef fun flatten
do return self
492 # Abstract class for the SequenceRead compatible
493 # views on String and Buffer objects
494 abstract class StringCharView
495 super SequenceRead[Char]
500 redef type OTHER: StringCharView
502 private var target
: SELFTYPE
504 private init(tgt
: SELFTYPE)
509 redef fun is_empty
do return target
.is_empty
511 redef fun length
do return target
.length
513 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
515 # Gets a new Iterator starting at position `pos`
518 # var iter = "abcd".iterator_from(2)
519 # while iter.is_ok do
525 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
527 # Gets an iterator starting at the end and going backwards
530 # var reviter = "now step live...".reverse_iterator
531 # while reviter.is_ok do
532 # printn reviter.item
536 # Outputs : ...evil pets won
537 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
539 # Gets an iterator on the chars of self starting from `pos`
542 # var iter = "abcd".reverse_iterator_from(1)
543 # while iter.is_ok do
549 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
551 redef fun has
(c
: Char): Bool
554 if i
== c
then return true
561 if other
== null then return false
562 if not other
isa StringCharView then return false
563 var other_chars
= other
.iterator
565 if i
!= other_chars
.item
then return false
573 var self_chars
= self.iterator
574 var other_chars
= other
.iterator
576 while self_chars
.is_ok
and other_chars
.is_ok
do
577 if self_chars
.item
< other_chars
.item
then return true
578 if self_chars
.item
> other_chars
.item
then return false
583 if self_chars
.is_ok
then
591 # View on Buffer objects, extends Sequence
592 # for mutation operations
593 abstract class BufferCharView
597 redef type SELFTYPE: Buffer
601 abstract class String
604 redef type SELFTYPE: String
606 redef fun to_s
do return self
610 # Immutable strings of characters.
615 redef type SELFTYPE: FlatString
616 redef type SELFVIEW: FlatStringCharView
618 # Index in _items of the start of the string
619 private var index_from
: Int
621 # Indes in _items of the last item of the string
622 private var index_to
: Int
624 redef var chars
: SELFVIEW = new FlatStringCharView(self)
626 ################################################
627 # AbstractString specific methods #
628 ################################################
630 redef fun [](index
) do
632 # Check that the index (+ index_from) is not larger than indexTo
633 # In other terms, if the index is valid
634 assert (index
+ index_from
) <= index_to
635 return items
[index
+ index_from
]
640 var native
= calloc_string
(self.length
+ 1)
641 var reviter
= chars
.reverse_iterator
643 while reviter
.is_ok
do
644 native
[pos
] = reviter
.item
648 return native
.to_s_with_length
(self.length
)
651 redef fun substring
(from
, count
)
657 if count
< 0 then count
= 0
661 var realFrom
= index_from
+ from
663 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
665 if count
== 0 then return empty
667 var to
= realFrom
+ count
- 1
669 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
672 redef fun empty
do return "".as(FlatString)
676 var outstr
= calloc_string
(self.length
+ 1)
679 var myitems
= self.items
680 var index_from
= self.index_from
681 var max
= self.index_to
683 while index_from
<= max
do
684 outstr
[out_index
] = myitems
[index_from
].to_upper
689 outstr
[self.length
] = '\0'
691 return outstr
.to_s_with_length
(self.length
)
696 var outstr
= calloc_string
(self.length
+ 1)
699 var myitems
= self.items
700 var index_from
= self.index_from
701 var max
= self.index_to
703 while index_from
<= max
do
704 outstr
[out_index
] = myitems
[index_from
].to_lower
709 outstr
[self.length
] = '\0'
711 return outstr
.to_s_with_length
(self.length
)
716 var i
= self.index_from
717 var imax
= self.index_to
724 ##################################################
725 # String Specific Methods #
726 ##################################################
728 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
736 # Return a null terminated char *
737 redef fun to_cstring
: NativeString
739 if real_items
!= null then return real_items
.as(not null)
740 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
741 var newItems
= calloc_string
(length
+ 1)
742 self.items
.copy_to
(newItems
, length
, index_from
, 0)
743 newItems
[length
] = '\0'
744 self.real_items
= newItems
752 if not other
isa FlatString then return super
754 if self.object_id
== other
.object_id
then return true
756 var my_length
= length
758 if other
.length
!= my_length
then return false
760 var my_index
= index_from
761 var its_index
= other
.index_from
763 var last_iteration
= my_index
+ my_length
765 var itsitems
= other
.items
766 var myitems
= self.items
768 while my_index
< last_iteration
do
769 if myitems
[my_index
] != itsitems
[its_index
] then return false
777 # The comparison between two strings is done on a lexicographical basis
779 # assert ("aa" < "b") == true
782 if not other
isa FlatString then return super
784 if self.object_id
== other
.object_id
then return false
786 var my_curr_char
: Char
787 var its_curr_char
: Char
789 var curr_id_self
= self.index_from
790 var curr_id_other
= other
.index_from
792 var my_items
= self.items
793 var its_items
= other
.items
795 var my_length
= self.length
796 var its_length
= other
.length
798 var max_iterations
= curr_id_self
+ my_length
800 while curr_id_self
< max_iterations
do
801 my_curr_char
= my_items
[curr_id_self
]
802 its_curr_char
= its_items
[curr_id_other
]
804 if my_curr_char
!= its_curr_char
then
805 if my_curr_char
< its_curr_char
then return true
813 return my_length
< its_length
816 # The concatenation of `self` with `s`
818 # assert "hello " + "world!" == "hello world!"
821 var my_length
= self.length
822 var its_length
= s
.length
824 var total_length
= my_length
+ its_length
826 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
828 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
829 if s
isa FlatString then
830 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
831 else if s
isa FlatBuffer then
832 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
834 var curr_pos
= my_length
836 target_string
[curr_pos
] = i
841 target_string
[total_length
] = '\0'
843 return target_string
.to_s_with_length
(total_length
)
846 # assert "abc"*3 == "abcabcabc"
847 # assert "abc"*1 == "abc"
848 # assert "abc"*0 == ""
853 var my_length
= self.length
855 var final_length
= my_length
* i
857 var my_items
= self.items
859 var target_string
= calloc_string
((final_length
) + 1)
861 target_string
[final_length
] = '\0'
865 for iteration
in [1 .. i
] do
866 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
867 current_last
+= my_length
870 return target_string
.to_s_with_length
(final_length
)
875 # djb2 hash algorythm
880 var strStart
= index_from
884 while i
>= strStart
do
885 h
= (h
* 32) + h
+ self.items
[i
].ascii
893 private class FlatStringReverseIterator
894 super IndexedIterator[Char]
896 var target
: FlatString
898 var target_items
: NativeString
902 init with_pos
(tgt
: FlatString, pos
: Int)
905 target_items
= tgt
.items
906 curr_pos
= pos
+ tgt
.index_from
909 redef fun is_ok
do return curr_pos
>= 0
911 redef fun item
do return target_items
[curr_pos
]
913 redef fun next
do curr_pos
-= 1
915 redef fun index
do return curr_pos
- target
.index_from
919 private class FlatStringIterator
920 super IndexedIterator[Char]
922 var target
: FlatString
924 var target_items
: NativeString
928 init with_pos
(tgt
: FlatString, pos
: Int)
931 target_items
= tgt
.items
932 curr_pos
= pos
+ target
.index_from
935 redef fun is_ok
do return curr_pos
<= target
.index_to
937 redef fun item
do return target_items
[curr_pos
]
939 redef fun next
do curr_pos
+= 1
941 redef fun index
do return curr_pos
- target
.index_from
945 private class FlatStringCharView
948 redef type SELFTYPE: FlatString
952 # Check that the index (+ index_from) is not larger than indexTo
953 # In other terms, if the index is valid
955 assert (index
+ target
.index_from
) <= target
.index_to
956 return target
.items
[index
+ target
.index_from
]
959 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
961 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
965 abstract class Buffer
968 redef type SELFVIEW: BufferCharView
969 redef type SELFTYPE: Buffer
971 # Modifies the char contained at pos `index`
973 # DEPRECATED : Use self.chars.[]= instead
974 fun []=(index
: Int, item
: Char) is abstract
976 # Adds a char `c` at the end of self
978 # DEPRECATED : Use self.chars.add instead
979 fun add
(c
: Char) is abstract
982 fun clear
is abstract
984 # Enlarges the subsequent array containing the chars of self
985 fun enlarge
(cap
: Int) is abstract
987 # Adds the content of text `s` at the end of self
988 fun append
(s
: Text) is abstract
992 # Mutable strings of characters.
997 redef type SELFVIEW: FlatBufferCharView
998 redef type SELFTYPE: FlatBuffer
1000 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
1004 redef fun []=(index
, item
)
1006 if index
== length
then
1010 assert index
>= 0 and index
< length
1016 if capacity
<= length
then enlarge
(length
+ 5)
1021 redef fun clear
do length
= 0
1023 redef fun empty
do return new FlatBuffer
1025 redef fun enlarge
(cap
)
1028 if cap
<= c
then return
1029 while c
<= cap
do c
= c
* 2 + 2
1030 var a
= calloc_string
(c
+1)
1031 items
.copy_to
(a
, length
, 0, 0)
1034 items
.copy_to
(a
, length
, 0, 0)
1037 redef fun to_s
: String
1040 var a
= calloc_string
(l
+1)
1041 items
.copy_to
(a
, l
, 0, 0)
1043 # Ensure the afterlast byte is '\0' to nul-terminated char *
1046 return a
.to_s_with_length
(length
)
1049 redef fun to_cstring
1051 if real_items
== null then
1052 var new_native
= calloc_string
(length
+ 1)
1053 new_native
[length
] = '\0'
1054 items
.copy_to
(new_native
, length
, 0, 0)
1055 real_items
= new_native
1057 return real_items
.as(not null)
1060 # Create a new empty string.
1068 capacity
= s
.length
+ 1
1070 items
= calloc_string
(capacity
)
1071 if s
isa FlatString then
1072 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1073 else if s
isa FlatBuffer then
1074 s
.items
.copy_to
(items
, length
, 0, 0)
1084 # Create a new empty string with a given capacity.
1085 init with_capacity
(cap
: Int)
1088 # _items = new NativeString.calloc(cap)
1089 items
= calloc_string
(cap
+1)
1097 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1098 if s
isa FlatString then
1099 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1100 else if s
isa FlatBuffer then
1101 s
.items
.copy_to
(items
, sl
, 0, length
)
1103 var curr_pos
= self.length
1112 # Copies the content of self in `dest`
1113 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1115 var self_chars
= self.chars
1116 var dest_chars
= dest
.chars
1117 for i
in [0..len-1
] do
1118 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1122 redef fun substring
(from
, count
)
1126 if from
< 0 then from
= 0
1127 if count
> length
then count
= length
1128 if from
< count
then
1129 var r
= new FlatBuffer.with_capacity
(count
- from
)
1130 while from
< count
do
1131 r
.chars
.push
(items
[from
])
1136 return new FlatBuffer
1142 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1143 var reviter
= self.chars
.reverse_iterator
1144 while reviter
.is_ok
do
1145 new_buf
.add
(reviter
.item
)
1153 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1154 new_buf
.append
(self)
1155 new_buf
.append
(other
)
1159 redef fun *(repeats
)
1161 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1162 for i
in [0..repeats
[ do
1163 new_buf
.append
(self)
1169 private class FlatBufferReverseIterator
1170 super IndexedIterator[Char]
1172 var target
: FlatBuffer
1174 var target_items
: NativeString
1178 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1181 target_items
= tgt
.items
1185 redef fun index
do return curr_pos
1187 redef fun is_ok
do return curr_pos
>= 0
1189 redef fun item
do return target_items
[curr_pos
]
1191 redef fun next
do curr_pos
-= 1
1195 private class FlatBufferCharView
1196 super BufferCharView
1199 redef type SELFTYPE: FlatBuffer
1201 redef fun [](index
) do return target
.items
[index
]
1203 redef fun []=(index
, item
)
1205 assert index
>= 0 and index
<= length
1206 if index
== length
then
1210 target
.items
[index
] = item
1223 fun enlarge
(cap
: Int)
1230 var my_items
= target
.items
1231 var s_length
= s
.length
1232 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1235 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1237 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1241 private class FlatBufferIterator
1242 super IndexedIterator[Char]
1244 var target
: FlatBuffer
1246 var target_items
: NativeString
1250 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1253 target_items
= tgt
.items
1257 redef fun index
do return curr_pos
1259 redef fun is_ok
do return curr_pos
< target
.length
1261 redef fun item
do return target_items
[curr_pos
]
1263 redef fun next
do curr_pos
+= 1
1267 ###############################################################################
1269 ###############################################################################
1272 # User readable representation of `self`.
1273 fun to_s
: String do return inspect
1275 # The class name of the object in NativeString format.
1276 private fun native_class_name
: NativeString is intern
1278 # The class name of the object.
1280 # assert 5.class_name == "Int"
1281 fun class_name
: String do return native_class_name
.to_s
1283 # Developer readable representation of `self`.
1284 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1287 return "<{inspect_head}>"
1290 # Return "CLASSNAME:#OBJECTID".
1291 # This function is mainly used with the redefinition of the inspect method
1292 protected fun inspect_head
: String
1294 return "{class_name}:#{object_id.to_hex}"
1297 protected fun args
: Sequence[String]
1304 # assert true.to_s == "true"
1305 # assert false.to_s == "false"
1317 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1318 # assume < to_c max const of char
1319 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1326 else if self == 0 then
1333 var pos
= digit_count
(base
) - 1
1334 while pos
>= 0 and n
> 0 do
1335 s
.chars
[pos
] = (n
% base
).to_c
1341 # C function to convert an nit Int to a NativeString (char*)
1342 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1344 # return displayable int in base 10 and signed
1346 # assert 1.to_s == "1"
1347 # assert (-123).to_s == "-123"
1349 var len
= digit_count
(10)
1350 return native_int_to_s
(len
).to_s_with_length
(len
)
1353 # return displayable int in hexadecimal (unsigned (not now))
1354 fun to_hex
: String do return to_base
(16,false)
1356 # return displayable int in base base and signed
1357 fun to_base
(base
: Int, signed
: Bool): String
1359 var l
= digit_count
(base
)
1360 var s
= new FlatBuffer.from
(" " * l
)
1361 fill_buffer
(s
, base
, signed
)
1367 # Pretty print self, print needoed decimals up to a max of 3.
1369 var str
= to_precision
( 3 )
1370 if is_inf
!= 0 or is_nan
then return str
1371 var len
= str
.length
1372 for i
in [0..len-1
] do
1374 var c
= str
.chars
[j
]
1377 else if c
== '.' then
1378 return str
.substring
( 0, j
+2 )
1380 return str
.substring
( 0, j
+1 )
1386 # `self` representation with `nb` digits after the '.'.
1387 fun to_precision
(nb
: Int): String
1389 if is_nan
then return "nan"
1391 var isinf
= self.is_inf
1394 else if isinf
== -1 then
1398 if nb
== 0 then return self.to_i
.to_s
1400 for i
in [0..nb
[ do f
= f
* 10.0
1407 if i
== 0 then return "0.0"
1411 var p1
= s
.substring
(0, s
.length-nb
)
1412 var p2
= s
.substring
(s
.length-nb
, nb
)
1413 return p1
+ "." + p2
1415 return "0." + ("0"*(nb-sl
)) + s
1419 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1423 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1424 str = malloc(size + 1);
1425 sprintf(str, "%.*f", (int)nb, recv );
1427 return NativeString_to_s( str );
1432 # assert 'x'.to_s == "x"
1435 var s
= new FlatBuffer.with_capacity
(1)
1440 # Returns true if the char is a numerical digit
1441 fun is_numeric
: Bool
1443 if self >= '0' and self <= '9'
1450 # Returns true if the char is an alpha digit
1453 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1457 # Returns true if the char is an alpha or a numeric digit
1458 fun is_alphanumeric
: Bool
1460 if self.is_numeric
or self.is_alpha
then return true
1465 redef class Collection[E
]
1466 # Concatenate elements.
1469 var s
= new FlatBuffer
1470 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1474 # Concatenate and separate each elements with `sep`.
1476 # assert [1, 2, 3].join(":") == "1:2:3"
1477 # assert [1..3].join(":") == "1:2:3"
1478 fun join
(sep
: String): String
1480 if is_empty
then return ""
1482 var s
= new FlatBuffer # Result
1487 if e
!= null then s
.append
(e
.to_s
)
1489 # Concat other items
1494 if e
!= null then s
.append
(e
.to_s
)
1501 redef class Array[E
]
1502 # Fast implementation
1505 var s
= new FlatBuffer
1510 if e
!= null then s
.append
(e
.to_s
)
1517 redef class Map[K
,V
]
1518 # Concatenate couple of 'key value'.
1519 # key and value are separated by `couple_sep`.
1520 # each couple is separated each couple with `sep`.
1522 # var m = new ArrayMap[Int, String]
1525 # assert m.join("; ", "=") == "1=one; 10=ten"
1526 fun join
(sep
: String, couple_sep
: String): String
1528 if is_empty
then return ""
1530 var s
= new FlatBuffer # Result
1536 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1538 # Concat other items
1544 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1551 ###############################################################################
1553 ###############################################################################
1555 # Native strings are simple C char *
1559 fun [](index
: Int): Char is intern
1560 fun []=(index
: Int, item
: Char) is intern
1561 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1563 # Position of the first nul character.
1564 fun cstring_length
: Int
1567 while self[l
] != '\0' do l
+= 1
1570 fun atoi
: Int is intern
1571 fun atof
: Float is extern "atof"
1575 return to_s_with_length
(cstring_length
)
1578 fun to_s_with_length
(length
: Int): FlatString
1581 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1584 fun to_s_with_copy
: FlatString
1586 var length
= cstring_length
1587 var new_self
= calloc_string
(length
+ 1)
1588 copy_to
(new_self
, length
, 0, 0)
1589 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1594 # StringCapable objects can create native strings
1595 interface StringCapable
1596 protected fun calloc_string
(size
: Int): NativeString is intern
1600 var _args_cache
: nullable Sequence[String]
1602 redef fun args
: Sequence[String]
1604 if _args_cache
== null then init_args
1605 return _args_cache
.as(not null)
1608 # The name of the program as given by the OS
1609 fun program_name
: String
1611 return native_argv
(0).to_s
1614 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1615 private fun init_args
1617 var argc
= native_argc
1618 var args
= new Array[String].with_capacity
(0)
1621 args
[i-1
] = native_argv
(i
).to_s
1627 # First argument of the main C function.
1628 private fun native_argc
: Int is intern
1630 # Second argument of the main C function.
1631 private fun native_argv
(i
: Int): NativeString is intern