1176e0401fc7eb20660f1ce5216f78ad672eee5c
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
32 redef type OTHER: Text
34 # Type of the view on self (.chars)
35 type SELFVIEW: StringCharView
37 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
40 # Gets a view on the chars of the Text object
41 fun chars
: SELFVIEW is abstract
43 # Number of characters contained in self.
44 fun length
: Int is abstract
48 # assert "abcd".substring(1, 2) == "bc"
49 # assert "abcd".substring(-1, 2) == "a"
50 # assert "abcd".substring(1, 0) == ""
51 # assert "abcd".substring(2, 5) == "cd"
53 # A `from` index < 0 will be replaced by 0.
54 # Unless a `count` value is > 0 at the same time.
55 # In this case, `from += count` and `count -= from`.
56 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
58 # Is the current Text empty (== "")
60 # assert not "foo".is_empty
61 fun is_empty
: Bool do return self.length
== 0
63 # Returns an empty Text of the right type
64 fun empty
: SELFTYPE is abstract
66 # Gets the first char of the Text
68 # DEPRECATED : Use self.chars.first instead
69 fun first
: Char do return self.chars
[0]
71 # Access a character at `index` in the string.
73 # assert "abcd"[2] == 'c'
75 # DEPRECATED : Use self.chars.[] instead
76 fun [](index
: Int): Char do return self.chars
[index
]
78 # Gets the index of the first occurence of 'c'
80 # Returns -1 if not found
82 # DEPRECATED : Use self.chars.index_of instead
83 fun index_of
(c
: Char): Int
85 return index_of_from
(c
, 0)
88 # Gets the last char of self
90 # DEPRECATED : Use self.chars.last instead
91 fun last
: Char do return self.chars
[length-1
]
93 # Gets the index of the first occurence of ´c´ starting from ´pos´
95 # Returns -1 if not found
97 # DEPRECATED : Use self.chars.index_of_from instead
98 fun index_of_from
(c
: Char, pos
: Int): Int
100 var iter
= self.chars
.iterator_from
(pos
)
102 if iter
.item
== c
then return iter
.index
107 # Gets the last index of char ´c´
109 # Returns -1 if not found
111 # DEPRECATED : Use self.chars.last_index_of instead
112 fun last_index_of
(c
: Char): Int
114 return last_index_of_from
(c
, length
- 1)
117 # The index of the last occurrence of an element starting from pos (in reverse order).
119 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
120 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
122 # Returns -1 if not found
124 # DEPRECATED : Use self.chars.last_index_of_from instead
125 fun last_index_of_from
(item
: Char, pos
: Int): Int
127 var iter
= self.chars
.reverse_iterator_from
(pos
)
129 if iter
.item
== item
then return iter
.index
135 # Gets an iterator on the chars of self
137 # DEPRECATED : Use self.chars.iterator instead
138 fun iterator
: Iterator[Char]
140 return self.chars
.iterator
143 # Is 'c' contained in self ?
145 # DEPRECATED : Use self.chars.has instead
146 fun has
(c
: Char): Bool
148 return self.chars
.has
(c
)
151 # Gets an Array containing the chars of self
153 # DEPRECATED : Use self.chars.to_a instead
154 fun to_a
: Array[Char] do return chars
.to_a
156 # Create a substring from `self` beginning at the `from` position
158 # assert "abcd".substring_from(1) == "bcd"
159 # assert "abcd".substring_from(-1) == "abcd"
160 # assert "abcd".substring_from(2) == "cd"
162 # As with substring, a `from` index < 0 will be replaced by 0
163 fun substring_from
(from
: Int): SELFTYPE
166 return substring
(from
, length
- from
)
169 # Does self have a substring `str` starting from position `pos`?
171 # assert "abcd".has_substring("bc",1) == true
172 # assert "abcd".has_substring("bc",2) == false
173 fun has_substring
(str
: String, pos
: Int): Bool
175 var myiter
= self.chars
.iterator_from
(pos
)
176 var itsiter
= str
.iterator
177 while myiter
.is_ok
and itsiter
.is_ok
do
178 if myiter
.item
!= itsiter
.item
then return false
182 if itsiter
.is_ok
then return false
186 # Is this string prefixed by `prefix`?
188 # assert "abcd".has_prefix("ab") == true
189 # assert "abcbc".has_prefix("bc") == false
190 # assert "ab".has_prefix("abcd") == false
191 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
193 # Is this string suffixed by `suffix`?
195 # assert "abcd".has_suffix("abc") == false
196 # assert "abcd".has_suffix("bcd") == true
197 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
199 # If `self` contains only digits, return the corresponding integer
201 # assert "123".to_i == 123
202 # assert "-1".to_i == -1
206 return to_s
.to_cstring
.atoi
209 # If `self` contains a float, return the corresponding float
211 # assert "123".to_f == 123.0
212 # assert "-1".to_f == -1.0
213 # assert "-1.2e-3".to_f == -0.0012
217 return to_s
.to_cstring
.atof
220 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
221 fun to_hex
: Int do return a_to
(16)
223 # If `self` contains only digits and letters, return the corresponding integer in a given base
225 # assert "120".a_to(3) == 15
226 fun a_to
(base
: Int) : Int
253 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
255 # assert "123".is_numeric == true
256 # assert "1.2".is_numeric == true
257 # assert "1,2".is_numeric == true
258 # assert "1..2".is_numeric == false
261 var has_point_or_comma
= false
266 if (i
== '.' or i
== ',') and not has_point_or_comma
268 has_point_or_comma
= true
277 # A upper case version of `self`
279 # assert "Hello World!".to_upper == "HELLO WORLD!"
280 fun to_upper
: SELFTYPE is abstract
282 # A lower case version of `self`
284 # assert "Hello World!".to_lower == "hello world!"
285 fun to_lower
: SELFTYPE is abstract
287 # Removes the whitespaces at the beginning of self
290 var iter
= self.chars
.iterator
292 if iter
.item
.ascii
> 32 then break
295 if iter
.index
== length
then return self.empty
296 return self.substring_from
(iter
.index
)
299 # Removes the whitespaces at the end of self
302 var iter
= self.chars
.reverse_iterator
304 if iter
.item
.ascii
> 32 then break
307 if iter
.index
== length
then return self.empty
308 return self.substring
(0, iter
.index
+ 1)
311 # Trims trailing and preceding white spaces
312 # A whitespace is defined as any character which ascii value is less than or equal to 32
314 # assert " Hello World ! ".trim == "Hello World !"
315 # assert "\na\nb\tc\t".trim == "a\nb\tc"
316 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
318 # Mangle a string to be a unique string only made of alphanumeric characters
319 fun to_cmangle
: String
321 var res
= new FlatBuffer
322 var underscore
= false
323 for c
in self.chars
do
324 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
330 res
.append
('_'.ascii
.to_s
)
333 if c
>= '0' and c
<= '9' then
336 else if c
== '_' then
341 res
.append
(c
.ascii
.to_s
)
349 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
351 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
352 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
353 fun escape_to_c
: String
355 var b
= new FlatBuffer
356 for c
in self.chars
do
359 else if c
== '\0' then
361 else if c
== '"' then
363 else if c == '\'' then
365 else if c == '\\
' then
367 else if c.ascii < 32 then
368 b.append("\\{c.ascii.to_base(8, false)}")
376 # Escape additionnal characters
377 # The result might no be legal in C but be used in other languages
379 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
380 fun escape_more_to_c(chars: String): String
382 var b = new FlatBuffer
383 for c in escape_to_c do
384 if chars.chars.has(c) then
392 # Escape to c plus braces
394 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
395 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
397 # Return a string where Nit escape sequences are transformed.
401 # assert s.length == 2
402 # var u = s.unescape_nit
403 # assert u.length == 1
404 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
405 fun unescape_nit
: String
407 var res
= new FlatBuffer.with_capacity
(self.length
)
408 var was_slash
= false
410 if not was_slash
then
421 else if c
== 'r' then
423 else if c
== 't' then
425 else if c
== '0' then
436 if o
== null then return false
437 if not o
isa Text then return false
438 if self.is_same_instance
(o
) then return true
439 if self.length
!= o
.length
then return false
440 return self.chars
== o
.chars
445 return self.chars
< o
.chars
450 # All kinds of array-based text representations.
451 abstract class FlatText
454 private var items
: NativeString
456 redef var length
: Int
470 # Abstract class for the SequenceRead compatible
471 # views on String and Buffer objects
472 abstract class StringCharView
473 super SequenceRead[Char]
478 redef type OTHER: StringCharView
480 private var target
: SELFTYPE
482 private init(tgt
: SELFTYPE)
487 redef fun is_empty
do return target
.is_empty
489 redef fun length
do return target
.length
491 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
493 # Gets a new Iterator starting at position `pos`
496 # var iter = "abcd".iterator_from(2)
497 # while iter.is_ok do
503 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
505 # Gets an iterator starting at the end and going backwards
508 # var reviter = "now step live...".reverse_iterator
509 # while reviter.is_ok do
510 # printn reviter.item
514 # Outputs : ...evil pets won
515 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
517 # Gets an iterator on the chars of self starting from `pos`
520 # var iter = "abcd".reverse_iterator_from(1)
521 # while iter.is_ok do
527 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
529 redef fun has
(c
: Char): Bool
532 if i
== c
then return true
539 if other
== null then return false
540 if not other
isa StringCharView then return false
541 var other_chars
= other
.iterator
543 if i
!= other_chars
.item
then return false
551 var self_chars
= self.iterator
552 var other_chars
= other
.iterator
554 while self_chars
.is_ok
and other_chars
.is_ok
do
555 if self_chars
.item
< other_chars
.item
then return true
556 if self_chars
.item
> other_chars
.item
then return false
561 if self_chars
.is_ok
then
569 # View on Buffer objects, extends Sequence
570 # for mutation operations
571 abstract class BufferCharView
575 redef type SELFTYPE: Buffer
579 # Immutable strings of characters.
584 redef type SELFTYPE: String
585 redef type SELFVIEW: FlatStringCharView
587 # Index in _items of the start of the string
588 private var index_from
: Int
590 # Indes in _items of the last item of the string
591 private var index_to
: Int
593 redef var chars
: SELFVIEW = new FlatStringCharView(self)
595 ################################################
596 # AbstractString specific methods #
597 ################################################
599 redef fun [](index
) do
601 # Check that the index (+ index_from) is not larger than indexTo
602 # In other terms, if the index is valid
603 assert (index
+ index_from
) <= index_to
604 return items
[index
+ index_from
]
607 redef fun substring
(from
, count
)
613 if count
< 0 then count
= 0
617 var realFrom
= index_from
+ from
619 if (realFrom
+ count
) > index_to
then return new String.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
621 if count
== 0 then return ""
623 var to
= realFrom
+ count
- 1
625 return new String.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
628 redef fun empty
do return "".as(String)
632 var outstr
= calloc_string
(self.length
+ 1)
635 var myitems
= self.items
636 var index_from
= self.index_from
637 var max
= self.index_to
639 while index_from
<= max
do
640 outstr
[out_index
] = myitems
[index_from
].to_upper
645 outstr
[self.length
] = '\0'
647 return outstr
.to_s_with_length
(self.length
)
652 var outstr
= calloc_string
(self.length
+ 1)
655 var myitems
= self.items
656 var index_from
= self.index_from
657 var max
= self.index_to
659 while index_from
<= max
do
660 outstr
[out_index
] = myitems
[index_from
].to_lower
665 outstr
[self.length
] = '\0'
667 return outstr
.to_s_with_length
(self.length
)
672 var i
= self.index_from
673 var imax
= self.index_to
680 ##################################################
681 # String Specific Methods #
682 ##################################################
684 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
692 # Return a null terminated char *
693 fun to_cstring
: NativeString
695 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
696 var newItems
= calloc_string
(length
+ 1)
697 self.items
.copy_to
(newItems
, length
, index_from
, 0)
698 newItems
[length
] = '\0'
706 if not other
isa String then return super
708 if self.object_id
== other
.object_id
then return true
710 var my_length
= length
712 if other
.length
!= my_length
then return false
714 var my_index
= index_from
715 var its_index
= other
.index_from
717 var last_iteration
= my_index
+ my_length
719 var itsitems
= other
.items
720 var myitems
= self.items
722 while my_index
< last_iteration
do
723 if myitems
[my_index
] != itsitems
[its_index
] then return false
731 # The comparison between two strings is done on a lexicographical basis
733 # assert ("aa" < "b") == true
736 if not other
isa String then return super
738 if self.object_id
== other
.object_id
then return false
740 var my_curr_char
: Char
741 var its_curr_char
: Char
743 var curr_id_self
= self.index_from
744 var curr_id_other
= other
.index_from
746 var my_items
= self.items
747 var its_items
= other
.items
749 var my_length
= self.length
750 var its_length
= other
.length
752 var max_iterations
= curr_id_self
+ my_length
754 while curr_id_self
< max_iterations
do
755 my_curr_char
= my_items
[curr_id_self
]
756 its_curr_char
= its_items
[curr_id_other
]
758 if my_curr_char
!= its_curr_char
then
759 if my_curr_char
< its_curr_char
then return true
767 return my_length
< its_length
770 # The concatenation of `self` with `s`
772 # assert "hello " + "world!" == "hello world!"
773 fun +(s
: String): String
775 var my_length
= self.length
776 var its_length
= s
.length
778 var total_length
= my_length
+ its_length
780 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
782 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
783 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
785 target_string
[total_length
] = '\0'
787 return target_string
.to_s_with_length
(total_length
)
790 # `i` repetitions of `self`
792 # assert "abc"*3 == "abcabcabc"
793 # assert "abc"*1 == "abc"
794 # assert "abc"*0 == ""
795 fun *(i
: Int): String
799 var my_length
= self.length
801 var final_length
= my_length
* i
803 var my_items
= self.items
805 var target_string
= calloc_string
((final_length
) + 1)
807 target_string
[final_length
] = '\0'
811 for iteration
in [1 .. i
] do
812 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
813 current_last
+= my_length
816 return target_string
.to_s_with_length
(final_length
)
819 redef fun to_s
do return self
823 # djb2 hash algorythm
828 var strStart
= index_from
832 while i
>= strStart
do
833 h
= (h
* 32) + h
+ self.items
[i
].ascii
841 private class FlatStringReverseIterator
842 super IndexedIterator[Char]
846 var target_items
: NativeString
850 init with_pos
(tgt
: String, pos
: Int)
853 target_items
= tgt
.items
854 curr_pos
= pos
+ tgt
.index_from
857 redef fun is_ok
do return curr_pos
>= 0
859 redef fun item
do return target_items
[curr_pos
]
861 redef fun next
do curr_pos
-= 1
863 redef fun index
do return curr_pos
- target
.index_from
867 private class FlatStringIterator
868 super IndexedIterator[Char]
872 var target_items
: NativeString
876 init with_pos
(tgt
: String, pos
: Int)
879 target_items
= tgt
.items
880 curr_pos
= pos
+ target
.index_from
883 redef fun is_ok
do return curr_pos
<= target
.index_to
885 redef fun item
do return target_items
[curr_pos
]
887 redef fun next
do curr_pos
+= 1
889 redef fun index
do return curr_pos
- target
.index_from
893 private class FlatStringCharView
896 redef type SELFTYPE: String
900 # Check that the index (+ index_from) is not larger than indexTo
901 # In other terms, if the index is valid
903 assert (index
+ target
.index_from
) <= target
.index_to
904 return target
.items
[index
+ target
.index_from
]
907 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
909 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
913 abstract class Buffer
916 redef type SELFVIEW: BufferCharView
917 redef type SELFTYPE: Buffer
919 # Modifies the char contained at pos `index`
921 # DEPRECATED : Use self.chars.[]= instead
922 fun []=(index
: Int, item
: Char) is abstract
924 # Adds a char `c` at the end of self
926 # DEPRECATED : Use self.chars.add instead
927 fun add
(c
: Char) is abstract
930 fun clear
is abstract
932 # Enlarges the subsequent array containing the chars of self
933 fun enlarge
(cap
: Int) is abstract
935 # Adds the content of string `s` at the end of self
936 fun append
(s
: String) is abstract
940 # Mutable strings of characters.
946 redef type SELFVIEW: FlatBufferCharView
947 redef type SELFTYPE: FlatBuffer
949 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
953 redef fun []=(index
, item
)
955 if index
== length
then
959 assert index
>= 0 and index
< length
965 if capacity
<= length
then enlarge
(length
+ 5)
970 redef fun clear
do length
= 0
972 redef fun empty
do return new FlatBuffer
974 redef fun enlarge
(cap
)
977 if cap
<= c
then return
978 while c
<= cap
do c
= c
* 2 + 2
979 var a
= calloc_string
(c
+1)
980 items
.copy_to
(a
, length
, 0, 0)
983 items
.copy_to
(a
, length
, 0, 0)
986 redef fun to_s
: String
989 var a
= calloc_string
(l
+1)
990 items
.copy_to
(a
, l
, 0, 0)
992 # Ensure the afterlast byte is '\0' to nul-terminated char *
995 return a
.to_s_with_length
(length
)
998 # Create a new empty string.
1004 init from
(s
: String)
1006 capacity
= s
.length
+ 1
1008 items
= calloc_string
(capacity
)
1009 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1012 # Create a new empty string with a given capacity.
1013 init with_capacity
(cap
: Int)
1016 # _items = new NativeString.calloc(cap)
1017 items
= calloc_string
(cap
+1)
1025 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1026 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1030 # Copies the content of self in `dest`
1031 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1033 var self_chars
= self.chars
1034 var dest_chars
= dest
.chars
1035 for i
in [0..len-1
] do
1036 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1040 redef fun substring
(from
, count
)
1044 if from
< 0 then from
= 0
1045 if count
> length
then count
= length
1046 if from
< count
then
1047 var r
= new FlatBuffer.with_capacity
(count
- from
)
1048 while from
< count
do
1049 r
.chars
.push
(items
[from
])
1054 return new FlatBuffer
1059 private class FlatBufferReverseIterator
1060 super IndexedIterator[Char]
1062 var target
: FlatBuffer
1064 var target_items
: NativeString
1068 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1071 target_items
= tgt
.items
1075 redef fun index
do return curr_pos
1077 redef fun is_ok
do return curr_pos
>= 0
1079 redef fun item
do return target_items
[curr_pos
]
1081 redef fun next
do curr_pos
-= 1
1085 private class FlatBufferCharView
1086 super BufferCharView
1089 redef type SELFTYPE: FlatBuffer
1091 redef fun [](index
) do return target
.items
[index
]
1093 redef fun []=(index
, item
)
1095 assert index
>= 0 and index
<= length
1096 if index
== length
then
1100 target
.items
[index
] = item
1113 fun enlarge
(cap
: Int)
1120 var my_items
= target
.items
1121 var s_length
= s
.length
1122 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1125 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1127 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1131 private class FlatBufferIterator
1132 super IndexedIterator[Char]
1134 var target
: FlatBuffer
1136 var target_items
: NativeString
1140 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1143 target_items
= tgt
.items
1147 redef fun index
do return curr_pos
1149 redef fun is_ok
do return curr_pos
< target
.length
1151 redef fun item
do return target_items
[curr_pos
]
1153 redef fun next
do curr_pos
+= 1
1157 ###############################################################################
1159 ###############################################################################
1162 # User readable representation of `self`.
1163 fun to_s
: String do return inspect
1165 # The class name of the object in NativeString format.
1166 private fun native_class_name
: NativeString is intern
1168 # The class name of the object.
1170 # assert 5.class_name == "Int"
1171 fun class_name
: String do return native_class_name
.to_s
1173 # Developer readable representation of `self`.
1174 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1177 return "<{inspect_head}>"
1180 # Return "CLASSNAME:#OBJECTID".
1181 # This function is mainly used with the redefinition of the inspect method
1182 protected fun inspect_head
: String
1184 return "{class_name}:#{object_id.to_hex}"
1187 protected fun args
: Sequence[String]
1194 # assert true.to_s == "true"
1195 # assert false.to_s == "false"
1207 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1208 # assume < to_c max const of char
1209 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1216 else if self == 0 then
1223 var pos
= digit_count
(base
) - 1
1224 while pos
>= 0 and n
> 0 do
1225 s
.chars
[pos
] = (n
% base
).to_c
1231 # C function to convert an nit Int to a NativeString (char*)
1232 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1234 # return displayable int in base 10 and signed
1236 # assert 1.to_s == "1"
1237 # assert (-123).to_s == "-123"
1239 var len
= digit_count
(10)
1240 return native_int_to_s
(len
).to_s_with_length
(len
)
1243 # return displayable int in hexadecimal (unsigned (not now))
1244 fun to_hex
: String do return to_base
(16,false)
1246 # return displayable int in base base and signed
1247 fun to_base
(base
: Int, signed
: Bool): String
1249 var l
= digit_count
(base
)
1250 var s
= new FlatBuffer.from
(" " * l
)
1251 fill_buffer
(s
, base
, signed
)
1257 # Pretty print self, print needoed decimals up to a max of 3.
1259 var str
= to_precision
( 3 )
1260 if is_inf
!= 0 or is_nan
then return str
1261 var len
= str
.length
1262 for i
in [0..len-1
] do
1264 var c
= str
.chars
[j
]
1267 else if c
== '.' then
1268 return str
.substring
( 0, j
+2 )
1270 return str
.substring
( 0, j
+1 )
1276 # `self` representation with `nb` digits after the '.'.
1277 fun to_precision
(nb
: Int): String
1279 if is_nan
then return "nan"
1281 var isinf
= self.is_inf
1284 else if isinf
== -1 then
1288 if nb
== 0 then return self.to_i
.to_s
1290 for i
in [0..nb
[ do f
= f
* 10.0
1297 if i
== 0 then return "0.0"
1301 var p1
= s
.substring
(0, s
.length-nb
)
1302 var p2
= s
.substring
(s
.length-nb
, nb
)
1303 return p1
+ "." + p2
1305 return "0." + ("0"*(nb-sl
)) + s
1309 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1313 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1314 str = malloc(size + 1);
1315 sprintf(str, "%.*f", (int)nb, recv );
1317 return NativeString_to_s( str );
1322 # assert 'x'.to_s == "x"
1325 var s
= new FlatBuffer.with_capacity
(1)
1330 # Returns true if the char is a numerical digit
1331 fun is_numeric
: Bool
1333 if self >= '0' and self <= '9'
1340 # Returns true if the char is an alpha digit
1343 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1347 # Returns true if the char is an alpha or a numeric digit
1348 fun is_alphanumeric
: Bool
1350 if self.is_numeric
or self.is_alpha
then return true
1355 redef class Collection[E
]
1356 # Concatenate elements.
1359 var s
= new FlatBuffer
1360 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1364 # Concatenate and separate each elements with `sep`.
1366 # assert [1, 2, 3].join(":") == "1:2:3"
1367 # assert [1..3].join(":") == "1:2:3"
1368 fun join
(sep
: String): String
1370 if is_empty
then return ""
1372 var s
= new FlatBuffer # Result
1377 if e
!= null then s
.append
(e
.to_s
)
1379 # Concat other items
1384 if e
!= null then s
.append
(e
.to_s
)
1391 redef class Array[E
]
1392 # Fast implementation
1395 var s
= new FlatBuffer
1400 if e
!= null then s
.append
(e
.to_s
)
1407 redef class Map[K
,V
]
1408 # Concatenate couple of 'key value'.
1409 # key and value are separated by `couple_sep`.
1410 # each couple is separated each couple with `sep`.
1412 # var m = new ArrayMap[Int, String]
1415 # assert m.join("; ", "=") == "1=one; 10=ten"
1416 fun join
(sep
: String, couple_sep
: String): String
1418 if is_empty
then return ""
1420 var s
= new FlatBuffer # Result
1426 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1428 # Concat other items
1434 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1441 ###############################################################################
1443 ###############################################################################
1445 # Native strings are simple C char *
1449 fun [](index
: Int): Char is intern
1450 fun []=(index
: Int, item
: Char) is intern
1451 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1453 # Position of the first nul character.
1454 fun cstring_length
: Int
1457 while self[l
] != '\0' do l
+= 1
1460 fun atoi
: Int is intern
1461 fun atof
: Float is extern "atof"
1465 return to_s_with_length
(cstring_length
)
1468 fun to_s_with_length
(length
: Int): String
1471 return new String.with_infos
(self, length
, 0, length
- 1)
1474 fun to_s_with_copy
: String
1476 var length
= cstring_length
1477 var new_self
= calloc_string
(length
+ 1)
1478 copy_to
(new_self
, length
, 0, 0)
1479 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1484 # StringCapable objects can create native strings
1485 interface StringCapable
1486 protected fun calloc_string
(size
: Int): NativeString is intern
1490 var _args_cache
: nullable Sequence[String]
1492 redef fun args
: Sequence[String]
1494 if _args_cache
== null then init_args
1495 return _args_cache
.as(not null)
1498 # The name of the program as given by the OS
1499 fun program_name
: String
1501 return native_argv
(0).to_s
1504 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1505 private fun init_args
1507 var argc
= native_argc
1508 var args
= new Array[String].with_capacity
(0)
1511 args
[i-1
] = native_argv
(i
).to_s
1517 # First argument of the main C function.
1518 private fun native_argc
: Int is intern
1520 # Second argument of the main C function.
1521 private fun native_argv
(i
: Int): NativeString is intern