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 # Iterates on the substrings of self if any
63 fun substrings
: Iterator[Text] is abstract
65 # Concatenates `o` to `self`
67 # assert "hello" + "world" == "helloworld"
68 # assert "" + "hello" + "" == "hello"
69 fun +(o
: Text): SELFTYPE is abstract
71 # Auto-concatenates self `i` times
73 # assert "abc" * 4 == "abcabcabcabc"
74 # assert "abc" * 1 == "abc"
75 # assert "abc" * 0 == ""
76 fun *(i
: Int): SELFTYPE is abstract
78 # Is the current Text empty (== "")
81 # assert not "foo".is_empty
82 fun is_empty
: Bool do return self.length
== 0
84 # Returns an empty Text of the right type
86 # This method is used internally to get the right
87 # implementation of an empty string.
88 protected fun empty
: SELFTYPE is abstract
90 # Gets the first char of the Text
92 # DEPRECATED : Use self.chars.first instead
93 fun first
: Char do return self.chars
[0]
95 # Access a character at `index` in the string.
97 # assert "abcd"[2] == 'c'
99 # DEPRECATED : Use self.chars.[] instead
100 fun [](index
: Int): Char do return self.chars
[index
]
102 # Gets the index of the first occurence of 'c'
104 # Returns -1 if not found
106 # DEPRECATED : Use self.chars.index_of instead
107 fun index_of
(c
: Char): Int
109 return index_of_from
(c
, 0)
112 # Gets the last char of self
114 # DEPRECATED : Use self.chars.last instead
115 fun last
: Char do return self.chars
[length-1
]
117 # Gets the index of the first occurence of ´c´ starting from ´pos´
119 # Returns -1 if not found
121 # DEPRECATED : Use self.chars.index_of_from instead
122 fun index_of_from
(c
: Char, pos
: Int): Int
124 var iter
= self.chars
.iterator_from
(pos
)
126 if iter
.item
== c
then return iter
.index
132 # Gets the last index of char ´c´
134 # Returns -1 if not found
136 # DEPRECATED : Use self.chars.last_index_of instead
137 fun last_index_of
(c
: Char): Int
139 return last_index_of_from
(c
, length
- 1)
142 # Return a null terminated char *
143 fun to_cstring
: NativeString do return flatten
.to_cstring
145 # The index of the last occurrence of an element starting from pos (in reverse order).
147 # var s = "/etc/bin/test/test.nit"
148 # assert s.last_index_of_from('/', s.length-1) == 13
149 # assert s.last_index_of_from('/', 12) == 8
151 # Returns -1 if not found
153 # DEPRECATED : Use self.chars.last_index_of_from instead
154 fun last_index_of_from
(item
: Char, pos
: Int): Int
156 var iter
= self.chars
.reverse_iterator_from
(pos
)
158 if iter
.item
== item
then return iter
.index
164 # Gets an iterator on the chars of self
166 # DEPRECATED : Use self.chars.iterator instead
167 fun iterator
: Iterator[Char]
169 return self.chars
.iterator
172 # Is 'c' contained in self ?
174 # DEPRECATED : Use self.chars.has instead
175 fun has
(c
: Char): Bool
177 return self.chars
.has
(c
)
180 # Gets an Array containing the chars of self
182 # DEPRECATED : Use self.chars.to_a instead
183 fun to_a
: Array[Char] do return chars
.to_a
185 # Create a substring from `self` beginning at the `from` position
187 # assert "abcd".substring_from(1) == "bcd"
188 # assert "abcd".substring_from(-1) == "abcd"
189 # assert "abcd".substring_from(2) == "cd"
191 # As with substring, a `from` index < 0 will be replaced by 0
192 fun substring_from
(from
: Int): SELFTYPE
194 if from
> self.length
then return empty
195 if from
< 0 then from
= 0
196 return substring
(from
, length
- from
)
199 # Returns a reversed version of self
201 # assert "hello".reversed == "olleh"
202 # assert "bob".reversed == "bob"
203 # assert "".reversed == ""
204 fun reversed
: SELFTYPE is abstract
206 # Does self have a substring `str` starting from position `pos`?
208 # assert "abcd".has_substring("bc",1) == true
209 # assert "abcd".has_substring("bc",2) == false
210 fun has_substring
(str
: String, pos
: Int): Bool
212 var myiter
= self.chars
.iterator_from
(pos
)
213 var itsiter
= str
.chars
.iterator
214 while myiter
.is_ok
and itsiter
.is_ok
do
215 if myiter
.item
!= itsiter
.item
then return false
219 if itsiter
.is_ok
then return false
223 # Is this string prefixed by `prefix`?
225 # assert "abcd".has_prefix("ab") == true
226 # assert "abcbc".has_prefix("bc") == false
227 # assert "ab".has_prefix("abcd") == false
228 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
230 # Is this string suffixed by `suffix`?
232 # assert "abcd".has_suffix("abc") == false
233 # assert "abcd".has_suffix("bcd") == true
234 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
236 # If `self` contains only digits, return the corresponding integer
238 # assert "123".to_i == 123
239 # assert "-1".to_i == -1
243 return to_s
.to_cstring
.atoi
246 # If `self` contains a float, return the corresponding float
248 # assert "123".to_f == 123.0
249 # assert "-1".to_f == -1.0
250 # assert "-1.2e-3".to_f == -0.0012
254 return to_s
.to_cstring
.atof
257 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
259 # assert "ff".to_hex == 255
260 fun to_hex
: Int do return a_to
(16)
262 # If `self` contains only digits and letters, return the corresponding integer in a given base
264 # assert "120".a_to(3) == 15
265 fun a_to
(base
: Int) : Int
292 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
294 # assert "123".is_numeric == true
295 # assert "1.2".is_numeric == true
296 # assert "1,2".is_numeric == true
297 # assert "1..2".is_numeric == false
300 var has_point_or_comma
= false
305 if (i
== '.' or i
== ',') and not has_point_or_comma
307 has_point_or_comma
= true
316 # A upper case version of `self`
318 # assert "Hello World!".to_upper == "HELLO WORLD!"
319 fun to_upper
: SELFTYPE is abstract
321 # A lower case version of `self`
323 # assert "Hello World!".to_lower == "hello world!"
324 fun to_lower
: SELFTYPE is abstract
326 # Removes the whitespaces at the beginning of self
328 # assert " \n\thello \n\t".l_trim == "hello \n\t"
330 # A whitespace is defined as any character which ascii value is less than or equal to 32
333 var iter
= self.chars
.iterator
335 if iter
.item
.ascii
> 32 then break
338 if iter
.index
== length
then return self.empty
339 return self.substring_from
(iter
.index
)
342 # Removes the whitespaces at the end of self
344 # assert " \n\thello \n\t".r_trim == " \n\thello"
346 # A whitespace is defined as any character which ascii value is less than or equal to 32
349 var iter
= self.chars
.reverse_iterator
351 if iter
.item
.ascii
> 32 then break
354 if iter
.index
== length
then return self.empty
355 return self.substring
(0, iter
.index
+ 1)
358 # Trims trailing and preceding white spaces
359 # A whitespace is defined as any character which ascii value is less than or equal to 32
361 # assert " Hello World ! ".trim == "Hello World !"
362 # assert "\na\nb\tc\t".trim == "a\nb\tc"
363 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
365 # Mangle a string to be a unique string only made of alphanumeric characters
366 fun to_cmangle
: String
368 var res
= new FlatBuffer
369 var underscore
= false
370 for c
in self.chars
do
371 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
377 res
.append
('_'.ascii
.to_s
)
380 if c
>= '0' and c
<= '9' then
383 else if c
== '_' then
388 res
.append
(c
.ascii
.to_s
)
396 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
398 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
399 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
400 fun escape_to_c
: String
402 var b
= new FlatBuffer
403 for c
in self.chars
do
406 else if c
== '\0' then
408 else if c
== '"' then
410 else if c == '\'' then
412 else if c == '\\
' then
414 else if c.ascii < 32 then
415 b.append("\\{c.ascii.to_base(8, false)}")
423 # Escape additionnal characters
424 # The result might no be legal in C but be used in other languages
426 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
427 fun escape_more_to_c(chars: String): String
429 var b = new FlatBuffer
430 for c in escape_to_c.chars do
431 if chars.chars.has(c) then
439 # Escape to C plus braces
441 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
442 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
444 # Return a string where Nit escape sequences are transformed.
447 # assert s.length == 2
448 # var u = s.unescape_nit
449 # assert u.length == 1
450 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
451 fun unescape_nit
: String
453 var res
= new FlatBuffer.with_capacity
(self.length
)
454 var was_slash
= false
456 if not was_slash
then
467 else if c
== 'r' then
469 else if c
== 't' then
471 else if c
== '0' then
481 # Two pieces of text are equals if thez have the same characters in the same order.
483 # assert "hello" == "hello"
484 # assert "hello" != "HELLO"
485 # assert "hello" == "hel"+"lo"
487 # Things that are not Text are not equal.
490 # assert "9" != ['9']
493 # assert "9".chars.first == '9' # equality of Char
494 # assert "9".chars == ['9'] # equality of Sequence
495 # assert "9".to_i == 9 # equality of Int
498 if o
== null then return false
499 if not o
isa Text then return false
500 if self.is_same_instance
(o
) then return true
501 if self.length
!= o
.length
then return false
502 return self.chars
== o
.chars
505 # Lexicographical comparaison
507 # assert "abc" < "xy"
508 # assert "ABC" < "abc"
511 var self_chars
= self.chars
.iterator
512 var other_chars
= other
.chars
.iterator
514 while self_chars
.is_ok
and other_chars
.is_ok
do
515 if self_chars
.item
< other_chars
.item
then return true
516 if self_chars
.item
> other_chars
.item
then return false
521 if self_chars
.is_ok
then
528 # Flat representation of self
529 fun flatten
: FlatText is abstract
531 private var hash_cache
: nullable Int = null
535 if hash_cache
== null then
536 # djb2 hash algorithm
539 for char
in self.chars
do
540 h
= h
.lshift
(5) + h
+ char
.ascii
545 return hash_cache
.as(not null)
550 # All kinds of array-based text representations.
551 abstract class FlatText
554 private var items
: NativeString
556 # Real items, used as cache for to_cstring is called
557 private var real_items
: nullable NativeString = null
559 redef var length
: Int = 0
572 redef fun flatten
do return self
575 # Abstract class for the SequenceRead compatible
576 # views on String and Buffer objects
577 private abstract class StringCharView
578 super SequenceRead[Char]
582 private var target
: SELFTYPE
584 private init(tgt
: SELFTYPE)
589 redef fun is_empty
do return target
.is_empty
591 redef fun length
do return target
.length
593 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
595 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
598 # View on Buffer objects, extends Sequence
599 # for mutation operations
600 private abstract class BufferCharView
604 redef type SELFTYPE: Buffer
608 abstract class String
611 redef type SELFTYPE: String
613 redef fun to_s
do return self
615 fun append
(s
: String): SELFTYPE is abstract
617 fun prepend
(s
: String): SELFTYPE is abstract
619 fun insert_at
(s
: String, pos
: Int): SELFTYPE is abstract
622 private class FlatSubstringsIter
623 super Iterator[FlatText]
625 var tgt
: nullable FlatText
627 init(tgt
: FlatText) do self.tgt
= tgt
631 return tgt
.as(not null)
634 redef fun is_ok
do return tgt
!= null
636 redef fun next
do tgt
= null
639 # Immutable strings of characters.
644 # Index in _items of the start of the string
645 private var index_from
: Int
647 # Indes in _items of the last item of the string
648 private var index_to
: Int
650 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
652 ################################################
653 # AbstractString specific methods #
654 ################################################
658 var native
= calloc_string
(self.length
+ 1)
659 var length
= self.length
660 var items
= self.items
663 while pos
< length
do
664 native
[pos
] = items
[ipos
]
668 return native
.to_s_with_length
(self.length
)
671 redef fun substring
(from
, count
)
677 if count
< 0 then count
= 0
681 var realFrom
= index_from
+ from
683 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
685 if count
== 0 then return empty
687 var to
= realFrom
+ count
- 1
689 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
692 redef fun empty
do return "".as(FlatString)
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_upper
709 outstr
[self.length
] = '\0'
711 return outstr
.to_s_with_length
(self.length
)
716 var outstr
= calloc_string
(self.length
+ 1)
719 var myitems
= self.items
720 var index_from
= self.index_from
721 var max
= self.index_to
723 while index_from
<= max
do
724 outstr
[out_index
] = myitems
[index_from
].to_lower
729 outstr
[self.length
] = '\0'
731 return outstr
.to_s_with_length
(self.length
)
736 var i
= self.index_from
737 var imax
= self.index_to
744 ##################################################
745 # String Specific Methods #
746 ##################################################
748 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
756 redef fun to_cstring
: NativeString
758 if real_items
!= null then return real_items
.as(not null)
759 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
760 var newItems
= calloc_string
(length
+ 1)
761 self.items
.copy_to
(newItems
, length
, index_from
, 0)
762 newItems
[length
] = '\0'
763 self.real_items
= newItems
771 if not other
isa FlatString then return super
773 if self.object_id
== other
.object_id
then return true
775 var my_length
= length
777 if other
.length
!= my_length
then return false
779 var my_index
= index_from
780 var its_index
= other
.index_from
782 var last_iteration
= my_index
+ my_length
784 var itsitems
= other
.items
785 var myitems
= self.items
787 while my_index
< last_iteration
do
788 if myitems
[my_index
] != itsitems
[its_index
] then return false
798 if not other
isa FlatString then return super
800 if self.object_id
== other
.object_id
then return false
802 var my_curr_char
: Char
803 var its_curr_char
: Char
805 var curr_id_self
= self.index_from
806 var curr_id_other
= other
.index_from
808 var my_items
= self.items
809 var its_items
= other
.items
811 var my_length
= self.length
812 var its_length
= other
.length
814 var max_iterations
= curr_id_self
+ my_length
816 while curr_id_self
< max_iterations
do
817 my_curr_char
= my_items
[curr_id_self
]
818 its_curr_char
= its_items
[curr_id_other
]
820 if my_curr_char
!= its_curr_char
then
821 if my_curr_char
< its_curr_char
then return true
829 return my_length
< its_length
834 var my_length
= self.length
835 var its_length
= s
.length
837 var total_length
= my_length
+ its_length
839 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
841 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
842 if s
isa FlatString then
843 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
844 else if s
isa FlatBuffer then
845 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
847 var curr_pos
= my_length
849 target_string
[curr_pos
] = i
854 target_string
[total_length
] = '\0'
856 return target_string
.to_s_with_length
(total_length
)
863 var my_length
= self.length
865 var final_length
= my_length
* i
867 var my_items
= self.items
869 var target_string
= calloc_string
((final_length
) + 1)
871 target_string
[final_length
] = '\0'
875 for iteration
in [1 .. i
] do
876 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
877 current_last
+= my_length
880 return target_string
.to_s_with_length
(final_length
)
885 if hash_cache
== null then
886 # djb2 hash algorithm
892 while i
<= index_to
do
893 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
900 return hash_cache
.as(not null)
903 redef fun substrings
do return new FlatSubstringsIter(self)
906 private class FlatStringReverseIterator
907 super IndexedIterator[Char]
909 var target
: FlatString
911 var target_items
: NativeString
915 init with_pos
(tgt
: FlatString, pos
: Int)
918 target_items
= tgt
.items
919 curr_pos
= pos
+ tgt
.index_from
922 redef fun is_ok
do return curr_pos
>= 0
924 redef fun item
do return target_items
[curr_pos
]
926 redef fun next
do curr_pos
-= 1
928 redef fun index
do return curr_pos
- target
.index_from
932 private class FlatStringIterator
933 super IndexedIterator[Char]
935 var target
: FlatString
937 var target_items
: NativeString
941 init with_pos
(tgt
: FlatString, pos
: Int)
944 target_items
= tgt
.items
945 curr_pos
= pos
+ target
.index_from
948 redef fun is_ok
do return curr_pos
<= target
.index_to
950 redef fun item
do return target_items
[curr_pos
]
952 redef fun next
do curr_pos
+= 1
954 redef fun index
do return curr_pos
- target
.index_from
958 private class FlatStringCharView
961 redef type SELFTYPE: FlatString
965 # Check that the index (+ index_from) is not larger than indexTo
966 # In other terms, if the index is valid
968 var target
= self.target
969 assert (index
+ target
.index_from
) <= target
.index_to
970 return target
.items
[index
+ target
.index_from
]
973 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
975 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
979 abstract class Buffer
982 redef type SELFTYPE: Buffer
984 # Specific implementations MUST set this to `true` in order to invalidate caches
985 protected var is_dirty
= true
987 # Modifies the char contained at pos `index`
989 # DEPRECATED : Use self.chars.[]= instead
990 fun []=(index
: Int, item
: Char) is abstract
992 # Adds a char `c` at the end of self
994 # DEPRECATED : Use self.chars.add instead
995 fun add
(c
: Char) is abstract
999 # var b = new FlatBuffer
1001 # assert not b.is_empty
1004 fun clear
is abstract
1006 # Enlarges the subsequent array containing the chars of self
1007 fun enlarge
(cap
: Int) is abstract
1009 # Adds the content of text `s` at the end of self
1011 # var b = new FlatBuffer
1014 # assert b == "helloworld"
1015 fun append
(s
: Text) is abstract
1019 if is_dirty
then hash_cache
= null
1023 # In Buffers, the internal sequence of character is mutable
1024 # Thus, `chars` can be used to modify the buffer.
1025 redef fun chars
: Sequence[Char] is abstract
1028 # Mutable strings of characters.
1033 redef type SELFTYPE: FlatBuffer
1035 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1037 private var capacity
: Int = 0
1039 redef fun substrings
do return new FlatSubstringsIter(self)
1041 redef fun []=(index
, item
)
1044 if index
== length
then
1048 assert index
>= 0 and index
< length
1055 if capacity
<= length
then enlarge
(length
+ 5)
1065 redef fun empty
do return new FlatBuffer
1067 redef fun enlarge
(cap
)
1070 if cap
<= c
then return
1071 while c
<= cap
do c
= c
* 2 + 2
1072 var a
= calloc_string
(c
+1)
1073 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1078 redef fun to_s
: String
1080 return to_cstring
.to_s_with_length
(length
)
1083 redef fun to_cstring
1086 var new_native
= calloc_string
(length
+ 1)
1087 new_native
[length
] = '\0'
1088 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1089 real_items
= new_native
1092 return real_items
.as(not null)
1095 # Create a new empty string.
1100 capacity
= s
.length
+ 1
1102 items
= calloc_string
(capacity
)
1103 if s
isa FlatString then
1104 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1105 else if s
isa FlatBuffer then
1106 s
.items
.copy_to
(items
, length
, 0, 0)
1116 # Create a new empty string with a given capacity.
1117 init with_capacity
(cap
: Int)
1120 # _items = new NativeString.calloc(cap)
1121 items
= calloc_string
(cap
+1)
1128 if s
.is_empty
then return
1131 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1132 if s
isa FlatString then
1133 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1134 else if s
isa FlatBuffer then
1135 s
.items
.copy_to
(items
, sl
, 0, length
)
1137 var curr_pos
= self.length
1146 # Copies the content of self in `dest`
1147 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1149 var self_chars
= self.chars
1150 var dest_chars
= dest
.chars
1151 for i
in [0..len-1
] do
1152 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1156 redef fun substring
(from
, count
)
1160 if from
< 0 then from
= 0
1161 if count
> length
then count
= length
1162 if from
< count
then
1163 var r
= new FlatBuffer.with_capacity
(count
- from
)
1164 while from
< count
do
1165 r
.chars
.push
(items
[from
])
1170 return new FlatBuffer
1176 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1177 var reviter
= self.chars
.reverse_iterator
1178 while reviter
.is_ok
do
1179 new_buf
.add
(reviter
.item
)
1187 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1188 new_buf
.append
(self)
1189 new_buf
.append
(other
)
1193 redef fun *(repeats
)
1195 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1196 for i
in [0..repeats
[ do
1197 new_buf
.append
(self)
1204 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1205 for i
in self.chars
do
1206 new_buf
.add
(i
.to_upper
)
1213 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1214 for i
in self.chars
do
1215 new_buf
.add
(i
.to_lower
)
1221 private class FlatBufferReverseIterator
1222 super IndexedIterator[Char]
1224 var target
: FlatBuffer
1226 var target_items
: NativeString
1230 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1233 if tgt
.length
> 0 then target_items
= tgt
.items
1237 redef fun index
do return curr_pos
1239 redef fun is_ok
do return curr_pos
>= 0
1241 redef fun item
do return target_items
[curr_pos
]
1243 redef fun next
do curr_pos
-= 1
1247 private class FlatBufferCharView
1248 super BufferCharView
1251 redef type SELFTYPE: FlatBuffer
1253 redef fun [](index
) do return target
.items
[index
]
1255 redef fun []=(index
, item
)
1257 assert index
>= 0 and index
<= length
1258 if index
== length
then
1262 target
.items
[index
] = item
1275 fun enlarge
(cap
: Int)
1282 var my_items
= target
.items
1283 var s_length
= s
.length
1284 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1287 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1289 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1293 private class FlatBufferIterator
1294 super IndexedIterator[Char]
1296 var target
: FlatBuffer
1298 var target_items
: NativeString
1302 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1305 if tgt
.length
> 0 then target_items
= tgt
.items
1309 redef fun index
do return curr_pos
1311 redef fun is_ok
do return curr_pos
< target
.length
1313 redef fun item
do return target_items
[curr_pos
]
1315 redef fun next
do curr_pos
+= 1
1319 ###############################################################################
1321 ###############################################################################
1324 # User readable representation of `self`.
1325 fun to_s
: String do return inspect
1327 # The class name of the object in NativeString format.
1328 private fun native_class_name
: NativeString is intern
1330 # The class name of the object.
1332 # assert 5.class_name == "Int"
1333 fun class_name
: String do return native_class_name
.to_s
1335 # Developer readable representation of `self`.
1336 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1339 return "<{inspect_head}>"
1342 # Return "CLASSNAME:#OBJECTID".
1343 # This function is mainly used with the redefinition of the inspect method
1344 protected fun inspect_head
: String
1346 return "{class_name}:#{object_id.to_hex}"
1349 protected fun args
: Sequence[String]
1356 # assert true.to_s == "true"
1357 # assert false.to_s == "false"
1370 # Wrapper of strerror C function
1371 private fun strerror_ext
: NativeString is extern `{
1372 return strerror(recv);
1375 # Returns a string describing error number
1376 fun strerror
: String do return strerror_ext
.to_s
1378 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1379 # assume < to_c max const of char
1380 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1387 else if self == 0 then
1394 var pos
= digit_count
(base
) - 1
1395 while pos
>= 0 and n
> 0 do
1396 s
.chars
[pos
] = (n
% base
).to_c
1402 # C function to convert an nit Int to a NativeString (char*)
1403 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1405 # return displayable int in base 10 and signed
1407 # assert 1.to_s == "1"
1408 # assert (-123).to_s == "-123"
1410 var len
= digit_count
(10)
1411 return native_int_to_s
(len
).to_s_with_length
(len
)
1414 # return displayable int in hexadecimal
1416 # assert 1.to_hex == "1"
1417 # assert (-255).to_hex == "-ff"
1418 fun to_hex
: String do return to_base
(16,false)
1420 # return displayable int in base base and signed
1421 fun to_base
(base
: Int, signed
: Bool): String
1423 var l
= digit_count
(base
)
1424 var s
= new FlatBuffer.from
(" " * l
)
1425 fill_buffer
(s
, base
, signed
)
1431 # Pretty print self, print needoed decimals up to a max of 3.
1433 # assert 12.34.to_s == "12.34"
1434 # assert (-0120.03450).to_s == "-120.035"
1436 # see `to_precision` for a different precision.
1438 var str
= to_precision
( 3 )
1439 if is_inf
!= 0 or is_nan
then return str
1440 var len
= str
.length
1441 for i
in [0..len-1
] do
1443 var c
= str
.chars
[j
]
1446 else if c
== '.' then
1447 return str
.substring
( 0, j
+2 )
1449 return str
.substring
( 0, j
+1 )
1455 # `self` representation with `nb` digits after the '.'.
1457 # assert 12.345.to_precision(1) == "12.3"
1458 # assert 12.345.to_precision(2) == "12.35"
1459 # assert 12.345.to_precision(3) == "12.345"
1460 # assert 12.345.to_precision(4) == "12.3450"
1461 fun to_precision
(nb
: Int): String
1463 if is_nan
then return "nan"
1465 var isinf
= self.is_inf
1468 else if isinf
== -1 then
1472 if nb
== 0 then return self.to_i
.to_s
1474 for i
in [0..nb
[ do f
= f
* 10.0
1481 if i
== 0 then return "0.0"
1485 var p1
= s
.substring
(0, s
.length-nb
)
1486 var p2
= s
.substring
(s
.length-nb
, nb
)
1487 return p1
+ "." + p2
1489 return "0." + ("0"*(nb-sl
)) + s
1493 # `self` representation with `nb` digits after the '.'.
1495 # assert 12.345.to_precision_native(1) == "12.3"
1496 # assert 12.345.to_precision_native(2) == "12.35"
1497 # assert 12.345.to_precision_native(3) == "12.345"
1498 # assert 12.345.to_precision_native(4) == "12.3450"
1499 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1503 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1504 str = malloc(size + 1);
1505 sprintf(str, "%.*f", (int)nb, recv );
1507 return NativeString_to_s( str );
1512 # assert 'x'.to_s == "x"
1515 var s
= new FlatBuffer.with_capacity
(1)
1520 # Returns true if the char is a numerical digit
1522 # assert '0'.is_numeric
1523 # assert '9'.is_numeric
1524 # assert not 'a'.is_numeric
1525 # assert not '?'.is_numeric
1526 fun is_numeric
: Bool
1528 return self >= '0' and self <= '9'
1531 # Returns true if the char is an alpha digit
1533 # assert 'a'.is_alpha
1534 # assert 'Z'.is_alpha
1535 # assert not '0'.is_alpha
1536 # assert not '?'.is_alpha
1539 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1542 # Returns true if the char is an alpha or a numeric digit
1544 # assert 'a'.is_alphanumeric
1545 # assert 'Z'.is_alphanumeric
1546 # assert '0'.is_alphanumeric
1547 # assert '9'.is_alphanumeric
1548 # assert not '?'.is_alphanumeric
1549 fun is_alphanumeric
: Bool
1551 return self.is_numeric
or self.is_alpha
1555 redef class Collection[E
]
1556 # Concatenate elements.
1559 var s
= new FlatBuffer
1560 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1564 # Concatenate and separate each elements with `sep`.
1566 # assert [1, 2, 3].join(":") == "1:2:3"
1567 # assert [1..3].join(":") == "1:2:3"
1568 fun join
(sep
: Text): String
1570 if is_empty
then return ""
1572 var s
= new FlatBuffer # Result
1577 if e
!= null then s
.append
(e
.to_s
)
1579 # Concat other items
1584 if e
!= null then s
.append
(e
.to_s
)
1591 redef class Array[E
]
1592 # Fast implementation
1595 var s
= new FlatBuffer
1600 if e
!= null then s
.append
(e
.to_s
)
1607 redef class Map[K
,V
]
1608 # Concatenate couple of 'key value'.
1609 # key and value are separated by `couple_sep`.
1610 # each couple is separated each couple with `sep`.
1612 # var m = new ArrayMap[Int, String]
1615 # assert m.join("; ", "=") == "1=one; 10=ten"
1616 fun join
(sep
: String, couple_sep
: String): String
1618 if is_empty
then return ""
1620 var s
= new FlatBuffer # Result
1626 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1628 # Concat other items
1634 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1641 ###############################################################################
1643 ###############################################################################
1645 # Native strings are simple C char *
1649 fun [](index
: Int): Char is intern
1650 fun []=(index
: Int, item
: Char) is intern
1651 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1653 # Position of the first nul character.
1654 fun cstring_length
: Int
1657 while self[l
] != '\0' do l
+= 1
1660 fun atoi
: Int is intern
1661 fun atof
: Float is extern "atof"
1665 return to_s_with_length
(cstring_length
)
1668 fun to_s_with_length
(length
: Int): FlatString
1671 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1674 fun to_s_with_copy
: FlatString
1676 var length
= cstring_length
1677 var new_self
= calloc_string
(length
+ 1)
1678 copy_to
(new_self
, length
, 0, 0)
1679 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1684 # StringCapable objects can create native strings
1685 interface StringCapable
1686 protected fun calloc_string
(size
: Int): NativeString is intern
1690 var _args_cache
: nullable Sequence[String]
1692 redef fun args
: Sequence[String]
1694 if _args_cache
== null then init_args
1695 return _args_cache
.as(not null)
1698 # The name of the program as given by the OS
1699 fun program_name
: String
1701 return native_argv
(0).to_s
1704 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1705 private fun init_args
1707 var argc
= native_argc
1708 var args
= new Array[String].with_capacity
(0)
1711 args
[i-1
] = native_argv
(i
).to_s
1717 # First argument of the main C function.
1718 private fun native_argc
: Int is intern
1720 # Second argument of the main C function.
1721 private fun native_argv
(i
: Int): NativeString is intern
1724 # Comparator that efficienlty use `to_s` to compare things
1726 # The comparaison call `to_s` on object and use the result to order things.
1728 # var a = [1, 2, 3, 10, 20]
1729 # (new CachedAlphaComparator).sort(a)
1730 # assert a == [1, 10, 2, 20, 3]
1732 # Internally the result of `to_s` is cached in a HashMap to counter
1733 # uneficient implementation of `to_s`.
1735 # Note: it caching is not usefull, see `alpha_comparator`
1736 class CachedAlphaComparator
1737 super Comparator[Object]
1739 private var cache
= new HashMap[Object, String]
1741 private fun do_to_s
(a
: Object): String do
1742 if cache
.has_key
(a
) then return cache
[a
]
1748 redef fun compare
(a
, b
) do
1749 return do_to_s
(a
) <=> do_to_s
(b
)
1753 # see `alpha_comparator`
1754 private class AlphaComparator
1755 super Comparator[Object]
1756 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1759 # Stateless comparator that naively use `to_s` to compare things.
1761 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1762 # on a single instace. See `CachedAlphaComparator` as an alternative.
1764 # var a = [1, 2, 3, 10, 20]
1765 # alpha_comparator.sort(a)
1766 # assert a == [1, 10, 2, 20, 3]
1767 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator