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
128 # Gets the last index of char ´c´
130 # Returns -1 if not found
132 # DEPRECATED : Use self.chars.last_index_of instead
133 fun last_index_of
(c
: Char): Int
135 return last_index_of_from
(c
, length
- 1)
138 # Return a null terminated char *
139 fun to_cstring
: NativeString do return flatten
.to_cstring
141 # The index of the last occurrence of an element starting from pos (in reverse order).
143 # var s = "/etc/bin/test/test.nit"
144 # assert s.last_index_of_from('/', s.length-1) == 13
145 # assert s.last_index_of_from('/', 12) == 8
147 # Returns -1 if not found
149 # DEPRECATED : Use self.chars.last_index_of_from instead
150 fun last_index_of_from
(item
: Char, pos
: Int): Int
152 var iter
= self.chars
.reverse_iterator_from
(pos
)
154 if iter
.item
== item
then return iter
.index
160 # Gets an iterator on the chars of self
162 # DEPRECATED : Use self.chars.iterator instead
163 fun iterator
: Iterator[Char]
165 return self.chars
.iterator
168 # Is 'c' contained in self ?
170 # DEPRECATED : Use self.chars.has instead
171 fun has
(c
: Char): Bool
173 return self.chars
.has
(c
)
176 # Gets an Array containing the chars of self
178 # DEPRECATED : Use self.chars.to_a instead
179 fun to_a
: Array[Char] do return chars
.to_a
181 # Create a substring from `self` beginning at the `from` position
183 # assert "abcd".substring_from(1) == "bcd"
184 # assert "abcd".substring_from(-1) == "abcd"
185 # assert "abcd".substring_from(2) == "cd"
187 # As with substring, a `from` index < 0 will be replaced by 0
188 fun substring_from
(from
: Int): SELFTYPE
190 if from
> self.length
then return empty
191 if from
< 0 then from
= 0
192 return substring
(from
, length
- from
)
195 # Returns a reversed version of self
197 # assert "hello".reversed == "olleh"
198 # assert "bob".reversed == "bob"
199 # assert "".reversed == ""
200 fun reversed
: SELFTYPE is abstract
202 # Does self have a substring `str` starting from position `pos`?
204 # assert "abcd".has_substring("bc",1) == true
205 # assert "abcd".has_substring("bc",2) == false
206 fun has_substring
(str
: String, pos
: Int): Bool
208 var myiter
= self.chars
.iterator_from
(pos
)
209 var itsiter
= str
.chars
.iterator
210 while myiter
.is_ok
and itsiter
.is_ok
do
211 if myiter
.item
!= itsiter
.item
then return false
215 if itsiter
.is_ok
then return false
219 # Is this string prefixed by `prefix`?
221 # assert "abcd".has_prefix("ab") == true
222 # assert "abcbc".has_prefix("bc") == false
223 # assert "ab".has_prefix("abcd") == false
224 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
226 # Is this string suffixed by `suffix`?
228 # assert "abcd".has_suffix("abc") == false
229 # assert "abcd".has_suffix("bcd") == true
230 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
232 # If `self` contains only digits, return the corresponding integer
234 # assert "123".to_i == 123
235 # assert "-1".to_i == -1
239 return to_s
.to_cstring
.atoi
242 # If `self` contains a float, return the corresponding float
244 # assert "123".to_f == 123.0
245 # assert "-1".to_f == -1.0
246 # assert "-1.2e-3".to_f == -0.0012
250 return to_s
.to_cstring
.atof
253 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
255 # assert "ff".to_hex == 255
256 fun to_hex
: Int do return a_to
(16)
258 # If `self` contains only digits and letters, return the corresponding integer in a given base
260 # assert "120".a_to(3) == 15
261 fun a_to
(base
: Int) : Int
288 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
290 # assert "123".is_numeric == true
291 # assert "1.2".is_numeric == true
292 # assert "1,2".is_numeric == true
293 # assert "1..2".is_numeric == false
296 var has_point_or_comma
= false
301 if (i
== '.' or i
== ',') and not has_point_or_comma
303 has_point_or_comma
= true
312 # A upper case version of `self`
314 # assert "Hello World!".to_upper == "HELLO WORLD!"
315 fun to_upper
: SELFTYPE is abstract
317 # A lower case version of `self`
319 # assert "Hello World!".to_lower == "hello world!"
320 fun to_lower
: SELFTYPE is abstract
322 # Removes the whitespaces at the beginning of self
324 # assert " \n\thello \n\t".l_trim == "hello \n\t"
326 # A whitespace is defined as any character which ascii value is less than or equal to 32
329 var iter
= self.chars
.iterator
331 if iter
.item
.ascii
> 32 then break
334 if iter
.index
== length
then return self.empty
335 return self.substring_from
(iter
.index
)
338 # Removes the whitespaces at the end of self
340 # assert " \n\thello \n\t".r_trim == " \n\thello"
342 # A whitespace is defined as any character which ascii value is less than or equal to 32
345 var iter
= self.chars
.reverse_iterator
347 if iter
.item
.ascii
> 32 then break
350 if iter
.index
== length
then return self.empty
351 return self.substring
(0, iter
.index
+ 1)
354 # Trims trailing and preceding white spaces
355 # A whitespace is defined as any character which ascii value is less than or equal to 32
357 # assert " Hello World ! ".trim == "Hello World !"
358 # assert "\na\nb\tc\t".trim == "a\nb\tc"
359 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
361 # Mangle a string to be a unique string only made of alphanumeric characters
362 fun to_cmangle
: String
364 var res
= new FlatBuffer
365 var underscore
= false
366 for c
in self.chars
do
367 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
373 res
.append
('_'.ascii
.to_s
)
376 if c
>= '0' and c
<= '9' then
379 else if c
== '_' then
384 res
.append
(c
.ascii
.to_s
)
392 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
394 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
395 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
396 fun escape_to_c
: String
398 var b
= new FlatBuffer
399 for c
in self.chars
do
402 else if c
== '\0' then
404 else if c
== '"' then
406 else if c == '\'' then
408 else if c == '\\
' then
410 else if c.ascii < 32 then
411 b.append("\\{c.ascii.to_base(8, false)}")
419 # Escape additionnal characters
420 # The result might no be legal in C but be used in other languages
422 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
423 fun escape_more_to_c(chars: String): String
425 var b = new FlatBuffer
426 for c in escape_to_c.chars do
427 if chars.chars.has(c) then
435 # Escape to C plus braces
437 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
438 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
440 # Return a string where Nit escape sequences are transformed.
443 # assert s.length == 2
444 # var u = s.unescape_nit
445 # assert u.length == 1
446 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
447 fun unescape_nit
: String
449 var res
= new FlatBuffer.with_capacity
(self.length
)
450 var was_slash
= false
452 if not was_slash
then
463 else if c
== 'r' then
465 else if c
== 't' then
467 else if c
== '0' then
477 # Two pieces of text are equals if thez have the same characters in the same order.
479 # assert "hello" == "hello"
480 # assert "hello" != "HELLO"
481 # assert "hello" == "hel"+"lo"
483 # Things that are not Text are not equal.
486 # assert "9" != ['9']
489 # assert "9".chars.first == '9' # equality of Char
490 # assert "9".chars == ['9'] # equality of Sequence
491 # assert "9".to_i == 9 # equality of Int
494 if o
== null then return false
495 if not o
isa Text then return false
496 if self.is_same_instance
(o
) then return true
497 if self.length
!= o
.length
then return false
498 return self.chars
== o
.chars
501 # Lexicographical comparaison
503 # assert "abc" < "xy"
504 # assert "ABC" < "abc"
507 var self_chars
= self.chars
.iterator
508 var other_chars
= other
.chars
.iterator
510 while self_chars
.is_ok
and other_chars
.is_ok
do
511 if self_chars
.item
< other_chars
.item
then return true
512 if self_chars
.item
> other_chars
.item
then return false
517 if self_chars
.is_ok
then
524 # Flat representation of self
525 fun flatten
: FlatText is abstract
527 private var hash_cache
: nullable Int = null
531 if hash_cache
== null then
532 # djb2 hash algorithm
536 for char
in self.chars
do
537 h
= (h
* 32) + h
+ char
.ascii
543 return hash_cache
.as(not null)
548 # All kinds of array-based text representations.
549 abstract class FlatText
552 private var items
: NativeString
554 # Real items, used as cache for to_cstring is called
555 private var real_items
: nullable NativeString = null
557 redef var length
: Int
570 redef fun flatten
do return self
573 # Abstract class for the SequenceRead compatible
574 # views on String and Buffer objects
575 private abstract class StringCharView
576 super SequenceRead[Char]
580 private var target
: SELFTYPE
582 private init(tgt
: SELFTYPE)
587 redef fun is_empty
do return target
.is_empty
589 redef fun length
do return target
.length
591 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
593 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
596 # View on Buffer objects, extends Sequence
597 # for mutation operations
598 private abstract class BufferCharView
602 redef type SELFTYPE: Buffer
606 abstract class String
609 redef type SELFTYPE: String
611 redef fun to_s
do return self
615 # Immutable strings of characters.
620 redef type SELFTYPE: FlatString
622 # Index in _items of the start of the string
623 private var index_from
: Int
625 # Indes in _items of the last item of the string
626 private var index_to
: Int
628 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
630 ################################################
631 # AbstractString specific methods #
632 ################################################
636 var native
= calloc_string
(self.length
+ 1)
637 var length
= self.length
638 var items
= self.items
641 while pos
< length
do
642 native
[pos
] = items
[ipos
]
646 return native
.to_s_with_length
(self.length
)
649 redef fun substring
(from
, count
)
655 if count
< 0 then count
= 0
659 var realFrom
= index_from
+ from
661 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
663 if count
== 0 then return empty
665 var to
= realFrom
+ count
- 1
667 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
670 redef fun empty
do return "".as(FlatString)
674 var outstr
= calloc_string
(self.length
+ 1)
677 var myitems
= self.items
678 var index_from
= self.index_from
679 var max
= self.index_to
681 while index_from
<= max
do
682 outstr
[out_index
] = myitems
[index_from
].to_upper
687 outstr
[self.length
] = '\0'
689 return outstr
.to_s_with_length
(self.length
)
694 var outstr
= calloc_string
(self.length
+ 1)
697 var myitems
= self.items
698 var index_from
= self.index_from
699 var max
= self.index_to
701 while index_from
<= max
do
702 outstr
[out_index
] = myitems
[index_from
].to_lower
707 outstr
[self.length
] = '\0'
709 return outstr
.to_s_with_length
(self.length
)
714 var i
= self.index_from
715 var imax
= self.index_to
722 ##################################################
723 # String Specific Methods #
724 ##################################################
726 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
734 redef fun to_cstring
: NativeString
736 if real_items
!= null then return real_items
.as(not null)
737 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
738 var newItems
= calloc_string
(length
+ 1)
739 self.items
.copy_to
(newItems
, length
, index_from
, 0)
740 newItems
[length
] = '\0'
741 self.real_items
= newItems
749 if not other
isa FlatString then return super
751 if self.object_id
== other
.object_id
then return true
753 var my_length
= length
755 if other
.length
!= my_length
then return false
757 var my_index
= index_from
758 var its_index
= other
.index_from
760 var last_iteration
= my_index
+ my_length
762 var itsitems
= other
.items
763 var myitems
= self.items
765 while my_index
< last_iteration
do
766 if myitems
[my_index
] != itsitems
[its_index
] then return false
776 if not other
isa FlatString then return super
778 if self.object_id
== other
.object_id
then return false
780 var my_curr_char
: Char
781 var its_curr_char
: Char
783 var curr_id_self
= self.index_from
784 var curr_id_other
= other
.index_from
786 var my_items
= self.items
787 var its_items
= other
.items
789 var my_length
= self.length
790 var its_length
= other
.length
792 var max_iterations
= curr_id_self
+ my_length
794 while curr_id_self
< max_iterations
do
795 my_curr_char
= my_items
[curr_id_self
]
796 its_curr_char
= its_items
[curr_id_other
]
798 if my_curr_char
!= its_curr_char
then
799 if my_curr_char
< its_curr_char
then return true
807 return my_length
< its_length
812 var my_length
= self.length
813 var its_length
= s
.length
815 var total_length
= my_length
+ its_length
817 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
819 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
820 if s
isa FlatString then
821 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
822 else if s
isa FlatBuffer then
823 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
825 var curr_pos
= my_length
827 target_string
[curr_pos
] = i
832 target_string
[total_length
] = '\0'
834 return target_string
.to_s_with_length
(total_length
)
841 var my_length
= self.length
843 var final_length
= my_length
* i
845 var my_items
= self.items
847 var target_string
= calloc_string
((final_length
) + 1)
849 target_string
[final_length
] = '\0'
853 for iteration
in [1 .. i
] do
854 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
855 current_last
+= my_length
858 return target_string
.to_s_with_length
(final_length
)
863 if hash_cache
== null then
864 # djb2 hash algorythm
869 var strStart
= index_from
873 while i
>= strStart
do
874 h
= (h
* 32) + h
+ self.items
[i
].ascii
881 return hash_cache
.as(not null)
885 private class FlatStringReverseIterator
886 super IndexedIterator[Char]
888 var target
: FlatString
890 var target_items
: NativeString
894 init with_pos
(tgt
: FlatString, pos
: Int)
897 target_items
= tgt
.items
898 curr_pos
= pos
+ tgt
.index_from
901 redef fun is_ok
do return curr_pos
>= 0
903 redef fun item
do return target_items
[curr_pos
]
905 redef fun next
do curr_pos
-= 1
907 redef fun index
do return curr_pos
- target
.index_from
911 private class FlatStringIterator
912 super IndexedIterator[Char]
914 var target
: FlatString
916 var target_items
: NativeString
920 init with_pos
(tgt
: FlatString, pos
: Int)
923 target_items
= tgt
.items
924 curr_pos
= pos
+ target
.index_from
927 redef fun is_ok
do return curr_pos
<= target
.index_to
929 redef fun item
do return target_items
[curr_pos
]
931 redef fun next
do curr_pos
+= 1
933 redef fun index
do return curr_pos
- target
.index_from
937 private class FlatStringCharView
940 redef type SELFTYPE: FlatString
944 # Check that the index (+ index_from) is not larger than indexTo
945 # In other terms, if the index is valid
947 var target
= self.target
948 assert (index
+ target
.index_from
) <= target
.index_to
949 return target
.items
[index
+ target
.index_from
]
952 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
954 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
958 abstract class Buffer
961 redef type SELFTYPE: Buffer
963 # Specific implementations MUST set this to `true` in order to invalidate caches
964 protected var is_dirty
= true
966 # Modifies the char contained at pos `index`
968 # DEPRECATED : Use self.chars.[]= instead
969 fun []=(index
: Int, item
: Char) is abstract
971 # Adds a char `c` at the end of self
973 # DEPRECATED : Use self.chars.add instead
974 fun add
(c
: Char) is abstract
978 # var b = new FlatBuffer
980 # assert not b.is_empty
983 fun clear
is abstract
985 # Enlarges the subsequent array containing the chars of self
986 fun enlarge
(cap
: Int) is abstract
988 # Adds the content of text `s` at the end of self
990 # var b = new FlatBuffer
993 # assert b == "helloworld"
994 fun append
(s
: Text) is abstract
998 if is_dirty
then hash_cache
= null
1002 # In Buffers, the internal sequence of character is mutable
1003 # Thus, `chars` can be used to modify the buffer.
1004 redef fun chars
: Sequence[Char] is abstract
1007 # Mutable strings of characters.
1012 redef type SELFTYPE: FlatBuffer
1014 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1016 private var capacity
: Int
1018 redef fun []=(index
, item
)
1021 if index
== length
then
1025 assert index
>= 0 and index
< length
1032 if capacity
<= length
then enlarge
(length
+ 5)
1042 redef fun empty
do return new FlatBuffer
1044 redef fun enlarge
(cap
)
1048 if cap
<= c
then return
1049 while c
<= cap
do c
= c
* 2 + 2
1050 var a
= calloc_string
(c
+1)
1051 items
.copy_to
(a
, length
, 0, 0)
1054 items
.copy_to
(a
, length
, 0, 0)
1057 redef fun to_s
: String
1059 return to_cstring
.to_s_with_length
(length
)
1062 redef fun to_cstring
1065 var new_native
= calloc_string
(length
+ 1)
1066 new_native
[length
] = '\0'
1067 items
.copy_to
(new_native
, length
, 0, 0)
1068 real_items
= new_native
1071 return real_items
.as(not null)
1074 # Create a new empty string.
1075 init do with_capacity
(5)
1079 capacity
= s
.length
+ 1
1081 items
= calloc_string
(capacity
)
1082 if s
isa FlatString then
1083 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1084 else if s
isa FlatBuffer then
1085 s
.items
.copy_to
(items
, length
, 0, 0)
1095 # Create a new empty string with a given capacity.
1096 init with_capacity
(cap
: Int)
1099 # _items = new NativeString.calloc(cap)
1100 items
= calloc_string
(cap
+1)
1109 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1110 if s
isa FlatString then
1111 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1112 else if s
isa FlatBuffer then
1113 s
.items
.copy_to
(items
, sl
, 0, length
)
1115 var curr_pos
= self.length
1124 # Copies the content of self in `dest`
1125 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1127 var self_chars
= self.chars
1128 var dest_chars
= dest
.chars
1129 for i
in [0..len-1
] do
1130 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1134 redef fun substring
(from
, count
)
1138 if from
< 0 then from
= 0
1139 if count
> length
then count
= length
1140 if from
< count
then
1141 var r
= new FlatBuffer.with_capacity
(count
- from
)
1142 while from
< count
do
1143 r
.chars
.push
(items
[from
])
1148 return new FlatBuffer
1154 var new_buf
= new FlatBuffer.with_capacity
(self.length
)
1155 var reviter
= self.chars
.reverse_iterator
1156 while reviter
.is_ok
do
1157 new_buf
.add
(reviter
.item
)
1165 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1166 new_buf
.append
(self)
1167 new_buf
.append
(other
)
1171 redef fun *(repeats
)
1173 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1174 for i
in [0..repeats
[ do
1175 new_buf
.append
(self)
1181 private class FlatBufferReverseIterator
1182 super IndexedIterator[Char]
1184 var target
: FlatBuffer
1186 var target_items
: NativeString
1190 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1193 target_items
= tgt
.items
1197 redef fun index
do return curr_pos
1199 redef fun is_ok
do return curr_pos
>= 0
1201 redef fun item
do return target_items
[curr_pos
]
1203 redef fun next
do curr_pos
-= 1
1207 private class FlatBufferCharView
1208 super BufferCharView
1211 redef type SELFTYPE: FlatBuffer
1213 redef fun [](index
) do return target
.items
[index
]
1215 redef fun []=(index
, item
)
1217 assert index
>= 0 and index
<= length
1218 if index
== length
then
1222 target
.items
[index
] = item
1235 fun enlarge
(cap
: Int)
1242 var my_items
= target
.items
1243 var s_length
= s
.length
1244 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1247 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1249 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1253 private class FlatBufferIterator
1254 super IndexedIterator[Char]
1256 var target
: FlatBuffer
1258 var target_items
: NativeString
1262 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1265 target_items
= tgt
.items
1269 redef fun index
do return curr_pos
1271 redef fun is_ok
do return curr_pos
< target
.length
1273 redef fun item
do return target_items
[curr_pos
]
1275 redef fun next
do curr_pos
+= 1
1279 ###############################################################################
1281 ###############################################################################
1284 # User readable representation of `self`.
1285 fun to_s
: String do return inspect
1287 # The class name of the object in NativeString format.
1288 private fun native_class_name
: NativeString is intern
1290 # The class name of the object.
1292 # assert 5.class_name == "Int"
1293 fun class_name
: String do return native_class_name
.to_s
1295 # Developer readable representation of `self`.
1296 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1299 return "<{inspect_head}>"
1302 # Return "CLASSNAME:#OBJECTID".
1303 # This function is mainly used with the redefinition of the inspect method
1304 protected fun inspect_head
: String
1306 return "{class_name}:#{object_id.to_hex}"
1309 protected fun args
: Sequence[String]
1316 # assert true.to_s == "true"
1317 # assert false.to_s == "false"
1330 # Wrapper of strerror C function
1331 private fun strerror_ext
: NativeString is extern `{
1332 return strerror(recv);
1335 # Returns a string describing error number
1336 fun strerror
: String do return strerror_ext
.to_s
1338 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1339 # assume < to_c max const of char
1340 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1347 else if self == 0 then
1354 var pos
= digit_count
(base
) - 1
1355 while pos
>= 0 and n
> 0 do
1356 s
.chars
[pos
] = (n
% base
).to_c
1362 # C function to convert an nit Int to a NativeString (char*)
1363 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1365 # return displayable int in base 10 and signed
1367 # assert 1.to_s == "1"
1368 # assert (-123).to_s == "-123"
1370 var len
= digit_count
(10)
1371 return native_int_to_s
(len
).to_s_with_length
(len
)
1374 # return displayable int in hexadecimal
1376 # assert 1.to_hex == "1"
1377 # assert (-255).to_hex == "-ff"
1378 fun to_hex
: String do return to_base
(16,false)
1380 # return displayable int in base base and signed
1381 fun to_base
(base
: Int, signed
: Bool): String
1383 var l
= digit_count
(base
)
1384 var s
= new FlatBuffer.from
(" " * l
)
1385 fill_buffer
(s
, base
, signed
)
1391 # Pretty print self, print needoed decimals up to a max of 3.
1393 # assert 12.34.to_s == "12.34"
1394 # assert (-0120.03450).to_s == "-120.035"
1396 # see `to_precision` for a different precision.
1398 var str
= to_precision
( 3 )
1399 if is_inf
!= 0 or is_nan
then return str
1400 var len
= str
.length
1401 for i
in [0..len-1
] do
1403 var c
= str
.chars
[j
]
1406 else if c
== '.' then
1407 return str
.substring
( 0, j
+2 )
1409 return str
.substring
( 0, j
+1 )
1415 # `self` representation with `nb` digits after the '.'.
1417 # assert 12.345.to_precision(1) == "12.3"
1418 # assert 12.345.to_precision(2) == "12.35"
1419 # assert 12.345.to_precision(3) == "12.345"
1420 # assert 12.345.to_precision(4) == "12.3450"
1421 fun to_precision
(nb
: Int): String
1423 if is_nan
then return "nan"
1425 var isinf
= self.is_inf
1428 else if isinf
== -1 then
1432 if nb
== 0 then return self.to_i
.to_s
1434 for i
in [0..nb
[ do f
= f
* 10.0
1441 if i
== 0 then return "0.0"
1445 var p1
= s
.substring
(0, s
.length-nb
)
1446 var p2
= s
.substring
(s
.length-nb
, nb
)
1447 return p1
+ "." + p2
1449 return "0." + ("0"*(nb-sl
)) + s
1453 # `self` representation with `nb` digits after the '.'.
1455 # assert 12.345.to_precision_native(1) == "12.3"
1456 # assert 12.345.to_precision_native(2) == "12.35"
1457 # assert 12.345.to_precision_native(3) == "12.345"
1458 # assert 12.345.to_precision_native(4) == "12.3450"
1459 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1463 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1464 str = malloc(size + 1);
1465 sprintf(str, "%.*f", (int)nb, recv );
1467 return NativeString_to_s( str );
1472 # assert 'x'.to_s == "x"
1475 var s
= new FlatBuffer.with_capacity
(1)
1480 # Returns true if the char is a numerical digit
1482 # assert '0'.is_numeric
1483 # assert '9'.is_numeric
1484 # assert not 'a'.is_numeric
1485 # assert not '?'.is_numeric
1486 fun is_numeric
: Bool
1488 return self >= '0' and self <= '9'
1491 # Returns true if the char is an alpha digit
1493 # assert 'a'.is_alpha
1494 # assert 'Z'.is_alpha
1495 # assert not '0'.is_alpha
1496 # assert not '?'.is_alpha
1499 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1502 # Returns true if the char is an alpha or a numeric digit
1504 # assert 'a'.is_alphanumeric
1505 # assert 'Z'.is_alphanumeric
1506 # assert '0'.is_alphanumeric
1507 # assert '9'.is_alphanumeric
1508 # assert not '?'.is_alphanumeric
1509 fun is_alphanumeric
: Bool
1511 return self.is_numeric
or self.is_alpha
1515 redef class Collection[E
]
1516 # Concatenate elements.
1519 var s
= new FlatBuffer
1520 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1524 # Concatenate and separate each elements with `sep`.
1526 # assert [1, 2, 3].join(":") == "1:2:3"
1527 # assert [1..3].join(":") == "1:2:3"
1528 fun join
(sep
: Text): String
1530 if is_empty
then return ""
1532 var s
= new FlatBuffer # Result
1537 if e
!= null then s
.append
(e
.to_s
)
1539 # Concat other items
1544 if e
!= null then s
.append
(e
.to_s
)
1551 redef class Array[E
]
1552 # Fast implementation
1555 var s
= new FlatBuffer
1560 if e
!= null then s
.append
(e
.to_s
)
1567 redef class Map[K
,V
]
1568 # Concatenate couple of 'key value'.
1569 # key and value are separated by `couple_sep`.
1570 # each couple is separated each couple with `sep`.
1572 # var m = new ArrayMap[Int, String]
1575 # assert m.join("; ", "=") == "1=one; 10=ten"
1576 fun join
(sep
: String, couple_sep
: String): String
1578 if is_empty
then return ""
1580 var s
= new FlatBuffer # Result
1586 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1588 # Concat other items
1594 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1601 ###############################################################################
1603 ###############################################################################
1605 # Native strings are simple C char *
1609 fun [](index
: Int): Char is intern
1610 fun []=(index
: Int, item
: Char) is intern
1611 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1613 # Position of the first nul character.
1614 fun cstring_length
: Int
1617 while self[l
] != '\0' do l
+= 1
1620 fun atoi
: Int is intern
1621 fun atof
: Float is extern "atof"
1625 return to_s_with_length
(cstring_length
)
1628 fun to_s_with_length
(length
: Int): FlatString
1631 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1634 fun to_s_with_copy
: FlatString
1636 var length
= cstring_length
1637 var new_self
= calloc_string
(length
+ 1)
1638 copy_to
(new_self
, length
, 0, 0)
1639 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1644 # StringCapable objects can create native strings
1645 interface StringCapable
1646 protected fun calloc_string
(size
: Int): NativeString is intern
1650 var _args_cache
: nullable Sequence[String]
1652 redef fun args
: Sequence[String]
1654 if _args_cache
== null then init_args
1655 return _args_cache
.as(not null)
1658 # The name of the program as given by the OS
1659 fun program_name
: String
1661 return native_argv
(0).to_s
1664 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1665 private fun init_args
1667 var argc
= native_argc
1668 var args
= new Array[String].with_capacity
(0)
1671 args
[i-1
] = native_argv
(i
).to_s
1677 # First argument of the main C function.
1678 private fun native_argc
: Int is intern
1680 # Second argument of the main C function.
1681 private fun native_argv
(i
: Int): NativeString is intern
1684 # Comparator that efficienlty use `to_s` to compare things
1686 # The comparaison call `to_s` on object and use the result to order things.
1688 # var a = [1, 2, 3, 10, 20]
1689 # (new CachedAlphaComparator).sort(a)
1690 # assert a == [1, 10, 2, 20, 3]
1692 # Internally the result of `to_s` is cached in a HashMap to counter
1693 # uneficient implementation of `to_s`.
1695 # Note: it caching is not usefull, see `alpha_comparator`
1696 class CachedAlphaComparator
1697 super Comparator[Object]
1699 private var cache
= new HashMap[Object, String]
1701 private fun do_to_s
(a
: Object): String do
1702 if cache
.has_key
(a
) then return cache
[a
]
1708 redef fun compare
(a
, b
) do
1709 return do_to_s
(a
) <=> do_to_s
(b
)
1713 # see `alpha_comparator`
1714 private class AlphaComparator
1715 super Comparator[Object]
1716 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1719 # Stateless comparator that naively use `to_s` to compare things.
1721 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1722 # on a single instace. See `CachedAlphaComparator` as an alternative.
1724 # var a = [1, 2, 3, 10, 20]
1725 # alpha_comparator.sort(a)
1726 # assert a == [1, 10, 2, 20, 3]
1727 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator