13bf585ab001ef3fd859eb175b41edae01079b7e
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
616 private class FlatSubstringsIter
617 super Iterator[FlatText]
619 var tgt
: nullable FlatText
621 init(tgt
: FlatText) do self.tgt
= tgt
625 return tgt
.as(not null)
628 redef fun is_ok
do return tgt
!= null
630 redef fun next
do tgt
= null
633 # Immutable strings of characters.
638 # Index in _items of the start of the string
639 private var index_from
: Int
641 # Indes in _items of the last item of the string
642 private var index_to
: Int
644 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
646 ################################################
647 # AbstractString specific methods #
648 ################################################
652 var native
= calloc_string
(self.length
+ 1)
653 var length
= self.length
654 var items
= self.items
657 while pos
< length
do
658 native
[pos
] = items
[ipos
]
662 return native
.to_s_with_length
(self.length
)
665 redef fun substring
(from
, count
)
671 if count
< 0 then count
= 0
675 var realFrom
= index_from
+ from
677 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
679 if count
== 0 then return empty
681 var to
= realFrom
+ count
- 1
683 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
686 redef fun empty
do return "".as(FlatString)
690 var outstr
= calloc_string
(self.length
+ 1)
693 var myitems
= self.items
694 var index_from
= self.index_from
695 var max
= self.index_to
697 while index_from
<= max
do
698 outstr
[out_index
] = myitems
[index_from
].to_upper
703 outstr
[self.length
] = '\0'
705 return outstr
.to_s_with_length
(self.length
)
710 var outstr
= calloc_string
(self.length
+ 1)
713 var myitems
= self.items
714 var index_from
= self.index_from
715 var max
= self.index_to
717 while index_from
<= max
do
718 outstr
[out_index
] = myitems
[index_from
].to_lower
723 outstr
[self.length
] = '\0'
725 return outstr
.to_s_with_length
(self.length
)
730 var i
= self.index_from
731 var imax
= self.index_to
738 ##################################################
739 # String Specific Methods #
740 ##################################################
742 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
750 redef fun to_cstring
: NativeString
752 if real_items
!= null then return real_items
.as(not null)
753 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
754 var newItems
= calloc_string
(length
+ 1)
755 self.items
.copy_to
(newItems
, length
, index_from
, 0)
756 newItems
[length
] = '\0'
757 self.real_items
= newItems
765 if not other
isa FlatString then return super
767 if self.object_id
== other
.object_id
then return true
769 var my_length
= length
771 if other
.length
!= my_length
then return false
773 var my_index
= index_from
774 var its_index
= other
.index_from
776 var last_iteration
= my_index
+ my_length
778 var itsitems
= other
.items
779 var myitems
= self.items
781 while my_index
< last_iteration
do
782 if myitems
[my_index
] != itsitems
[its_index
] then return false
792 if not other
isa FlatString then return super
794 if self.object_id
== other
.object_id
then return false
796 var my_curr_char
: Char
797 var its_curr_char
: Char
799 var curr_id_self
= self.index_from
800 var curr_id_other
= other
.index_from
802 var my_items
= self.items
803 var its_items
= other
.items
805 var my_length
= self.length
806 var its_length
= other
.length
808 var max_iterations
= curr_id_self
+ my_length
810 while curr_id_self
< max_iterations
do
811 my_curr_char
= my_items
[curr_id_self
]
812 its_curr_char
= its_items
[curr_id_other
]
814 if my_curr_char
!= its_curr_char
then
815 if my_curr_char
< its_curr_char
then return true
823 return my_length
< its_length
828 var my_length
= self.length
829 var its_length
= s
.length
831 var total_length
= my_length
+ its_length
833 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
835 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
836 if s
isa FlatString then
837 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
838 else if s
isa FlatBuffer then
839 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
841 var curr_pos
= my_length
843 target_string
[curr_pos
] = i
848 target_string
[total_length
] = '\0'
850 return target_string
.to_s_with_length
(total_length
)
857 var my_length
= self.length
859 var final_length
= my_length
* i
861 var my_items
= self.items
863 var target_string
= calloc_string
((final_length
) + 1)
865 target_string
[final_length
] = '\0'
869 for iteration
in [1 .. i
] do
870 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
871 current_last
+= my_length
874 return target_string
.to_s_with_length
(final_length
)
879 if hash_cache
== null then
880 # djb2 hash algorithm
886 while i
<= index_to
do
887 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
894 return hash_cache
.as(not null)
897 redef fun substrings
do return new FlatSubstringsIter(self)
900 private class FlatStringReverseIterator
901 super IndexedIterator[Char]
903 var target
: FlatString
905 var target_items
: NativeString
909 init with_pos
(tgt
: FlatString, pos
: Int)
912 target_items
= tgt
.items
913 curr_pos
= pos
+ tgt
.index_from
916 redef fun is_ok
do return curr_pos
>= 0
918 redef fun item
do return target_items
[curr_pos
]
920 redef fun next
do curr_pos
-= 1
922 redef fun index
do return curr_pos
- target
.index_from
926 private class FlatStringIterator
927 super IndexedIterator[Char]
929 var target
: FlatString
931 var target_items
: NativeString
935 init with_pos
(tgt
: FlatString, pos
: Int)
938 target_items
= tgt
.items
939 curr_pos
= pos
+ target
.index_from
942 redef fun is_ok
do return curr_pos
<= target
.index_to
944 redef fun item
do return target_items
[curr_pos
]
946 redef fun next
do curr_pos
+= 1
948 redef fun index
do return curr_pos
- target
.index_from
952 private class FlatStringCharView
955 redef type SELFTYPE: FlatString
959 # Check that the index (+ index_from) is not larger than indexTo
960 # In other terms, if the index is valid
962 var target
= self.target
963 assert (index
+ target
.index_from
) <= target
.index_to
964 return target
.items
[index
+ target
.index_from
]
967 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
969 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
973 abstract class Buffer
976 redef type SELFTYPE: Buffer
978 # Specific implementations MUST set this to `true` in order to invalidate caches
979 protected var is_dirty
= true
981 # Modifies the char contained at pos `index`
983 # DEPRECATED : Use self.chars.[]= instead
984 fun []=(index
: Int, item
: Char) is abstract
986 # Adds a char `c` at the end of self
988 # DEPRECATED : Use self.chars.add instead
989 fun add
(c
: Char) is abstract
993 # var b = new FlatBuffer
995 # assert not b.is_empty
998 fun clear
is abstract
1000 # Enlarges the subsequent array containing the chars of self
1001 fun enlarge
(cap
: Int) is abstract
1003 # Adds the content of text `s` at the end of self
1005 # var b = new FlatBuffer
1008 # assert b == "helloworld"
1009 fun append
(s
: Text) is abstract
1013 if is_dirty
then hash_cache
= null
1017 # In Buffers, the internal sequence of character is mutable
1018 # Thus, `chars` can be used to modify the buffer.
1019 redef fun chars
: Sequence[Char] is abstract
1022 # Mutable strings of characters.
1027 redef type SELFTYPE: FlatBuffer
1029 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1031 private var capacity
: Int = 0
1033 redef fun substrings
do return new FlatSubstringsIter(self)
1035 redef fun []=(index
, item
)
1038 if index
== length
then
1042 assert index
>= 0 and index
< length
1049 if capacity
<= length
then enlarge
(length
+ 5)
1059 redef fun empty
do return new FlatBuffer
1061 redef fun enlarge
(cap
)
1064 if cap
<= c
then return
1065 while c
<= cap
do c
= c
* 2 + 2
1066 var a
= calloc_string
(c
+1)
1067 if length
> 0 then 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 if length
> 0 then 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.
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)
1122 if s
.is_empty
then return
1125 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1126 if s
isa FlatString then
1127 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1128 else if s
isa FlatBuffer then
1129 s
.items
.copy_to
(items
, sl
, 0, length
)
1131 var curr_pos
= self.length
1140 # Copies the content of self in `dest`
1141 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1143 var self_chars
= self.chars
1144 var dest_chars
= dest
.chars
1145 for i
in [0..len-1
] do
1146 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1150 redef fun substring
(from
, count
)
1154 if from
< 0 then from
= 0
1155 if count
> length
then count
= length
1156 if from
< count
then
1157 var r
= new FlatBuffer.with_capacity
(count
- from
)
1158 while from
< count
do
1159 r
.chars
.push
(items
[from
])
1164 return new FlatBuffer
1170 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1171 var reviter
= self.chars
.reverse_iterator
1172 while reviter
.is_ok
do
1173 new_buf
.add
(reviter
.item
)
1181 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1182 new_buf
.append
(self)
1183 new_buf
.append
(other
)
1187 redef fun *(repeats
)
1189 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1190 for i
in [0..repeats
[ do
1191 new_buf
.append
(self)
1198 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1199 for i
in self.chars
do
1200 new_buf
.add
(i
.to_upper
)
1207 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1208 for i
in self.chars
do
1209 new_buf
.add
(i
.to_lower
)
1215 private class FlatBufferReverseIterator
1216 super IndexedIterator[Char]
1218 var target
: FlatBuffer
1220 var target_items
: NativeString
1224 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1227 if tgt
.length
> 0 then target_items
= tgt
.items
1231 redef fun index
do return curr_pos
1233 redef fun is_ok
do return curr_pos
>= 0
1235 redef fun item
do return target_items
[curr_pos
]
1237 redef fun next
do curr_pos
-= 1
1241 private class FlatBufferCharView
1242 super BufferCharView
1245 redef type SELFTYPE: FlatBuffer
1247 redef fun [](index
) do return target
.items
[index
]
1249 redef fun []=(index
, item
)
1251 assert index
>= 0 and index
<= length
1252 if index
== length
then
1256 target
.items
[index
] = item
1269 fun enlarge
(cap
: Int)
1276 var my_items
= target
.items
1277 var s_length
= s
.length
1278 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1281 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1283 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1287 private class FlatBufferIterator
1288 super IndexedIterator[Char]
1290 var target
: FlatBuffer
1292 var target_items
: NativeString
1296 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1299 if tgt
.length
> 0 then target_items
= tgt
.items
1303 redef fun index
do return curr_pos
1305 redef fun is_ok
do return curr_pos
< target
.length
1307 redef fun item
do return target_items
[curr_pos
]
1309 redef fun next
do curr_pos
+= 1
1313 ###############################################################################
1315 ###############################################################################
1318 # User readable representation of `self`.
1319 fun to_s
: String do return inspect
1321 # The class name of the object in NativeString format.
1322 private fun native_class_name
: NativeString is intern
1324 # The class name of the object.
1326 # assert 5.class_name == "Int"
1327 fun class_name
: String do return native_class_name
.to_s
1329 # Developer readable representation of `self`.
1330 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1333 return "<{inspect_head}>"
1336 # Return "CLASSNAME:#OBJECTID".
1337 # This function is mainly used with the redefinition of the inspect method
1338 protected fun inspect_head
: String
1340 return "{class_name}:#{object_id.to_hex}"
1343 protected fun args
: Sequence[String]
1350 # assert true.to_s == "true"
1351 # assert false.to_s == "false"
1364 # Wrapper of strerror C function
1365 private fun strerror_ext
: NativeString is extern `{
1366 return strerror(recv);
1369 # Returns a string describing error number
1370 fun strerror
: String do return strerror_ext
.to_s
1372 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1373 # assume < to_c max const of char
1374 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1381 else if self == 0 then
1388 var pos
= digit_count
(base
) - 1
1389 while pos
>= 0 and n
> 0 do
1390 s
.chars
[pos
] = (n
% base
).to_c
1396 # C function to convert an nit Int to a NativeString (char*)
1397 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1399 # return displayable int in base 10 and signed
1401 # assert 1.to_s == "1"
1402 # assert (-123).to_s == "-123"
1404 var len
= digit_count
(10)
1405 return native_int_to_s
(len
).to_s_with_length
(len
)
1408 # return displayable int in hexadecimal
1410 # assert 1.to_hex == "1"
1411 # assert (-255).to_hex == "-ff"
1412 fun to_hex
: String do return to_base
(16,false)
1414 # return displayable int in base base and signed
1415 fun to_base
(base
: Int, signed
: Bool): String
1417 var l
= digit_count
(base
)
1418 var s
= new FlatBuffer.from
(" " * l
)
1419 fill_buffer
(s
, base
, signed
)
1425 # Pretty print self, print needoed decimals up to a max of 3.
1427 # assert 12.34.to_s == "12.34"
1428 # assert (-0120.03450).to_s == "-120.035"
1430 # see `to_precision` for a different precision.
1432 var str
= to_precision
( 3 )
1433 if is_inf
!= 0 or is_nan
then return str
1434 var len
= str
.length
1435 for i
in [0..len-1
] do
1437 var c
= str
.chars
[j
]
1440 else if c
== '.' then
1441 return str
.substring
( 0, j
+2 )
1443 return str
.substring
( 0, j
+1 )
1449 # `self` representation with `nb` digits after the '.'.
1451 # assert 12.345.to_precision(1) == "12.3"
1452 # assert 12.345.to_precision(2) == "12.35"
1453 # assert 12.345.to_precision(3) == "12.345"
1454 # assert 12.345.to_precision(4) == "12.3450"
1455 fun to_precision
(nb
: Int): String
1457 if is_nan
then return "nan"
1459 var isinf
= self.is_inf
1462 else if isinf
== -1 then
1466 if nb
== 0 then return self.to_i
.to_s
1468 for i
in [0..nb
[ do f
= f
* 10.0
1475 if i
== 0 then return "0.0"
1479 var p1
= s
.substring
(0, s
.length-nb
)
1480 var p2
= s
.substring
(s
.length-nb
, nb
)
1481 return p1
+ "." + p2
1483 return "0." + ("0"*(nb-sl
)) + s
1487 # `self` representation with `nb` digits after the '.'.
1489 # assert 12.345.to_precision_native(1) == "12.3"
1490 # assert 12.345.to_precision_native(2) == "12.35"
1491 # assert 12.345.to_precision_native(3) == "12.345"
1492 # assert 12.345.to_precision_native(4) == "12.3450"
1493 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1497 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1498 str = malloc(size + 1);
1499 sprintf(str, "%.*f", (int)nb, recv );
1501 return NativeString_to_s( str );
1506 # assert 'x'.to_s == "x"
1509 var s
= new FlatBuffer.with_capacity
(1)
1514 # Returns true if the char is a numerical digit
1516 # assert '0'.is_numeric
1517 # assert '9'.is_numeric
1518 # assert not 'a'.is_numeric
1519 # assert not '?'.is_numeric
1520 fun is_numeric
: Bool
1522 return self >= '0' and self <= '9'
1525 # Returns true if the char is an alpha digit
1527 # assert 'a'.is_alpha
1528 # assert 'Z'.is_alpha
1529 # assert not '0'.is_alpha
1530 # assert not '?'.is_alpha
1533 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1536 # Returns true if the char is an alpha or a numeric digit
1538 # assert 'a'.is_alphanumeric
1539 # assert 'Z'.is_alphanumeric
1540 # assert '0'.is_alphanumeric
1541 # assert '9'.is_alphanumeric
1542 # assert not '?'.is_alphanumeric
1543 fun is_alphanumeric
: Bool
1545 return self.is_numeric
or self.is_alpha
1549 redef class Collection[E
]
1550 # Concatenate elements.
1553 var s
= new FlatBuffer
1554 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1558 # Concatenate and separate each elements with `sep`.
1560 # assert [1, 2, 3].join(":") == "1:2:3"
1561 # assert [1..3].join(":") == "1:2:3"
1562 fun join
(sep
: Text): String
1564 if is_empty
then return ""
1566 var s
= new FlatBuffer # Result
1571 if e
!= null then s
.append
(e
.to_s
)
1573 # Concat other items
1578 if e
!= null then s
.append
(e
.to_s
)
1585 redef class Array[E
]
1586 # Fast implementation
1589 var s
= new FlatBuffer
1594 if e
!= null then s
.append
(e
.to_s
)
1601 redef class Map[K
,V
]
1602 # Concatenate couple of 'key value'.
1603 # key and value are separated by `couple_sep`.
1604 # each couple is separated each couple with `sep`.
1606 # var m = new ArrayMap[Int, String]
1609 # assert m.join("; ", "=") == "1=one; 10=ten"
1610 fun join
(sep
: String, couple_sep
: String): String
1612 if is_empty
then return ""
1614 var s
= new FlatBuffer # Result
1620 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1622 # Concat other items
1628 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1635 ###############################################################################
1637 ###############################################################################
1639 # Native strings are simple C char *
1643 fun [](index
: Int): Char is intern
1644 fun []=(index
: Int, item
: Char) is intern
1645 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1647 # Position of the first nul character.
1648 fun cstring_length
: Int
1651 while self[l
] != '\0' do l
+= 1
1654 fun atoi
: Int is intern
1655 fun atof
: Float is extern "atof"
1659 return to_s_with_length
(cstring_length
)
1662 fun to_s_with_length
(length
: Int): FlatString
1665 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1668 fun to_s_with_copy
: FlatString
1670 var length
= cstring_length
1671 var new_self
= calloc_string
(length
+ 1)
1672 copy_to
(new_self
, length
, 0, 0)
1673 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1678 # StringCapable objects can create native strings
1679 interface StringCapable
1680 protected fun calloc_string
(size
: Int): NativeString is intern
1684 var _args_cache
: nullable Sequence[String]
1686 redef fun args
: Sequence[String]
1688 if _args_cache
== null then init_args
1689 return _args_cache
.as(not null)
1692 # The name of the program as given by the OS
1693 fun program_name
: String
1695 return native_argv
(0).to_s
1698 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1699 private fun init_args
1701 var argc
= native_argc
1702 var args
= new Array[String].with_capacity
(0)
1705 args
[i-1
] = native_argv
(i
).to_s
1711 # First argument of the main C function.
1712 private fun native_argc
: Int is intern
1714 # Second argument of the main C function.
1715 private fun native_argv
(i
: Int): NativeString is intern
1718 # Comparator that efficienlty use `to_s` to compare things
1720 # The comparaison call `to_s` on object and use the result to order things.
1722 # var a = [1, 2, 3, 10, 20]
1723 # (new CachedAlphaComparator).sort(a)
1724 # assert a == [1, 10, 2, 20, 3]
1726 # Internally the result of `to_s` is cached in a HashMap to counter
1727 # uneficient implementation of `to_s`.
1729 # Note: it caching is not usefull, see `alpha_comparator`
1730 class CachedAlphaComparator
1731 super Comparator[Object]
1733 private var cache
= new HashMap[Object, String]
1735 private fun do_to_s
(a
: Object): String do
1736 if cache
.has_key
(a
) then return cache
[a
]
1742 redef fun compare
(a
, b
) do
1743 return do_to_s
(a
) <=> do_to_s
(b
)
1747 # see `alpha_comparator`
1748 private class AlphaComparator
1749 super Comparator[Object]
1750 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1753 # Stateless comparator that naively use `to_s` to compare things.
1755 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1756 # on a single instace. See `CachedAlphaComparator` as an alternative.
1758 # var a = [1, 2, 3, 10, 20]
1759 # alpha_comparator.sort(a)
1760 # assert a == [1, 10, 2, 20, 3]
1761 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator