638efff972e4b8cf7fe04c8dbe42ee9e15f2eb38
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 # Concatenates `o` to `self`
64 # assert "hello" + "world" == "helloworld"
65 # assert "" + "hello" + "" == "hello"
66 fun +(o
: Text): SELFTYPE is abstract
68 # Auto-concatenates self `i` times
70 # assert "abc" * 4 == "abcabcabcabc"
71 # assert "abc" * 1 == "abc"
72 # assert "abc" * 0 == ""
73 fun *(i
: Int): SELFTYPE is abstract
75 # Is the current Text empty (== "")
78 # assert not "foo".is_empty
79 fun is_empty
: Bool do return self.length
== 0
81 # Returns an empty Text of the right type
83 # This method is used internally to get the right
84 # implementation of an empty string.
85 protected fun empty
: SELFTYPE is abstract
87 # Gets the first char of the Text
89 # DEPRECATED : Use self.chars.first instead
90 fun first
: Char do return self.chars
[0]
92 # Access a character at `index` in the string.
94 # assert "abcd"[2] == 'c'
96 # DEPRECATED : Use self.chars.[] instead
97 fun [](index
: Int): Char do return self.chars
[index
]
99 # Gets the index of the first occurence of 'c'
101 # Returns -1 if not found
103 # DEPRECATED : Use self.chars.index_of instead
104 fun index_of
(c
: Char): Int
106 return index_of_from
(c
, 0)
109 # Gets the last char of self
111 # DEPRECATED : Use self.chars.last instead
112 fun last
: Char do return self.chars
[length-1
]
114 # Gets the index of the first occurence of ´c´ starting from ´pos´
116 # Returns -1 if not found
118 # DEPRECATED : Use self.chars.index_of_from instead
119 fun index_of_from
(c
: Char, pos
: Int): Int
121 var iter
= self.chars
.iterator_from
(pos
)
123 if iter
.item
== c
then return iter
.index
129 # Gets the last index of char ´c´
131 # Returns -1 if not found
133 # DEPRECATED : Use self.chars.last_index_of instead
134 fun last_index_of
(c
: Char): Int
136 return last_index_of_from
(c
, length
- 1)
139 # Return a null terminated char *
140 fun to_cstring
: NativeString do return flatten
.to_cstring
142 # The index of the last occurrence of an element starting from pos (in reverse order).
144 # var s = "/etc/bin/test/test.nit"
145 # assert s.last_index_of_from('/', s.length-1) == 13
146 # assert s.last_index_of_from('/', 12) == 8
148 # Returns -1 if not found
150 # DEPRECATED : Use self.chars.last_index_of_from instead
151 fun last_index_of_from
(item
: Char, pos
: Int): Int
153 var iter
= self.chars
.reverse_iterator_from
(pos
)
155 if iter
.item
== item
then return iter
.index
161 # Gets an iterator on the chars of self
163 # DEPRECATED : Use self.chars.iterator instead
164 fun iterator
: Iterator[Char]
166 return self.chars
.iterator
169 # Is 'c' contained in self ?
171 # DEPRECATED : Use self.chars.has instead
172 fun has
(c
: Char): Bool
174 return self.chars
.has
(c
)
177 # Gets an Array containing the chars of self
179 # DEPRECATED : Use self.chars.to_a instead
180 fun to_a
: Array[Char] do return chars
.to_a
182 # Create a substring from `self` beginning at the `from` position
184 # assert "abcd".substring_from(1) == "bcd"
185 # assert "abcd".substring_from(-1) == "abcd"
186 # assert "abcd".substring_from(2) == "cd"
188 # As with substring, a `from` index < 0 will be replaced by 0
189 fun substring_from
(from
: Int): SELFTYPE
191 if from
> self.length
then return empty
192 if from
< 0 then from
= 0
193 return substring
(from
, length
- from
)
196 # Returns a reversed version of self
198 # assert "hello".reversed == "olleh"
199 # assert "bob".reversed == "bob"
200 # assert "".reversed == ""
201 fun reversed
: SELFTYPE is abstract
203 # Does self have a substring `str` starting from position `pos`?
205 # assert "abcd".has_substring("bc",1) == true
206 # assert "abcd".has_substring("bc",2) == false
207 fun has_substring
(str
: String, pos
: Int): Bool
209 var myiter
= self.chars
.iterator_from
(pos
)
210 var itsiter
= str
.chars
.iterator
211 while myiter
.is_ok
and itsiter
.is_ok
do
212 if myiter
.item
!= itsiter
.item
then return false
216 if itsiter
.is_ok
then return false
220 # Is this string prefixed by `prefix`?
222 # assert "abcd".has_prefix("ab") == true
223 # assert "abcbc".has_prefix("bc") == false
224 # assert "ab".has_prefix("abcd") == false
225 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
227 # Is this string suffixed by `suffix`?
229 # assert "abcd".has_suffix("abc") == false
230 # assert "abcd".has_suffix("bcd") == true
231 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
233 # If `self` contains only digits, return the corresponding integer
235 # assert "123".to_i == 123
236 # assert "-1".to_i == -1
240 return to_s
.to_cstring
.atoi
243 # If `self` contains a float, return the corresponding float
245 # assert "123".to_f == 123.0
246 # assert "-1".to_f == -1.0
247 # assert "-1.2e-3".to_f == -0.0012
251 return to_s
.to_cstring
.atof
254 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
256 # assert "ff".to_hex == 255
257 fun to_hex
: Int do return a_to
(16)
259 # If `self` contains only digits and letters, return the corresponding integer in a given base
261 # assert "120".a_to(3) == 15
262 fun a_to
(base
: Int) : Int
289 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
291 # assert "123".is_numeric == true
292 # assert "1.2".is_numeric == true
293 # assert "1,2".is_numeric == true
294 # assert "1..2".is_numeric == false
297 var has_point_or_comma
= false
302 if (i
== '.' or i
== ',') and not has_point_or_comma
304 has_point_or_comma
= true
313 # A upper case version of `self`
315 # assert "Hello World!".to_upper == "HELLO WORLD!"
316 fun to_upper
: SELFTYPE is abstract
318 # A lower case version of `self`
320 # assert "Hello World!".to_lower == "hello world!"
321 fun to_lower
: SELFTYPE is abstract
323 # Removes the whitespaces at the beginning of self
325 # assert " \n\thello \n\t".l_trim == "hello \n\t"
327 # A whitespace is defined as any character which ascii value is less than or equal to 32
330 var iter
= self.chars
.iterator
332 if iter
.item
.ascii
> 32 then break
335 if iter
.index
== length
then return self.empty
336 return self.substring_from
(iter
.index
)
339 # Removes the whitespaces at the end of self
341 # assert " \n\thello \n\t".r_trim == " \n\thello"
343 # A whitespace is defined as any character which ascii value is less than or equal to 32
346 var iter
= self.chars
.reverse_iterator
348 if iter
.item
.ascii
> 32 then break
351 if iter
.index
== length
then return self.empty
352 return self.substring
(0, iter
.index
+ 1)
355 # Trims trailing and preceding white spaces
356 # A whitespace is defined as any character which ascii value is less than or equal to 32
358 # assert " Hello World ! ".trim == "Hello World !"
359 # assert "\na\nb\tc\t".trim == "a\nb\tc"
360 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
362 # Mangle a string to be a unique string only made of alphanumeric characters
363 fun to_cmangle
: String
365 var res
= new FlatBuffer
366 var underscore
= false
367 for c
in self.chars
do
368 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
374 res
.append
('_'.ascii
.to_s
)
377 if c
>= '0' and c
<= '9' then
380 else if c
== '_' then
385 res
.append
(c
.ascii
.to_s
)
393 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
395 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
396 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
397 fun escape_to_c
: String
399 var b
= new FlatBuffer
400 for c
in self.chars
do
403 else if c
== '\0' then
405 else if c
== '"' then
407 else if c == '\'' then
409 else if c == '\\
' then
411 else if c.ascii < 32 then
412 b.append("\\{c.ascii.to_base(8, false)}")
420 # Escape additionnal characters
421 # The result might no be legal in C but be used in other languages
423 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
424 fun escape_more_to_c(chars: String): String
426 var b = new FlatBuffer
427 for c in escape_to_c.chars do
428 if chars.chars.has(c) then
436 # Escape to C plus braces
438 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
439 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
441 # Return a string where Nit escape sequences are transformed.
444 # assert s.length == 2
445 # var u = s.unescape_nit
446 # assert u.length == 1
447 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
448 fun unescape_nit
: String
450 var res
= new FlatBuffer.with_capacity
(self.length
)
451 var was_slash
= false
453 if not was_slash
then
464 else if c
== 'r' then
466 else if c
== 't' then
468 else if c
== '0' then
478 # Two pieces of text are equals if thez have the same characters in the same order.
480 # assert "hello" == "hello"
481 # assert "hello" != "HELLO"
482 # assert "hello" == "hel"+"lo"
484 # Things that are not Text are not equal.
487 # assert "9" != ['9']
490 # assert "9".chars.first == '9' # equality of Char
491 # assert "9".chars == ['9'] # equality of Sequence
492 # assert "9".to_i == 9 # equality of Int
495 if o
== null then return false
496 if not o
isa Text then return false
497 if self.is_same_instance
(o
) then return true
498 if self.length
!= o
.length
then return false
499 return self.chars
== o
.chars
502 # Lexicographical comparaison
504 # assert "abc" < "xy"
505 # assert "ABC" < "abc"
508 var self_chars
= self.chars
.iterator
509 var other_chars
= other
.chars
.iterator
511 while self_chars
.is_ok
and other_chars
.is_ok
do
512 if self_chars
.item
< other_chars
.item
then return true
513 if self_chars
.item
> other_chars
.item
then return false
518 if self_chars
.is_ok
then
525 # Flat representation of self
526 fun flatten
: FlatText is abstract
528 private var hash_cache
: nullable Int = null
532 if hash_cache
== null then
533 # djb2 hash algorithm
537 for char
in self.chars
do
538 h
= (h
* 32) + h
+ char
.ascii
544 return hash_cache
.as(not null)
549 # All kinds of array-based text representations.
550 abstract class FlatText
553 private var items
: NativeString
555 # Real items, used as cache for to_cstring is called
556 private var real_items
: nullable NativeString = null
558 redef var length
: Int
571 redef fun flatten
do return self
574 # Abstract class for the SequenceRead compatible
575 # views on String and Buffer objects
576 private abstract class StringCharView
577 super SequenceRead[Char]
581 private var target
: SELFTYPE
583 private init(tgt
: SELFTYPE)
588 redef fun is_empty
do return target
.is_empty
590 redef fun length
do return target
.length
592 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
594 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
597 # View on Buffer objects, extends Sequence
598 # for mutation operations
599 private abstract class BufferCharView
603 redef type SELFTYPE: Buffer
607 abstract class String
610 redef type SELFTYPE: String
612 redef fun to_s
do return self
616 # Immutable strings of characters.
621 redef type SELFTYPE: FlatString
623 # Index in _items of the start of the string
624 private var index_from
: Int
626 # Indes in _items of the last item of the string
627 private var index_to
: Int
629 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
631 ################################################
632 # AbstractString specific methods #
633 ################################################
637 var native
= calloc_string
(self.length
+ 1)
638 var length
= self.length
639 var items
= self.items
642 while pos
< length
do
643 native
[pos
] = items
[ipos
]
647 return native
.to_s_with_length
(self.length
)
650 redef fun substring
(from
, count
)
656 if count
< 0 then count
= 0
660 var realFrom
= index_from
+ from
662 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
664 if count
== 0 then return empty
666 var to
= realFrom
+ count
- 1
668 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
671 redef fun empty
do return "".as(FlatString)
675 var outstr
= calloc_string
(self.length
+ 1)
678 var myitems
= self.items
679 var index_from
= self.index_from
680 var max
= self.index_to
682 while index_from
<= max
do
683 outstr
[out_index
] = myitems
[index_from
].to_upper
688 outstr
[self.length
] = '\0'
690 return outstr
.to_s_with_length
(self.length
)
695 var outstr
= calloc_string
(self.length
+ 1)
698 var myitems
= self.items
699 var index_from
= self.index_from
700 var max
= self.index_to
702 while index_from
<= max
do
703 outstr
[out_index
] = myitems
[index_from
].to_lower
708 outstr
[self.length
] = '\0'
710 return outstr
.to_s_with_length
(self.length
)
715 var i
= self.index_from
716 var imax
= self.index_to
723 ##################################################
724 # String Specific Methods #
725 ##################################################
727 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
735 redef fun to_cstring
: NativeString
737 if real_items
!= null then return real_items
.as(not null)
738 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
739 var newItems
= calloc_string
(length
+ 1)
740 self.items
.copy_to
(newItems
, length
, index_from
, 0)
741 newItems
[length
] = '\0'
742 self.real_items
= newItems
750 if not other
isa FlatString then return super
752 if self.object_id
== other
.object_id
then return true
754 var my_length
= length
756 if other
.length
!= my_length
then return false
758 var my_index
= index_from
759 var its_index
= other
.index_from
761 var last_iteration
= my_index
+ my_length
763 var itsitems
= other
.items
764 var myitems
= self.items
766 while my_index
< last_iteration
do
767 if myitems
[my_index
] != itsitems
[its_index
] then return false
777 if not other
isa FlatString then return super
779 if self.object_id
== other
.object_id
then return false
781 var my_curr_char
: Char
782 var its_curr_char
: Char
784 var curr_id_self
= self.index_from
785 var curr_id_other
= other
.index_from
787 var my_items
= self.items
788 var its_items
= other
.items
790 var my_length
= self.length
791 var its_length
= other
.length
793 var max_iterations
= curr_id_self
+ my_length
795 while curr_id_self
< max_iterations
do
796 my_curr_char
= my_items
[curr_id_self
]
797 its_curr_char
= its_items
[curr_id_other
]
799 if my_curr_char
!= its_curr_char
then
800 if my_curr_char
< its_curr_char
then return true
808 return my_length
< its_length
813 var my_length
= self.length
814 var its_length
= s
.length
816 var total_length
= my_length
+ its_length
818 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
820 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
821 if s
isa FlatString then
822 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
823 else if s
isa FlatBuffer then
824 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
826 var curr_pos
= my_length
828 target_string
[curr_pos
] = i
833 target_string
[total_length
] = '\0'
835 return target_string
.to_s_with_length
(total_length
)
842 var my_length
= self.length
844 var final_length
= my_length
* i
846 var my_items
= self.items
848 var target_string
= calloc_string
((final_length
) + 1)
850 target_string
[final_length
] = '\0'
854 for iteration
in [1 .. i
] do
855 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
856 current_last
+= my_length
859 return target_string
.to_s_with_length
(final_length
)
864 if hash_cache
== null then
865 # djb2 hash algorythm
870 var strStart
= index_from
874 while i
>= strStart
do
875 h
= (h
* 32) + h
+ self.items
[i
].ascii
882 return hash_cache
.as(not null)
886 private class FlatStringReverseIterator
887 super IndexedIterator[Char]
889 var target
: FlatString
891 var target_items
: NativeString
895 init with_pos
(tgt
: FlatString, pos
: Int)
898 target_items
= tgt
.items
899 curr_pos
= pos
+ tgt
.index_from
902 redef fun is_ok
do return curr_pos
>= 0
904 redef fun item
do return target_items
[curr_pos
]
906 redef fun next
do curr_pos
-= 1
908 redef fun index
do return curr_pos
- target
.index_from
912 private class FlatStringIterator
913 super IndexedIterator[Char]
915 var target
: FlatString
917 var target_items
: NativeString
921 init with_pos
(tgt
: FlatString, pos
: Int)
924 target_items
= tgt
.items
925 curr_pos
= pos
+ target
.index_from
928 redef fun is_ok
do return curr_pos
<= target
.index_to
930 redef fun item
do return target_items
[curr_pos
]
932 redef fun next
do curr_pos
+= 1
934 redef fun index
do return curr_pos
- target
.index_from
938 private class FlatStringCharView
941 redef type SELFTYPE: FlatString
945 # Check that the index (+ index_from) is not larger than indexTo
946 # In other terms, if the index is valid
948 var target
= self.target
949 assert (index
+ target
.index_from
) <= target
.index_to
950 return target
.items
[index
+ target
.index_from
]
953 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
955 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
959 abstract class Buffer
962 redef type SELFTYPE: Buffer
964 # Specific implementations MUST set this to `true` in order to invalidate caches
965 protected var is_dirty
= true
967 # Modifies the char contained at pos `index`
969 # DEPRECATED : Use self.chars.[]= instead
970 fun []=(index
: Int, item
: Char) is abstract
972 # Adds a char `c` at the end of self
974 # DEPRECATED : Use self.chars.add instead
975 fun add
(c
: Char) is abstract
979 # var b = new FlatBuffer
981 # assert not b.is_empty
984 fun clear
is abstract
986 # Enlarges the subsequent array containing the chars of self
987 fun enlarge
(cap
: Int) is abstract
989 # Adds the content of text `s` at the end of self
991 # var b = new FlatBuffer
994 # assert b == "helloworld"
995 fun append
(s
: Text) is abstract
999 if is_dirty
then hash_cache
= null
1003 # In Buffers, the internal sequence of character is mutable
1004 # Thus, `chars` can be used to modify the buffer.
1005 redef fun chars
: Sequence[Char] is abstract
1008 # Mutable strings of characters.
1013 redef type SELFTYPE: FlatBuffer
1015 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1017 private var capacity
: Int
1019 redef fun []=(index
, item
)
1022 if index
== length
then
1026 assert index
>= 0 and index
< length
1033 if capacity
<= length
then enlarge
(length
+ 5)
1043 redef fun empty
do return new FlatBuffer
1045 redef fun enlarge
(cap
)
1049 if cap
<= c
then return
1050 while c
<= cap
do c
= c
* 2 + 2
1051 var a
= calloc_string
(c
+1)
1052 items
.copy_to
(a
, length
, 0, 0)
1055 items
.copy_to
(a
, length
, 0, 0)
1058 redef fun to_s
: String
1060 return to_cstring
.to_s_with_length
(length
)
1063 redef fun to_cstring
1066 var new_native
= calloc_string
(length
+ 1)
1067 new_native
[length
] = '\0'
1068 items
.copy_to
(new_native
, length
, 0, 0)
1069 real_items
= new_native
1072 return real_items
.as(not null)
1075 # Create a new empty string.
1076 init do with_capacity
(5)
1080 capacity
= s
.length
+ 1
1082 items
= calloc_string
(capacity
)
1083 if s
isa FlatString then
1084 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1085 else if s
isa FlatBuffer then
1086 s
.items
.copy_to
(items
, length
, 0, 0)
1096 # Create a new empty string with a given capacity.
1097 init with_capacity
(cap
: Int)
1100 # _items = new NativeString.calloc(cap)
1101 items
= calloc_string
(cap
+1)
1110 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1111 if s
isa FlatString then
1112 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1113 else if s
isa FlatBuffer then
1114 s
.items
.copy_to
(items
, sl
, 0, length
)
1116 var curr_pos
= self.length
1125 # Copies the content of self in `dest`
1126 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1128 var self_chars
= self.chars
1129 var dest_chars
= dest
.chars
1130 for i
in [0..len-1
] do
1131 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1135 redef fun substring
(from
, count
)
1139 if from
< 0 then from
= 0
1140 if count
> length
then count
= length
1141 if from
< count
then
1142 var r
= new FlatBuffer.with_capacity
(count
- from
)
1143 while from
< count
do
1144 r
.chars
.push
(items
[from
])
1149 return new FlatBuffer
1155 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1156 var reviter
= self.chars
.reverse_iterator
1157 while reviter
.is_ok
do
1158 new_buf
.add
(reviter
.item
)
1166 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1167 new_buf
.append
(self)
1168 new_buf
.append
(other
)
1172 redef fun *(repeats
)
1174 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1175 for i
in [0..repeats
[ do
1176 new_buf
.append
(self)
1182 private class FlatBufferReverseIterator
1183 super IndexedIterator[Char]
1185 var target
: FlatBuffer
1187 var target_items
: NativeString
1191 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1194 target_items
= tgt
.items
1198 redef fun index
do return curr_pos
1200 redef fun is_ok
do return curr_pos
>= 0
1202 redef fun item
do return target_items
[curr_pos
]
1204 redef fun next
do curr_pos
-= 1
1208 private class FlatBufferCharView
1209 super BufferCharView
1212 redef type SELFTYPE: FlatBuffer
1214 redef fun [](index
) do return target
.items
[index
]
1216 redef fun []=(index
, item
)
1218 assert index
>= 0 and index
<= length
1219 if index
== length
then
1223 target
.items
[index
] = item
1236 fun enlarge
(cap
: Int)
1243 var my_items
= target
.items
1244 var s_length
= s
.length
1245 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1248 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1250 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1254 private class FlatBufferIterator
1255 super IndexedIterator[Char]
1257 var target
: FlatBuffer
1259 var target_items
: NativeString
1263 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1266 target_items
= tgt
.items
1270 redef fun index
do return curr_pos
1272 redef fun is_ok
do return curr_pos
< target
.length
1274 redef fun item
do return target_items
[curr_pos
]
1276 redef fun next
do curr_pos
+= 1
1280 ###############################################################################
1282 ###############################################################################
1285 # User readable representation of `self`.
1286 fun to_s
: String do return inspect
1288 # The class name of the object in NativeString format.
1289 private fun native_class_name
: NativeString is intern
1291 # The class name of the object.
1293 # assert 5.class_name == "Int"
1294 fun class_name
: String do return native_class_name
.to_s
1296 # Developer readable representation of `self`.
1297 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1300 return "<{inspect_head}>"
1303 # Return "CLASSNAME:#OBJECTID".
1304 # This function is mainly used with the redefinition of the inspect method
1305 protected fun inspect_head
: String
1307 return "{class_name}:#{object_id.to_hex}"
1310 protected fun args
: Sequence[String]
1317 # assert true.to_s == "true"
1318 # assert false.to_s == "false"
1331 # Wrapper of strerror C function
1332 private fun strerror_ext
: NativeString is extern `{
1333 return strerror(recv);
1336 # Returns a string describing error number
1337 fun strerror
: String do return strerror_ext
.to_s
1339 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1340 # assume < to_c max const of char
1341 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1348 else if self == 0 then
1355 var pos
= digit_count
(base
) - 1
1356 while pos
>= 0 and n
> 0 do
1357 s
.chars
[pos
] = (n
% base
).to_c
1363 # C function to convert an nit Int to a NativeString (char*)
1364 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1366 # return displayable int in base 10 and signed
1368 # assert 1.to_s == "1"
1369 # assert (-123).to_s == "-123"
1371 var len
= digit_count
(10)
1372 return native_int_to_s
(len
).to_s_with_length
(len
)
1375 # return displayable int in hexadecimal
1377 # assert 1.to_hex == "1"
1378 # assert (-255).to_hex == "-ff"
1379 fun to_hex
: String do return to_base
(16,false)
1381 # return displayable int in base base and signed
1382 fun to_base
(base
: Int, signed
: Bool): String
1384 var l
= digit_count
(base
)
1385 var s
= new FlatBuffer.from
(" " * l
)
1386 fill_buffer
(s
, base
, signed
)
1392 # Pretty print self, print needoed decimals up to a max of 3.
1394 # assert 12.34.to_s == "12.34"
1395 # assert (-0120.03450).to_s == "-120.035"
1397 # see `to_precision` for a different precision.
1399 var str
= to_precision
( 3 )
1400 if is_inf
!= 0 or is_nan
then return str
1401 var len
= str
.length
1402 for i
in [0..len-1
] do
1404 var c
= str
.chars
[j
]
1407 else if c
== '.' then
1408 return str
.substring
( 0, j
+2 )
1410 return str
.substring
( 0, j
+1 )
1416 # `self` representation with `nb` digits after the '.'.
1418 # assert 12.345.to_precision(1) == "12.3"
1419 # assert 12.345.to_precision(2) == "12.35"
1420 # assert 12.345.to_precision(3) == "12.345"
1421 # assert 12.345.to_precision(4) == "12.3450"
1422 fun to_precision
(nb
: Int): String
1424 if is_nan
then return "nan"
1426 var isinf
= self.is_inf
1429 else if isinf
== -1 then
1433 if nb
== 0 then return self.to_i
.to_s
1435 for i
in [0..nb
[ do f
= f
* 10.0
1442 if i
== 0 then return "0.0"
1446 var p1
= s
.substring
(0, s
.length-nb
)
1447 var p2
= s
.substring
(s
.length-nb
, nb
)
1448 return p1
+ "." + p2
1450 return "0." + ("0"*(nb-sl
)) + s
1454 # `self` representation with `nb` digits after the '.'.
1456 # assert 12.345.to_precision_native(1) == "12.3"
1457 # assert 12.345.to_precision_native(2) == "12.35"
1458 # assert 12.345.to_precision_native(3) == "12.345"
1459 # assert 12.345.to_precision_native(4) == "12.3450"
1460 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1464 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1465 str = malloc(size + 1);
1466 sprintf(str, "%.*f", (int)nb, recv );
1468 return NativeString_to_s( str );
1473 # assert 'x'.to_s == "x"
1476 var s
= new FlatBuffer.with_capacity
(1)
1481 # Returns true if the char is a numerical digit
1483 # assert '0'.is_numeric
1484 # assert '9'.is_numeric
1485 # assert not 'a'.is_numeric
1486 # assert not '?'.is_numeric
1487 fun is_numeric
: Bool
1489 return self >= '0' and self <= '9'
1492 # Returns true if the char is an alpha digit
1494 # assert 'a'.is_alpha
1495 # assert 'Z'.is_alpha
1496 # assert not '0'.is_alpha
1497 # assert not '?'.is_alpha
1500 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1503 # Returns true if the char is an alpha or a numeric digit
1505 # assert 'a'.is_alphanumeric
1506 # assert 'Z'.is_alphanumeric
1507 # assert '0'.is_alphanumeric
1508 # assert '9'.is_alphanumeric
1509 # assert not '?'.is_alphanumeric
1510 fun is_alphanumeric
: Bool
1512 return self.is_numeric
or self.is_alpha
1516 redef class Collection[E
]
1517 # Concatenate elements.
1520 var s
= new FlatBuffer
1521 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1525 # Concatenate and separate each elements with `sep`.
1527 # assert [1, 2, 3].join(":") == "1:2:3"
1528 # assert [1..3].join(":") == "1:2:3"
1529 fun join
(sep
: Text): String
1531 if is_empty
then return ""
1533 var s
= new FlatBuffer # Result
1538 if e
!= null then s
.append
(e
.to_s
)
1540 # Concat other items
1545 if e
!= null then s
.append
(e
.to_s
)
1552 redef class Array[E
]
1553 # Fast implementation
1556 var s
= new FlatBuffer
1561 if e
!= null then s
.append
(e
.to_s
)
1568 redef class Map[K
,V
]
1569 # Concatenate couple of 'key value'.
1570 # key and value are separated by `couple_sep`.
1571 # each couple is separated each couple with `sep`.
1573 # var m = new ArrayMap[Int, String]
1576 # assert m.join("; ", "=") == "1=one; 10=ten"
1577 fun join
(sep
: String, couple_sep
: String): String
1579 if is_empty
then return ""
1581 var s
= new FlatBuffer # Result
1587 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1589 # Concat other items
1595 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1602 ###############################################################################
1604 ###############################################################################
1606 # Native strings are simple C char *
1610 fun [](index
: Int): Char is intern
1611 fun []=(index
: Int, item
: Char) is intern
1612 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1614 # Position of the first nul character.
1615 fun cstring_length
: Int
1618 while self[l
] != '\0' do l
+= 1
1621 fun atoi
: Int is intern
1622 fun atof
: Float is extern "atof"
1626 return to_s_with_length
(cstring_length
)
1629 fun to_s_with_length
(length
: Int): FlatString
1632 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1635 fun to_s_with_copy
: FlatString
1637 var length
= cstring_length
1638 var new_self
= calloc_string
(length
+ 1)
1639 copy_to
(new_self
, length
, 0, 0)
1640 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1645 # StringCapable objects can create native strings
1646 interface StringCapable
1647 protected fun calloc_string
(size
: Int): NativeString is intern
1651 var _args_cache
: nullable Sequence[String]
1653 redef fun args
: Sequence[String]
1655 if _args_cache
== null then init_args
1656 return _args_cache
.as(not null)
1659 # The name of the program as given by the OS
1660 fun program_name
: String
1662 return native_argv
(0).to_s
1665 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1666 private fun init_args
1668 var argc
= native_argc
1669 var args
= new Array[String].with_capacity
(0)
1672 args
[i-1
] = native_argv
(i
).to_s
1678 # First argument of the main C function.
1679 private fun native_argc
: Int is intern
1681 # Second argument of the main C function.
1682 private fun native_argv
(i
: Int): NativeString is intern
1685 # Comparator that efficienlty use `to_s` to compare things
1687 # The comparaison call `to_s` on object and use the result to order things.
1689 # var a = [1, 2, 3, 10, 20]
1690 # (new CachedAlphaComparator).sort(a)
1691 # assert a == [1, 10, 2, 20, 3]
1693 # Internally the result of `to_s` is cached in a HashMap to counter
1694 # uneficient implementation of `to_s`.
1696 # Note: it caching is not usefull, see `alpha_comparator`
1697 class CachedAlphaComparator
1698 super Comparator[Object]
1700 private var cache
= new HashMap[Object, String]
1702 private fun do_to_s
(a
: Object): String do
1703 if cache
.has_key
(a
) then return cache
[a
]
1709 redef fun compare
(a
, b
) do
1710 return do_to_s
(a
) <=> do_to_s
(b
)
1714 # see `alpha_comparator`
1715 private class AlphaComparator
1716 super Comparator[Object]
1717 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1720 # Stateless comparator that naively use `to_s` to compare things.
1722 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1723 # on a single instace. See `CachedAlphaComparator` as an alternative.
1725 # var a = [1, 2, 3, 10, 20]
1726 # alpha_comparator.sort(a)
1727 # assert a == [1, 10, 2, 20, 3]
1728 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator