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 the view on self (.chars)
36 type SELFVIEW: StringCharView
38 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
41 # Gets a view on the chars of the Text object
43 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
44 fun chars
: SELFVIEW is abstract
46 # Number of characters contained in self.
48 # assert "12345".length == 5
49 # assert "".length == 0
50 fun length
: Int is abstract
54 # assert "abcd".substring(1, 2) == "bc"
55 # assert "abcd".substring(-1, 2) == "a"
56 # assert "abcd".substring(1, 0) == ""
57 # assert "abcd".substring(2, 5) == "cd"
59 # A `from` index < 0 will be replaced by 0.
60 # Unless a `count` value is > 0 at the same time.
61 # In this case, `from += count` and `count -= from`.
62 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
64 # Concatenates `o` to `self`
66 # assert "hello" + "world" == "helloworld"
67 # assert "" + "hello" + "" == "hello"
68 fun +(o
: Text): SELFTYPE is abstract
70 # Auto-concatenates self `i` times
72 # assert "abc" * 4 == "abcabcabcabc"
73 # assert "abc" * 1 == "abc"
74 # assert "abc" * 0 == ""
75 fun *(i
: Int): SELFTYPE is abstract
77 # Is the current Text empty (== "")
80 # assert not "foo".is_empty
81 fun is_empty
: Bool do return self.length
== 0
83 # Returns an empty Text of the right type
85 # This method is used internally to get the right
86 # implementation of an empty string.
87 protected fun empty
: SELFTYPE is abstract
89 # Gets the first char of the Text
91 # DEPRECATED : Use self.chars.first instead
92 fun first
: Char do return self.chars
[0]
94 # Access a character at `index` in the string.
96 # assert "abcd"[2] == 'c'
98 # DEPRECATED : Use self.chars.[] instead
99 fun [](index
: Int): Char do return self.chars
[index
]
101 # Gets the index of the first occurence of 'c'
103 # Returns -1 if not found
105 # DEPRECATED : Use self.chars.index_of instead
106 fun index_of
(c
: Char): Int
108 return index_of_from
(c
, 0)
111 # Gets the last char of self
113 # DEPRECATED : Use self.chars.last instead
114 fun last
: Char do return self.chars
[length-1
]
116 # Gets the index of the first occurence of ´c´ starting from ´pos´
118 # Returns -1 if not found
120 # DEPRECATED : Use self.chars.index_of_from instead
121 fun index_of_from
(c
: Char, pos
: Int): Int
123 var iter
= self.chars
.iterator_from
(pos
)
125 if iter
.item
== c
then return iter
.index
130 # Gets the last index of char ´c´
132 # Returns -1 if not found
134 # DEPRECATED : Use self.chars.last_index_of instead
135 fun last_index_of
(c
: Char): Int
137 return last_index_of_from
(c
, length
- 1)
140 # Return a null terminated char *
141 fun to_cstring
: NativeString do return flatten
.to_cstring
143 # The index of the last occurrence of an element starting from pos (in reverse order).
145 # var s = "/etc/bin/test/test.nit"
146 # assert s.last_index_of_from('/', s.length-1) == 13
147 # assert s.last_index_of_from('/', 12) == 8
149 # Returns -1 if not found
151 # DEPRECATED : Use self.chars.last_index_of_from instead
152 fun last_index_of_from
(item
: Char, pos
: Int): Int
154 var iter
= self.chars
.reverse_iterator_from
(pos
)
156 if iter
.item
== item
then return iter
.index
162 # Gets an iterator on the chars of self
164 # DEPRECATED : Use self.chars.iterator instead
165 fun iterator
: Iterator[Char]
167 return self.chars
.iterator
170 # Is 'c' contained in self ?
172 # DEPRECATED : Use self.chars.has instead
173 fun has
(c
: Char): Bool
175 return self.chars
.has
(c
)
178 # Gets an Array containing the chars of self
180 # DEPRECATED : Use self.chars.to_a instead
181 fun to_a
: Array[Char] do return chars
.to_a
183 # Create a substring from `self` beginning at the `from` position
185 # assert "abcd".substring_from(1) == "bcd"
186 # assert "abcd".substring_from(-1) == "abcd"
187 # assert "abcd".substring_from(2) == "cd"
189 # As with substring, a `from` index < 0 will be replaced by 0
190 fun substring_from
(from
: Int): SELFTYPE
192 if from
> self.length
then return empty
193 if from
< 0 then from
= 0
194 return substring
(from
, length
- from
)
197 # Returns a reversed version of self
199 # assert "hello".reversed == "olleh"
200 # assert "bob".reversed == "bob"
201 # assert "".reversed == ""
202 fun reversed
: SELFTYPE is abstract
204 # Does self have a substring `str` starting from position `pos`?
206 # assert "abcd".has_substring("bc",1) == true
207 # assert "abcd".has_substring("bc",2) == false
208 fun has_substring
(str
: String, pos
: Int): Bool
210 var myiter
= self.chars
.iterator_from
(pos
)
211 var itsiter
= str
.chars
.iterator
212 while myiter
.is_ok
and itsiter
.is_ok
do
213 if myiter
.item
!= itsiter
.item
then return false
217 if itsiter
.is_ok
then return false
221 # Is this string prefixed by `prefix`?
223 # assert "abcd".has_prefix("ab") == true
224 # assert "abcbc".has_prefix("bc") == false
225 # assert "ab".has_prefix("abcd") == false
226 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
228 # Is this string suffixed by `suffix`?
230 # assert "abcd".has_suffix("abc") == false
231 # assert "abcd".has_suffix("bcd") == true
232 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
234 # If `self` contains only digits, return the corresponding integer
236 # assert "123".to_i == 123
237 # assert "-1".to_i == -1
241 return to_s
.to_cstring
.atoi
244 # If `self` contains a float, return the corresponding float
246 # assert "123".to_f == 123.0
247 # assert "-1".to_f == -1.0
248 # assert "-1.2e-3".to_f == -0.0012
252 return to_s
.to_cstring
.atof
255 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
257 # assert "ff".to_hex == 255
258 fun to_hex
: Int do return a_to
(16)
260 # If `self` contains only digits and letters, return the corresponding integer in a given base
262 # assert "120".a_to(3) == 15
263 fun a_to
(base
: Int) : Int
290 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
292 # assert "123".is_numeric == true
293 # assert "1.2".is_numeric == true
294 # assert "1,2".is_numeric == true
295 # assert "1..2".is_numeric == false
298 var has_point_or_comma
= false
303 if (i
== '.' or i
== ',') and not has_point_or_comma
305 has_point_or_comma
= true
314 # A upper case version of `self`
316 # assert "Hello World!".to_upper == "HELLO WORLD!"
317 fun to_upper
: SELFTYPE is abstract
319 # A lower case version of `self`
321 # assert "Hello World!".to_lower == "hello world!"
322 fun to_lower
: SELFTYPE is abstract
324 # Removes the whitespaces at the beginning of self
326 # assert " \n\thello \n\t".l_trim == "hello \n\t"
328 # A whitespace is defined as any character which ascii value is less than or equal to 32
331 var iter
= self.chars
.iterator
333 if iter
.item
.ascii
> 32 then break
336 if iter
.index
== length
then return self.empty
337 return self.substring_from
(iter
.index
)
340 # Removes the whitespaces at the end of self
342 # assert " \n\thello \n\t".r_trim == " \n\thello"
344 # A whitespace is defined as any character which ascii value is less than or equal to 32
347 var iter
= self.chars
.reverse_iterator
349 if iter
.item
.ascii
> 32 then break
352 if iter
.index
== length
then return self.empty
353 return self.substring
(0, iter
.index
+ 1)
356 # Trims trailing and preceding white spaces
357 # A whitespace is defined as any character which ascii value is less than or equal to 32
359 # assert " Hello World ! ".trim == "Hello World !"
360 # assert "\na\nb\tc\t".trim == "a\nb\tc"
361 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
363 # Mangle a string to be a unique string only made of alphanumeric characters
364 fun to_cmangle
: String
366 var res
= new FlatBuffer
367 var underscore
= false
368 for c
in self.chars
do
369 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
375 res
.append
('_'.ascii
.to_s
)
378 if c
>= '0' and c
<= '9' then
381 else if c
== '_' then
386 res
.append
(c
.ascii
.to_s
)
394 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
396 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
397 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
398 fun escape_to_c
: String
400 var b
= new FlatBuffer
401 for c
in self.chars
do
404 else if c
== '\0' then
406 else if c
== '"' then
408 else if c == '\'' then
410 else if c == '\\
' then
412 else if c.ascii < 32 then
413 b.append("\\{c.ascii.to_base(8, false)}")
421 # Escape additionnal characters
422 # The result might no be legal in C but be used in other languages
424 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
425 fun escape_more_to_c(chars: String): String
427 var b = new FlatBuffer
428 for c in escape_to_c.chars do
429 if chars.chars.has(c) then
437 # Escape to C plus braces
439 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
440 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
442 # Return a string where Nit escape sequences are transformed.
445 # assert s.length == 2
446 # var u = s.unescape_nit
447 # assert u.length == 1
448 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
449 fun unescape_nit
: String
451 var res
= new FlatBuffer.with_capacity
(self.length
)
452 var was_slash
= false
454 if not was_slash
then
465 else if c
== 'r' then
467 else if c
== 't' then
469 else if c
== '0' then
479 # Two pieces of text are equals if thez have the same characters in the same order.
481 # assert "hello" == "hello"
482 # assert "hello" != "HELLO"
483 # assert "hello" == "hel"+"lo"
485 # Things that are not Text are not equal.
488 # assert "9" != ['9']
491 # assert "9".chars.first == '9' # equality of Char
492 # assert "9".chars == ['9'] # equality of Sequence
493 # assert "9".to_i == 9 # equality of Int
496 if o
== null then return false
497 if not o
isa Text then return false
498 if self.is_same_instance
(o
) then return true
499 if self.length
!= o
.length
then return false
500 return self.chars
== o
.chars
503 # Lexicographical comparaison
505 # assert "abc" < "xy"
506 # assert "ABC" < "abc"
509 var self_chars
= self.chars
.iterator
510 var other_chars
= other
.chars
.iterator
512 while self_chars
.is_ok
and other_chars
.is_ok
do
513 if self_chars
.item
< other_chars
.item
then return true
514 if self_chars
.item
> other_chars
.item
then return false
519 if self_chars
.is_ok
then
526 # Flat representation of self
527 fun flatten
: FlatText is abstract
529 private var hash_cache
: nullable Int = null
533 if hash_cache
== null then
534 # djb2 hash algorithm
538 for char
in self.chars
do
539 h
= (h
* 32) + h
+ char
.ascii
545 return hash_cache
.as(not null)
550 # All kinds of array-based text representations.
551 abstract class FlatText
554 private var items
: NativeString
556 # Real items, used as cache for to_cstring is called
557 private var real_items
: nullable NativeString = null
559 redef var length
: Int
572 redef fun flatten
do return self
575 # Abstract class for the SequenceRead compatible
576 # views on String and Buffer objects
577 abstract class StringCharView
578 super SequenceRead[Char]
582 private var target
: SELFTYPE
584 private init(tgt
: SELFTYPE)
589 redef fun is_empty
do return target
.is_empty
591 redef fun length
do return target
.length
593 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
595 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
598 # View on Buffer objects, extends Sequence
599 # for mutation operations
600 abstract class BufferCharView
604 redef type SELFTYPE: Buffer
608 abstract class String
611 redef type SELFTYPE: String
613 redef fun to_s
do return self
617 # Immutable strings of characters.
622 redef type SELFTYPE: FlatString
624 # Index in _items of the start of the string
625 private var index_from
: Int
627 # Indes in _items of the last item of the string
628 private var index_to
: Int
630 redef var chars
: SELFVIEW = new FlatStringCharView(self)
632 ################################################
633 # AbstractString specific methods #
634 ################################################
638 var native
= calloc_string
(self.length
+ 1)
639 var length
= self.length
640 var items
= self.items
643 while pos
< length
do
644 native
[pos
] = items
[ipos
]
648 return native
.to_s_with_length
(self.length
)
651 redef fun substring
(from
, count
)
657 if count
< 0 then count
= 0
661 var realFrom
= index_from
+ from
663 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
665 if count
== 0 then return empty
667 var to
= realFrom
+ count
- 1
669 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
672 redef fun empty
do return "".as(FlatString)
676 var outstr
= calloc_string
(self.length
+ 1)
679 var myitems
= self.items
680 var index_from
= self.index_from
681 var max
= self.index_to
683 while index_from
<= max
do
684 outstr
[out_index
] = myitems
[index_from
].to_upper
689 outstr
[self.length
] = '\0'
691 return outstr
.to_s_with_length
(self.length
)
696 var outstr
= calloc_string
(self.length
+ 1)
699 var myitems
= self.items
700 var index_from
= self.index_from
701 var max
= self.index_to
703 while index_from
<= max
do
704 outstr
[out_index
] = myitems
[index_from
].to_lower
709 outstr
[self.length
] = '\0'
711 return outstr
.to_s_with_length
(self.length
)
716 var i
= self.index_from
717 var imax
= self.index_to
724 ##################################################
725 # String Specific Methods #
726 ##################################################
728 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
736 redef fun to_cstring
: NativeString
738 if real_items
!= null then return real_items
.as(not null)
739 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
740 var newItems
= calloc_string
(length
+ 1)
741 self.items
.copy_to
(newItems
, length
, index_from
, 0)
742 newItems
[length
] = '\0'
743 self.real_items
= newItems
751 if not other
isa FlatString then return super
753 if self.object_id
== other
.object_id
then return true
755 var my_length
= length
757 if other
.length
!= my_length
then return false
759 var my_index
= index_from
760 var its_index
= other
.index_from
762 var last_iteration
= my_index
+ my_length
764 var itsitems
= other
.items
765 var myitems
= self.items
767 while my_index
< last_iteration
do
768 if myitems
[my_index
] != itsitems
[its_index
] then return false
778 if not other
isa FlatString then return super
780 if self.object_id
== other
.object_id
then return false
782 var my_curr_char
: Char
783 var its_curr_char
: Char
785 var curr_id_self
= self.index_from
786 var curr_id_other
= other
.index_from
788 var my_items
= self.items
789 var its_items
= other
.items
791 var my_length
= self.length
792 var its_length
= other
.length
794 var max_iterations
= curr_id_self
+ my_length
796 while curr_id_self
< max_iterations
do
797 my_curr_char
= my_items
[curr_id_self
]
798 its_curr_char
= its_items
[curr_id_other
]
800 if my_curr_char
!= its_curr_char
then
801 if my_curr_char
< its_curr_char
then return true
809 return my_length
< its_length
814 var my_length
= self.length
815 var its_length
= s
.length
817 var total_length
= my_length
+ its_length
819 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
821 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
822 if s
isa FlatString then
823 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
824 else if s
isa FlatBuffer then
825 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
827 var curr_pos
= my_length
829 target_string
[curr_pos
] = i
834 target_string
[total_length
] = '\0'
836 return target_string
.to_s_with_length
(total_length
)
843 var my_length
= self.length
845 var final_length
= my_length
* i
847 var my_items
= self.items
849 var target_string
= calloc_string
((final_length
) + 1)
851 target_string
[final_length
] = '\0'
855 for iteration
in [1 .. i
] do
856 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
857 current_last
+= my_length
860 return target_string
.to_s_with_length
(final_length
)
865 if hash_cache
== null then
866 # djb2 hash algorythm
871 var strStart
= index_from
875 while i
>= strStart
do
876 h
= (h
* 32) + h
+ self.items
[i
].ascii
883 return hash_cache
.as(not null)
887 private class FlatStringReverseIterator
888 super IndexedIterator[Char]
890 var target
: FlatString
892 var target_items
: NativeString
896 init with_pos
(tgt
: FlatString, pos
: Int)
899 target_items
= tgt
.items
900 curr_pos
= pos
+ tgt
.index_from
903 redef fun is_ok
do return curr_pos
>= 0
905 redef fun item
do return target_items
[curr_pos
]
907 redef fun next
do curr_pos
-= 1
909 redef fun index
do return curr_pos
- target
.index_from
913 private class FlatStringIterator
914 super IndexedIterator[Char]
916 var target
: FlatString
918 var target_items
: NativeString
922 init with_pos
(tgt
: FlatString, pos
: Int)
925 target_items
= tgt
.items
926 curr_pos
= pos
+ target
.index_from
929 redef fun is_ok
do return curr_pos
<= target
.index_to
931 redef fun item
do return target_items
[curr_pos
]
933 redef fun next
do curr_pos
+= 1
935 redef fun index
do return curr_pos
- target
.index_from
939 private class FlatStringCharView
942 redef type SELFTYPE: FlatString
946 # Check that the index (+ index_from) is not larger than indexTo
947 # In other terms, if the index is valid
949 var target
= self.target
950 assert (index
+ target
.index_from
) <= target
.index_to
951 return target
.items
[index
+ target
.index_from
]
954 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
956 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
960 abstract class Buffer
963 redef type SELFVIEW: BufferCharView
964 redef type SELFTYPE: Buffer
966 # Specific implementations MUST set this to `true` in order to invalidate caches
967 protected var is_dirty
= true
969 # Modifies the char contained at pos `index`
971 # DEPRECATED : Use self.chars.[]= instead
972 fun []=(index
: Int, item
: Char) is abstract
974 # Adds a char `c` at the end of self
976 # DEPRECATED : Use self.chars.add instead
977 fun add
(c
: Char) is abstract
981 # var b = new FlatBuffer
983 # assert not b.is_empty
986 fun clear
is abstract
988 # Enlarges the subsequent array containing the chars of self
989 fun enlarge
(cap
: Int) is abstract
991 # Adds the content of text `s` at the end of self
993 # var b = new FlatBuffer
996 # assert b == "helloworld"
997 fun append
(s
: Text) is abstract
1001 if is_dirty
then hash_cache
= null
1007 # Mutable strings of characters.
1012 redef type SELFTYPE: FlatBuffer
1014 redef var chars
: SELFVIEW = 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"
1329 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1330 # assume < to_c max const of char
1331 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1338 else if self == 0 then
1345 var pos
= digit_count
(base
) - 1
1346 while pos
>= 0 and n
> 0 do
1347 s
.chars
[pos
] = (n
% base
).to_c
1353 # C function to convert an nit Int to a NativeString (char*)
1354 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1356 # return displayable int in base 10 and signed
1358 # assert 1.to_s == "1"
1359 # assert (-123).to_s == "-123"
1361 var len
= digit_count
(10)
1362 return native_int_to_s
(len
).to_s_with_length
(len
)
1365 # return displayable int in hexadecimal
1367 # assert 1.to_hex == "1"
1368 # assert (-255).to_hex == "-ff"
1369 fun to_hex
: String do return to_base
(16,false)
1371 # return displayable int in base base and signed
1372 fun to_base
(base
: Int, signed
: Bool): String
1374 var l
= digit_count
(base
)
1375 var s
= new FlatBuffer.from
(" " * l
)
1376 fill_buffer
(s
, base
, signed
)
1382 # Pretty print self, print needoed decimals up to a max of 3.
1384 # assert 12.34.to_s == "12.34"
1385 # assert (-0120.03450).to_s == "-120.035"
1387 # see `to_precision` for a different precision.
1389 var str
= to_precision
( 3 )
1390 if is_inf
!= 0 or is_nan
then return str
1391 var len
= str
.length
1392 for i
in [0..len-1
] do
1394 var c
= str
.chars
[j
]
1397 else if c
== '.' then
1398 return str
.substring
( 0, j
+2 )
1400 return str
.substring
( 0, j
+1 )
1406 # `self` representation with `nb` digits after the '.'.
1408 # assert 12.345.to_precision(1) == "12.3"
1409 # assert 12.345.to_precision(2) == "12.35"
1410 # assert 12.345.to_precision(3) == "12.345"
1411 # assert 12.345.to_precision(4) == "12.3450"
1412 fun to_precision
(nb
: Int): String
1414 if is_nan
then return "nan"
1416 var isinf
= self.is_inf
1419 else if isinf
== -1 then
1423 if nb
== 0 then return self.to_i
.to_s
1425 for i
in [0..nb
[ do f
= f
* 10.0
1432 if i
== 0 then return "0.0"
1436 var p1
= s
.substring
(0, s
.length-nb
)
1437 var p2
= s
.substring
(s
.length-nb
, nb
)
1438 return p1
+ "." + p2
1440 return "0." + ("0"*(nb-sl
)) + s
1444 # `self` representation with `nb` digits after the '.'.
1446 # assert 12.345.to_precision_native(1) == "12.3"
1447 # assert 12.345.to_precision_native(2) == "12.35"
1448 # assert 12.345.to_precision_native(3) == "12.345"
1449 # assert 12.345.to_precision_native(4) == "12.3450"
1450 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1454 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1455 str = malloc(size + 1);
1456 sprintf(str, "%.*f", (int)nb, recv );
1458 return NativeString_to_s( str );
1463 # assert 'x'.to_s == "x"
1466 var s
= new FlatBuffer.with_capacity
(1)
1471 # Returns true if the char is a numerical digit
1473 # assert '0'.is_numeric
1474 # assert '9'.is_numeric
1475 # assert not 'a'.is_numeric
1476 # assert not '?'.is_numeric
1477 fun is_numeric
: Bool
1479 return self >= '0' and self <= '9'
1482 # Returns true if the char is an alpha digit
1484 # assert 'a'.is_alpha
1485 # assert 'Z'.is_alpha
1486 # assert not '0'.is_alpha
1487 # assert not '?'.is_alpha
1490 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1493 # Returns true if the char is an alpha or a numeric digit
1495 # assert 'a'.is_alphanumeric
1496 # assert 'Z'.is_alphanumeric
1497 # assert '0'.is_alphanumeric
1498 # assert '9'.is_alphanumeric
1499 # assert not '?'.is_alphanumeric
1500 fun is_alphanumeric
: Bool
1502 return self.is_numeric
or self.is_alpha
1506 redef class Collection[E
]
1507 # Concatenate elements.
1510 var s
= new FlatBuffer
1511 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1515 # Concatenate and separate each elements with `sep`.
1517 # assert [1, 2, 3].join(":") == "1:2:3"
1518 # assert [1..3].join(":") == "1:2:3"
1519 fun join
(sep
: String): String
1521 if is_empty
then return ""
1523 var s
= new FlatBuffer # Result
1528 if e
!= null then s
.append
(e
.to_s
)
1530 # Concat other items
1535 if e
!= null then s
.append
(e
.to_s
)
1542 redef class Array[E
]
1543 # Fast implementation
1546 var s
= new FlatBuffer
1551 if e
!= null then s
.append
(e
.to_s
)
1558 redef class Map[K
,V
]
1559 # Concatenate couple of 'key value'.
1560 # key and value are separated by `couple_sep`.
1561 # each couple is separated each couple with `sep`.
1563 # var m = new ArrayMap[Int, String]
1566 # assert m.join("; ", "=") == "1=one; 10=ten"
1567 fun join
(sep
: String, couple_sep
: String): String
1569 if is_empty
then return ""
1571 var s
= new FlatBuffer # Result
1577 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1579 # Concat other items
1585 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1592 ###############################################################################
1594 ###############################################################################
1596 # Native strings are simple C char *
1600 fun [](index
: Int): Char is intern
1601 fun []=(index
: Int, item
: Char) is intern
1602 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1604 # Position of the first nul character.
1605 fun cstring_length
: Int
1608 while self[l
] != '\0' do l
+= 1
1611 fun atoi
: Int is intern
1612 fun atof
: Float is extern "atof"
1616 return to_s_with_length
(cstring_length
)
1619 fun to_s_with_length
(length
: Int): FlatString
1622 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1625 fun to_s_with_copy
: FlatString
1627 var length
= cstring_length
1628 var new_self
= calloc_string
(length
+ 1)
1629 copy_to
(new_self
, length
, 0, 0)
1630 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1635 # StringCapable objects can create native strings
1636 interface StringCapable
1637 protected fun calloc_string
(size
: Int): NativeString is intern
1641 var _args_cache
: nullable Sequence[String]
1643 redef fun args
: Sequence[String]
1645 if _args_cache
== null then init_args
1646 return _args_cache
.as(not null)
1649 # The name of the program as given by the OS
1650 fun program_name
: String
1652 return native_argv
(0).to_s
1655 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1656 private fun init_args
1658 var argc
= native_argc
1659 var args
= new Array[String].with_capacity
(0)
1662 args
[i-1
] = native_argv
(i
).to_s
1668 # First argument of the main C function.
1669 private fun native_argc
: Int is intern
1671 # Second argument of the main C function.
1672 private fun native_argv
(i
: Int): NativeString is intern
1675 # Comparator that efficienlty use `to_s` to compare things
1677 # The comparaison call `to_s` on object and use the result to order things.
1679 # var a = [1, 2, 3, 10, 20]
1680 # (new CachedAlphaComparator).sort(a)
1681 # assert a == [1, 10, 2, 20, 3]
1683 # Internally the result of `to_s` is cached in a HashMap to counter
1684 # uneficient implementation of `to_s`.
1686 # Note: it caching is not usefull, see `alpha_comparator`
1687 class CachedAlphaComparator
1688 super Comparator[Object]
1690 private var cache
= new HashMap[Object, String]
1692 private fun do_to_s
(a
: Object): String do
1693 if cache
.has_key
(a
) then return cache
[a
]
1699 redef fun compare
(a
, b
) do
1700 return do_to_s
(a
) <=> do_to_s
(b
)
1704 # see `alpha_comparator`
1705 private class AlphaComparator
1706 super Comparator[Object]
1707 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1710 # Stateless comparator that naively use `to_s` to compare things.
1712 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1713 # on a single instace. See `CachedAlphaComparator` as an alternative.
1715 # var a = [1, 2, 3, 10, 20]
1716 # alpha_comparator.sort(a)
1717 # assert a == [1, 10, 2, 20, 3]
1718 fun alpha_comparator
: Comparator[Object] do return once
new AlphaComparator