1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
6 # This file is free software, which comes along with NIT. This software is
7 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
8 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
9 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
10 # is kept unaltered, and a notification of the changes is added.
11 # You are allowed to redistribute it and sell it, alone or is a part of
14 # Basic manipulations of strings of characters
18 intrude import collection
# FIXME should be collection::array
24 ###############################################################################
26 ###############################################################################
28 # High-level abstraction for all text representations
33 redef type OTHER: Text
35 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
38 # Gets a view on the chars of the Text object
40 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
41 fun chars
: SequenceRead[Char] is abstract
43 # Number of characters contained in self.
45 # assert "12345".length == 5
46 # assert "".length == 0
47 fun length
: Int is abstract
51 # assert "abcd".substring(1, 2) == "bc"
52 # assert "abcd".substring(-1, 2) == "a"
53 # assert "abcd".substring(1, 0) == ""
54 # assert "abcd".substring(2, 5) == "cd"
56 # A `from` index < 0 will be replaced by 0.
57 # Unless a `count` value is > 0 at the same time.
58 # In this case, `from += count` and `count -= from`.
59 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
61 # Concatenates `o` to `self`
63 # assert "hello" + "world" == "helloworld"
64 # assert "" + "hello" + "" == "hello"
65 fun +(o
: Text): SELFTYPE is abstract
67 # Auto-concatenates self `i` times
69 # assert "abc" * 4 == "abcabcabcabc"
70 # assert "abc" * 1 == "abc"
71 # assert "abc" * 0 == ""
72 fun *(i
: Int): SELFTYPE is abstract
74 # Is the current Text empty (== "")
77 # assert not "foo".is_empty
78 fun is_empty
: Bool do return self.length
== 0
80 # Returns an empty Text of the right type
82 # This method is used internally to get the right
83 # implementation of an empty string.
84 protected fun empty
: SELFTYPE is abstract
86 # Gets the first char of the Text
88 # DEPRECATED : Use self.chars.first instead
89 fun first
: Char do return self.chars
[0]
91 # Access a character at `index` in the string.
93 # assert "abcd"[2] == 'c'
95 # DEPRECATED : Use self.chars.[] instead
96 fun [](index
: Int): Char do return self.chars
[index
]
98 # Gets the index of the first occurence of 'c'
100 # Returns -1 if not found
102 # DEPRECATED : Use self.chars.index_of instead
103 fun index_of
(c
: Char): Int
105 return index_of_from
(c
, 0)
108 # Gets the last char of self
110 # DEPRECATED : Use self.chars.last instead
111 fun last
: Char do return self.chars
[length-1
]
113 # Gets the index of the first occurence of ´c´ starting from ´pos´
115 # Returns -1 if not found
117 # DEPRECATED : Use self.chars.index_of_from instead
118 fun index_of_from
(c
: Char, pos
: Int): Int
120 var iter
= self.chars
.iterator_from
(pos
)
122 if iter
.item
== c
then return iter
.index
127 # Gets the last index of char ´c´
129 # Returns -1 if not found
131 # DEPRECATED : Use self.chars.last_index_of instead
132 fun last_index_of
(c
: Char): Int
134 return last_index_of_from
(c
, length
- 1)
137 # Return a null terminated char *
138 fun to_cstring
: NativeString do return flatten
.to_cstring
140 # The index of the last occurrence of an element starting from pos (in reverse order).
142 # var s = "/etc/bin/test/test.nit"
143 # assert s.last_index_of_from('/', s.length-1) == 13
144 # assert s.last_index_of_from('/', 12) == 8
146 # Returns -1 if not found
148 # DEPRECATED : Use self.chars.last_index_of_from instead
149 fun last_index_of_from
(item
: Char, pos
: Int): Int
151 var iter
= self.chars
.reverse_iterator_from
(pos
)
153 if iter
.item
== item
then return iter
.index
159 # Gets an iterator on the chars of self
161 # DEPRECATED : Use self.chars.iterator instead
162 fun iterator
: Iterator[Char]
164 return self.chars
.iterator
167 # Is 'c' contained in self ?
169 # DEPRECATED : Use self.chars.has instead
170 fun has
(c
: Char): Bool
172 return self.chars
.has
(c
)
175 # Gets an Array containing the chars of self
177 # DEPRECATED : Use self.chars.to_a instead
178 fun to_a
: Array[Char] do return chars
.to_a
180 # Create a substring from `self` beginning at the `from` position
182 # assert "abcd".substring_from(1) == "bcd"
183 # assert "abcd".substring_from(-1) == "abcd"
184 # assert "abcd".substring_from(2) == "cd"
186 # As with substring, a `from` index < 0 will be replaced by 0
187 fun substring_from
(from
: Int): SELFTYPE
189 if from
> self.length
then return empty
190 if from
< 0 then from
= 0
191 return substring
(from
, length
- from
)
194 # Returns a reversed version of self
196 # assert "hello".reversed == "olleh"
197 # assert "bob".reversed == "bob"
198 # assert "".reversed == ""
199 fun reversed
: SELFTYPE is abstract
201 # Does self have a substring `str` starting from position `pos`?
203 # assert "abcd".has_substring("bc",1) == true
204 # assert "abcd".has_substring("bc",2) == false
205 fun has_substring
(str
: String, pos
: Int): Bool
207 var myiter
= self.chars
.iterator_from
(pos
)
208 var itsiter
= str
.chars
.iterator
209 while myiter
.is_ok
and itsiter
.is_ok
do
210 if myiter
.item
!= itsiter
.item
then return false
214 if itsiter
.is_ok
then return false
218 # Is this string prefixed by `prefix`?
220 # assert "abcd".has_prefix("ab") == true
221 # assert "abcbc".has_prefix("bc") == false
222 # assert "ab".has_prefix("abcd") == false
223 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
225 # Is this string suffixed by `suffix`?
227 # assert "abcd".has_suffix("abc") == false
228 # assert "abcd".has_suffix("bcd") == true
229 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
231 # If `self` contains only digits, return the corresponding integer
233 # assert "123".to_i == 123
234 # assert "-1".to_i == -1
238 return to_s
.to_cstring
.atoi
241 # If `self` contains a float, return the corresponding float
243 # assert "123".to_f == 123.0
244 # assert "-1".to_f == -1.0
245 # assert "-1.2e-3".to_f == -0.0012
249 return to_s
.to_cstring
.atof
252 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
254 # assert "ff".to_hex == 255
255 fun to_hex
: Int do return a_to
(16)
257 # If `self` contains only digits and letters, return the corresponding integer in a given base
259 # assert "120".a_to(3) == 15
260 fun a_to
(base
: Int) : Int
287 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
289 # assert "123".is_numeric == true
290 # assert "1.2".is_numeric == true
291 # assert "1,2".is_numeric == true
292 # assert "1..2".is_numeric == false
295 var has_point_or_comma
= false
300 if (i
== '.' or i
== ',') and not has_point_or_comma
302 has_point_or_comma
= true
311 # A upper case version of `self`
313 # assert "Hello World!".to_upper == "HELLO WORLD!"
314 fun to_upper
: SELFTYPE is abstract
316 # A lower case version of `self`
318 # assert "Hello World!".to_lower == "hello world!"
319 fun to_lower
: SELFTYPE is abstract
321 # Removes the whitespaces at the beginning of self
323 # assert " \n\thello \n\t".l_trim == "hello \n\t"
325 # A whitespace is defined as any character which ascii value is less than or equal to 32
328 var iter
= self.chars
.iterator
330 if iter
.item
.ascii
> 32 then break
333 if iter
.index
== length
then return self.empty
334 return self.substring_from
(iter
.index
)
337 # Removes the whitespaces at the end of self
339 # assert " \n\thello \n\t".r_trim == " \n\thello"
341 # A whitespace is defined as any character which ascii value is less than or equal to 32
344 var iter
= self.chars
.reverse_iterator
346 if iter
.item
.ascii
> 32 then break
349 if iter
.index
== length
then return self.empty
350 return self.substring
(0, iter
.index
+ 1)
353 # Trims trailing and preceding white spaces
354 # A whitespace is defined as any character which ascii value is less than or equal to 32
356 # assert " Hello World ! ".trim == "Hello World !"
357 # assert "\na\nb\tc\t".trim == "a\nb\tc"
358 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
360 # Mangle a string to be a unique string only made of alphanumeric characters
361 fun to_cmangle
: String
363 var res
= new FlatBuffer
364 var underscore
= false
365 for c
in self.chars
do
366 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
372 res
.append
('_'.ascii
.to_s
)
375 if c
>= '0' and c
<= '9' then
378 else if c
== '_' then
383 res
.append
(c
.ascii
.to_s
)
391 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
393 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
394 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
395 fun escape_to_c
: String
397 var b
= new FlatBuffer
398 for c
in self.chars
do
401 else if c
== '\0' then
403 else if c
== '"' then
405 else if c == '\'' then
407 else if c == '\\
' then
409 else if c.ascii < 32 then
410 b.append("\\{c.ascii.to_base(8, false)}")
418 # Escape additionnal characters
419 # The result might no be legal in C but be used in other languages
421 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
422 fun escape_more_to_c(chars: String): String
424 var b = new FlatBuffer
425 for c in escape_to_c.chars do
426 if chars.chars.has(c) then
434 # Escape to C plus braces
436 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
437 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
439 # Return a string where Nit escape sequences are transformed.
442 # assert s.length == 2
443 # var u = s.unescape_nit
444 # assert u.length == 1
445 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
446 fun unescape_nit
: String
448 var res
= new FlatBuffer.with_capacity
(self.length
)
449 var was_slash
= false
451 if not was_slash
then
462 else if c
== 'r' then
464 else if c
== 't' then
466 else if c
== '0' then
476 # Two pieces of text are equals if thez have the same characters in the same order.
478 # assert "hello" == "hello"
479 # assert "hello" != "HELLO"
480 # assert "hello" == "hel"+"lo"
482 # Things that are not Text are not equal.
485 # assert "9" != ['9']
488 # assert "9".chars.first == '9' # equality of Char
489 # assert "9".chars == ['9'] # equality of Sequence
490 # assert "9".to_i == 9 # equality of Int
493 if o
== null then return false
494 if not o
isa Text then return false
495 if self.is_same_instance
(o
) then return true
496 if self.length
!= o
.length
then return false
497 return self.chars
== o
.chars
500 # Lexicographical comparaison
502 # assert "abc" < "xy"
503 # assert "ABC" < "abc"
506 var self_chars
= self.chars
.iterator
507 var other_chars
= other
.chars
.iterator
509 while self_chars
.is_ok
and other_chars
.is_ok
do
510 if self_chars
.item
< other_chars
.item
then return true
511 if self_chars
.item
> other_chars
.item
then return false
516 if self_chars
.is_ok
then
523 # Flat representation of self
524 fun flatten
: FlatText is abstract
526 private var hash_cache
: nullable Int = null
530 if hash_cache
== null then
531 # djb2 hash algorithm
535 for char
in self.chars
do
536 h
= (h
* 32) + h
+ char
.ascii
542 return hash_cache
.as(not null)
547 # All kinds of array-based text representations.
548 abstract class FlatText
551 private var items
: NativeString
553 # Real items, used as cache for to_cstring is called
554 private var real_items
: nullable NativeString = null
556 redef var length
: Int
569 redef fun flatten
do return self
572 # Abstract class for the SequenceRead compatible
573 # views on String and Buffer objects
574 private abstract class StringCharView
575 super SequenceRead[Char]
579 private var target
: SELFTYPE
581 private init(tgt
: SELFTYPE)
586 redef fun is_empty
do return target
.is_empty
588 redef fun length
do return target
.length
590 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
592 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
595 # View on Buffer objects, extends Sequence
596 # for mutation operations
597 private abstract class BufferCharView
601 redef type SELFTYPE: Buffer
605 abstract class String
608 redef type SELFTYPE: String
610 redef fun to_s
do return self
614 # Immutable strings of characters.
619 redef type SELFTYPE: FlatString
621 # Index in _items of the start of the string
622 private var index_from
: Int
624 # Indes in _items of the last item of the string
625 private var index_to
: Int
627 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
629 ################################################
630 # AbstractString specific methods #
631 ################################################
635 var native
= calloc_string
(self.length
+ 1)
636 var length
= self.length
637 var items
= self.items
640 while pos
< length
do
641 native
[pos
] = items
[ipos
]
645 return native
.to_s_with_length
(self.length
)
648 redef fun substring
(from
, count
)
654 if count
< 0 then count
= 0
658 var realFrom
= index_from
+ from
660 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
662 if count
== 0 then return empty
664 var to
= realFrom
+ count
- 1
666 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
669 redef fun empty
do return "".as(FlatString)
673 var outstr
= calloc_string
(self.length
+ 1)
676 var myitems
= self.items
677 var index_from
= self.index_from
678 var max
= self.index_to
680 while index_from
<= max
do
681 outstr
[out_index
] = myitems
[index_from
].to_upper
686 outstr
[self.length
] = '\0'
688 return outstr
.to_s_with_length
(self.length
)
693 var outstr
= calloc_string
(self.length
+ 1)
696 var myitems
= self.items
697 var index_from
= self.index_from
698 var max
= self.index_to
700 while index_from
<= max
do
701 outstr
[out_index
] = myitems
[index_from
].to_lower
706 outstr
[self.length
] = '\0'
708 return outstr
.to_s_with_length
(self.length
)
713 var i
= self.index_from
714 var imax
= self.index_to
721 ##################################################
722 # String Specific Methods #
723 ##################################################
725 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
733 redef fun to_cstring
: NativeString
735 if real_items
!= null then return real_items
.as(not null)
736 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
737 var newItems
= calloc_string
(length
+ 1)
738 self.items
.copy_to
(newItems
, length
, index_from
, 0)
739 newItems
[length
] = '\0'
740 self.real_items
= newItems
748 if not other
isa FlatString then return super
750 if self.object_id
== other
.object_id
then return true
752 var my_length
= length
754 if other
.length
!= my_length
then return false
756 var my_index
= index_from
757 var its_index
= other
.index_from
759 var last_iteration
= my_index
+ my_length
761 var itsitems
= other
.items
762 var myitems
= self.items
764 while my_index
< last_iteration
do
765 if myitems
[my_index
] != itsitems
[its_index
] then return false
775 if not other
isa FlatString then return super
777 if self.object_id
== other
.object_id
then return false
779 var my_curr_char
: Char
780 var its_curr_char
: Char
782 var curr_id_self
= self.index_from
783 var curr_id_other
= other
.index_from
785 var my_items
= self.items
786 var its_items
= other
.items
788 var my_length
= self.length
789 var its_length
= other
.length
791 var max_iterations
= curr_id_self
+ my_length
793 while curr_id_self
< max_iterations
do
794 my_curr_char
= my_items
[curr_id_self
]
795 its_curr_char
= its_items
[curr_id_other
]
797 if my_curr_char
!= its_curr_char
then
798 if my_curr_char
< its_curr_char
then return true
806 return my_length
< its_length
811 var my_length
= self.length
812 var its_length
= s
.length
814 var total_length
= my_length
+ its_length
816 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
818 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
819 if s
isa FlatString then
820 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
821 else if s
isa FlatBuffer then
822 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
824 var curr_pos
= my_length
826 target_string
[curr_pos
] = i
831 target_string
[total_length
] = '\0'
833 return target_string
.to_s_with_length
(total_length
)
840 var my_length
= self.length
842 var final_length
= my_length
* i
844 var my_items
= self.items
846 var target_string
= calloc_string
((final_length
) + 1)
848 target_string
[final_length
] = '\0'
852 for iteration
in [1 .. i
] do
853 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
854 current_last
+= my_length
857 return target_string
.to_s_with_length
(final_length
)
862 if hash_cache
== null then
863 # djb2 hash algorythm
868 var strStart
= index_from
872 while i
>= strStart
do
873 h
= (h
* 32) + h
+ self.items
[i
].ascii
880 return hash_cache
.as(not null)
884 private class FlatStringReverseIterator
885 super IndexedIterator[Char]
887 var target
: FlatString
889 var target_items
: NativeString
893 init with_pos
(tgt
: FlatString, pos
: Int)
896 target_items
= tgt
.items
897 curr_pos
= pos
+ tgt
.index_from
900 redef fun is_ok
do return curr_pos
>= 0
902 redef fun item
do return target_items
[curr_pos
]
904 redef fun next
do curr_pos
-= 1
906 redef fun index
do return curr_pos
- target
.index_from
910 private class FlatStringIterator
911 super IndexedIterator[Char]
913 var target
: FlatString
915 var target_items
: NativeString
919 init with_pos
(tgt
: FlatString, pos
: Int)
922 target_items
= tgt
.items
923 curr_pos
= pos
+ target
.index_from
926 redef fun is_ok
do return curr_pos
<= target
.index_to
928 redef fun item
do return target_items
[curr_pos
]
930 redef fun next
do curr_pos
+= 1
932 redef fun index
do return curr_pos
- target
.index_from
936 private class FlatStringCharView
939 redef type SELFTYPE: FlatString
943 # Check that the index (+ index_from) is not larger than indexTo
944 # In other terms, if the index is valid
946 var target
= self.target
947 assert (index
+ target
.index_from
) <= target
.index_to
948 return target
.items
[index
+ target
.index_from
]
951 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
953 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
957 abstract class Buffer
960 redef type SELFTYPE: Buffer
962 # Specific implementations MUST set this to `true` in order to invalidate caches
963 protected var is_dirty
= true
965 # Modifies the char contained at pos `index`
967 # DEPRECATED : Use self.chars.[]= instead
968 fun []=(index
: Int, item
: Char) is abstract
970 # Adds a char `c` at the end of self
972 # DEPRECATED : Use self.chars.add instead
973 fun add
(c
: Char) is abstract
977 # var b = new FlatBuffer
979 # assert not b.is_empty
982 fun clear
is abstract
984 # Enlarges the subsequent array containing the chars of self
985 fun enlarge
(cap
: Int) is abstract
987 # Adds the content of text `s` at the end of self
989 # var b = new FlatBuffer
992 # assert b == "helloworld"
993 fun append
(s
: Text) is abstract
997 if is_dirty
then hash_cache
= null
1001 # In Buffers, the internal sequence of character is mutable
1002 # Thus, `chars` can be used to modify the buffer.
1003 redef fun chars
: Sequence[Char] is abstract
1006 # Mutable strings of characters.
1011 redef type SELFTYPE: FlatBuffer
1013 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1015 private var capacity
: Int
1017 redef fun []=(index
, item
)
1020 if index
== length
then
1024 assert index
>= 0 and index
< length
1031 if capacity
<= length
then enlarge
(length
+ 5)
1041 redef fun empty
do return new FlatBuffer
1043 redef fun enlarge
(cap
)
1047 if cap
<= c
then return
1048 while c
<= cap
do c
= c
* 2 + 2
1049 var a
= calloc_string
(c
+1)
1050 items
.copy_to
(a
, length
, 0, 0)
1053 items
.copy_to
(a
, length
, 0, 0)
1056 redef fun to_s
: String
1058 return to_cstring
.to_s_with_length
(length
)
1061 redef fun to_cstring
1064 var new_native
= calloc_string
(length
+ 1)
1065 new_native
[length
] = '\0'
1066 items
.copy_to
(new_native
, length
, 0, 0)
1067 real_items
= new_native
1070 return real_items
.as(not null)
1073 # Create a new empty string.
1074 init do with_capacity
(5)
1078 capacity
= s
.length
+ 1
1080 items
= calloc_string
(capacity
)
1081 if s
isa FlatString then
1082 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1083 else if s
isa FlatBuffer then
1084 s
.items
.copy_to
(items
, length
, 0, 0)
1094 # Create a new empty string with a given capacity.
1095 init with_capacity
(cap
: Int)
1098 # _items = new NativeString.calloc(cap)
1099 items
= calloc_string
(cap
+1)
1108 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1109 if s
isa FlatString then
1110 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1111 else if s
isa FlatBuffer then
1112 s
.items
.copy_to
(items
, sl
, 0, length
)
1114 var curr_pos
= self.length
1123 # Copies the content of self in `dest`
1124 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1126 var self_chars
= self.chars
1127 var dest_chars
= dest
.chars
1128 for i
in [0..len-1
] do
1129 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1133 redef fun substring
(from
, count
)
1137 if from
< 0 then from
= 0
1138 if count
> length
then count
= length
1139 if from
< count
then
1140 var r
= new FlatBuffer.with_capacity
(count
- from
)
1141 while from
< count
do
1142 r
.chars
.push
(items
[from
])
1147 return new FlatBuffer
1153 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1154 var reviter
= self.chars
.reverse_iterator
1155 while reviter
.is_ok
do
1156 new_buf
.add
(reviter
.item
)
1164 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1165 new_buf
.append
(self)
1166 new_buf
.append
(other
)
1170 redef fun *(repeats
)
1172 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1173 for i
in [0..repeats
[ do
1174 new_buf
.append
(self)
1180 private class FlatBufferReverseIterator
1181 super IndexedIterator[Char]
1183 var target
: FlatBuffer
1185 var target_items
: NativeString
1189 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1192 target_items
= tgt
.items
1196 redef fun index
do return curr_pos
1198 redef fun is_ok
do return curr_pos
>= 0
1200 redef fun item
do return target_items
[curr_pos
]
1202 redef fun next
do curr_pos
-= 1
1206 private class FlatBufferCharView
1207 super BufferCharView
1210 redef type SELFTYPE: FlatBuffer
1212 redef fun [](index
) do return target
.items
[index
]
1214 redef fun []=(index
, item
)
1216 assert index
>= 0 and index
<= length
1217 if index
== length
then
1221 target
.items
[index
] = item
1234 fun enlarge
(cap
: Int)
1241 var my_items
= target
.items
1242 var s_length
= s
.length
1243 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1246 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1248 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1252 private class FlatBufferIterator
1253 super IndexedIterator[Char]
1255 var target
: FlatBuffer
1257 var target_items
: NativeString
1261 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1264 target_items
= tgt
.items
1268 redef fun index
do return curr_pos
1270 redef fun is_ok
do return curr_pos
< target
.length
1272 redef fun item
do return target_items
[curr_pos
]
1274 redef fun next
do curr_pos
+= 1
1278 ###############################################################################
1280 ###############################################################################
1283 # User readable representation of `self`.
1284 fun to_s
: String do return inspect
1286 # The class name of the object in NativeString format.
1287 private fun native_class_name
: NativeString is intern
1289 # The class name of the object.
1291 # assert 5.class_name == "Int"
1292 fun class_name
: String do return native_class_name
.to_s
1294 # Developer readable representation of `self`.
1295 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1298 return "<{inspect_head}>"
1301 # Return "CLASSNAME:#OBJECTID".
1302 # This function is mainly used with the redefinition of the inspect method
1303 protected fun inspect_head
: String
1305 return "{class_name}:#{object_id.to_hex}"
1308 protected fun args
: Sequence[String]
1315 # assert true.to_s == "true"
1316 # assert false.to_s == "false"
1328 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1329 # assume < to_c max const of char
1330 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1337 else if self == 0 then
1344 var pos
= digit_count
(base
) - 1
1345 while pos
>= 0 and n
> 0 do
1346 s
.chars
[pos
] = (n
% base
).to_c
1352 # C function to convert an nit Int to a NativeString (char*)
1353 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1355 # return displayable int in base 10 and signed
1357 # assert 1.to_s == "1"
1358 # assert (-123).to_s == "-123"
1360 var len
= digit_count
(10)
1361 return native_int_to_s
(len
).to_s_with_length
(len
)
1364 # return displayable int in hexadecimal
1366 # assert 1.to_hex == "1"
1367 # assert (-255).to_hex == "-ff"
1368 fun to_hex
: String do return to_base
(16,false)
1370 # return displayable int in base base and signed
1371 fun to_base
(base
: Int, signed
: Bool): String
1373 var l
= digit_count
(base
)
1374 var s
= new FlatBuffer.from
(" " * l
)
1375 fill_buffer
(s
, base
, signed
)
1381 # Pretty print self, print needoed decimals up to a max of 3.
1383 # assert 12.34.to_s == "12.34"
1384 # assert (-0120.03450).to_s == "-120.035"
1386 # see `to_precision` for a different precision.
1388 var str
= to_precision
( 3 )
1389 if is_inf
!= 0 or is_nan
then return str
1390 var len
= str
.length
1391 for i
in [0..len-1
] do
1393 var c
= str
.chars
[j
]
1396 else if c
== '.' then
1397 return str
.substring
( 0, j
+2 )
1399 return str
.substring
( 0, j
+1 )
1405 # `self` representation with `nb` digits after the '.'.
1407 # assert 12.345.to_precision(1) == "12.3"
1408 # assert 12.345.to_precision(2) == "12.35"
1409 # assert 12.345.to_precision(3) == "12.345"
1410 # assert 12.345.to_precision(4) == "12.3450"
1411 fun to_precision
(nb
: Int): String
1413 if is_nan
then return "nan"
1415 var isinf
= self.is_inf
1418 else if isinf
== -1 then
1422 if nb
== 0 then return self.to_i
.to_s
1424 for i
in [0..nb
[ do f
= f
* 10.0
1431 if i
== 0 then return "0.0"
1435 var p1
= s
.substring
(0, s
.length-nb
)
1436 var p2
= s
.substring
(s
.length-nb
, nb
)
1437 return p1
+ "." + p2
1439 return "0." + ("0"*(nb-sl
)) + s
1443 # `self` representation with `nb` digits after the '.'.
1445 # assert 12.345.to_precision_native(1) == "12.3"
1446 # assert 12.345.to_precision_native(2) == "12.35"
1447 # assert 12.345.to_precision_native(3) == "12.345"
1448 # assert 12.345.to_precision_native(4) == "12.3450"
1449 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1453 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1454 str = malloc(size + 1);
1455 sprintf(str, "%.*f", (int)nb, recv );
1457 return NativeString_to_s( str );
1462 # assert 'x'.to_s == "x"
1465 var s
= new FlatBuffer.with_capacity
(1)
1470 # Returns true if the char is a numerical digit
1472 # assert '0'.is_numeric
1473 # assert '9'.is_numeric
1474 # assert not 'a'.is_numeric
1475 # assert not '?'.is_numeric
1476 fun is_numeric
: Bool
1478 return self >= '0' and self <= '9'
1481 # Returns true if the char is an alpha digit
1483 # assert 'a'.is_alpha
1484 # assert 'Z'.is_alpha
1485 # assert not '0'.is_alpha
1486 # assert not '?'.is_alpha
1489 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1492 # Returns true if the char is an alpha or a numeric digit
1494 # assert 'a'.is_alphanumeric
1495 # assert 'Z'.is_alphanumeric
1496 # assert '0'.is_alphanumeric
1497 # assert '9'.is_alphanumeric
1498 # assert not '?'.is_alphanumeric
1499 fun is_alphanumeric
: Bool
1501 return self.is_numeric
or self.is_alpha
1505 redef class Collection[E
]
1506 # Concatenate elements.
1509 var s
= new FlatBuffer
1510 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1514 # Concatenate and separate each elements with `sep`.
1516 # assert [1, 2, 3].join(":") == "1:2:3"
1517 # assert [1..3].join(":") == "1:2:3"
1518 fun join
(sep
: Text): String
1520 if is_empty
then return ""
1522 var s
= new FlatBuffer # Result
1527 if e
!= null then s
.append
(e
.to_s
)
1529 # Concat other items
1534 if e
!= null then s
.append
(e
.to_s
)
1541 redef class Array[E
]
1542 # Fast implementation
1545 var s
= new FlatBuffer
1550 if e
!= null then s
.append
(e
.to_s
)
1557 redef class Map[K
,V
]
1558 # Concatenate couple of 'key value'.
1559 # key and value are separated by `couple_sep`.
1560 # each couple is separated each couple with `sep`.
1562 # var m = new ArrayMap[Int, String]
1565 # assert m.join("; ", "=") == "1=one; 10=ten"
1566 fun join
(sep
: String, couple_sep
: String): String
1568 if is_empty
then return ""
1570 var s
= new FlatBuffer # Result
1576 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1578 # Concat other items
1584 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1591 ###############################################################################
1593 ###############################################################################
1595 # Native strings are simple C char *
1599 fun [](index
: Int): Char is intern
1600 fun []=(index
: Int, item
: Char) is intern
1601 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1603 # Position of the first nul character.
1604 fun cstring_length
: Int
1607 while self[l
] != '\0' do l
+= 1
1610 fun atoi
: Int is intern
1611 fun atof
: Float is extern "atof"
1615 return to_s_with_length
(cstring_length
)
1618 fun to_s_with_length
(length
: Int): FlatString
1621 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1624 fun to_s_with_copy
: FlatString
1626 var length
= cstring_length
1627 var new_self
= calloc_string
(length
+ 1)
1628 copy_to
(new_self
, length
, 0, 0)
1629 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1634 # StringCapable objects can create native strings
1635 interface StringCapable
1636 protected fun calloc_string
(size
: Int): NativeString is intern
1640 var _args_cache
: nullable Sequence[String]
1642 redef fun args
: Sequence[String]
1644 if _args_cache
== null then init_args
1645 return _args_cache
.as(not null)
1648 # The name of the program as given by the OS
1649 fun program_name
: String
1651 return native_argv
(0).to_s
1654 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1655 private fun init_args
1657 var argc
= native_argc
1658 var args
= new Array[String].with_capacity
(0)
1661 args
[i-1
] = native_argv
(i
).to_s
1667 # First argument of the main C function.
1668 private fun native_argc
: Int is intern
1670 # Second argument of the main C function.
1671 private fun native_argv
(i
: Int): NativeString is intern
1674 # Comparator that efficienlty use `to_s` to compare things
1676 # The comparaison call `to_s` on object and use the result to order things.
1678 # var a = [1, 2, 3, 10, 20]
1679 # (new CachedAlphaComparator).sort(a)
1680 # assert a == [1, 10, 2, 20, 3]
1682 # Internally the result of `to_s` is cached in a HashMap to counter
1683 # uneficient implementation of `to_s`.
1685 # Note: it caching is not usefull, see `alpha_comparator`
1686 class CachedAlphaComparator
1687 super Comparator[Object]
1689 private var cache
= new HashMap[Object, String]
1691 private fun do_to_s
(a
: Object): String do
1692 if cache
.has_key
(a
) then return cache
[a
]
1698 redef fun compare
(a
, b
) do
1699 return do_to_s
(a
) <=> do_to_s
(b
)
1703 # see `alpha_comparator`
1704 private class AlphaComparator
1705 super Comparator[Object]
1706 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1709 # Stateless comparator that naively use `to_s` to compare things.
1711 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1712 # on a single instace. See `CachedAlphaComparator` as an alternative.
1714 # var a = [1, 2, 3, 10, 20]
1715 # alpha_comparator.sort(a)
1716 # assert a == [1, 10, 2, 20, 3]
1717 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator