f348b75a600e1d20ba0b4f9d858c24c49f5a3dc1
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
42 fun chars
: SELFVIEW is abstract
44 # Number of characters contained in self.
45 fun length
: Int is abstract
49 # assert "abcd".substring(1, 2) == "bc"
50 # assert "abcd".substring(-1, 2) == "a"
51 # assert "abcd".substring(1, 0) == ""
52 # assert "abcd".substring(2, 5) == "cd"
54 # A `from` index < 0 will be replaced by 0.
55 # Unless a `count` value is > 0 at the same time.
56 # In this case, `from += count` and `count -= from`.
57 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
59 # Concatenates `o` to `self`
60 fun +(o
: Text): SELFTYPE is abstract
62 # Auto-concatenates self `i` times
63 fun *(i
: Int): SELFTYPE is abstract
65 # Is the current Text empty (== "")
67 # assert not "foo".is_empty
68 fun is_empty
: Bool do return self.length
== 0
70 # Returns an empty Text of the right type
71 fun empty
: SELFTYPE is abstract
73 # Gets the first char of the Text
75 # DEPRECATED : Use self.chars.first instead
76 fun first
: Char do return self.chars
[0]
78 # Access a character at `index` in the string.
80 # assert "abcd"[2] == 'c'
82 # DEPRECATED : Use self.chars.[] instead
83 fun [](index
: Int): Char do return self.chars
[index
]
85 # Gets the index of the first occurence of 'c'
87 # Returns -1 if not found
89 # DEPRECATED : Use self.chars.index_of instead
90 fun index_of
(c
: Char): Int
92 return index_of_from
(c
, 0)
95 # Gets the last char of self
97 # DEPRECATED : Use self.chars.last instead
98 fun last
: Char do return self.chars
[length-1
]
100 # Gets the index of the first occurence of ´c´ starting from ´pos´
102 # Returns -1 if not found
104 # DEPRECATED : Use self.chars.index_of_from instead
105 fun index_of_from
(c
: Char, pos
: Int): Int
107 var iter
= self.chars
.iterator_from
(pos
)
109 if iter
.item
== c
then return iter
.index
114 # Gets the last index of char ´c´
116 # Returns -1 if not found
118 # DEPRECATED : Use self.chars.last_index_of instead
119 fun last_index_of
(c
: Char): Int
121 return last_index_of_from
(c
, length
- 1)
124 # The index of the last occurrence of an element starting from pos (in reverse order).
126 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
127 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
129 # Returns -1 if not found
131 # DEPRECATED : Use self.chars.last_index_of_from instead
132 fun last_index_of_from
(item
: Char, pos
: Int): Int
134 var iter
= self.chars
.reverse_iterator_from
(pos
)
136 if iter
.item
== item
then return iter
.index
142 # Gets an iterator on the chars of self
144 # DEPRECATED : Use self.chars.iterator instead
145 fun iterator
: Iterator[Char]
147 return self.chars
.iterator
150 # Is 'c' contained in self ?
152 # DEPRECATED : Use self.chars.has instead
153 fun has
(c
: Char): Bool
155 return self.chars
.has
(c
)
158 # Gets an Array containing the chars of self
160 # DEPRECATED : Use self.chars.to_a instead
161 fun to_a
: Array[Char] do return chars
.to_a
163 # Create a substring from `self` beginning at the `from` position
165 # assert "abcd".substring_from(1) == "bcd"
166 # assert "abcd".substring_from(-1) == "abcd"
167 # assert "abcd".substring_from(2) == "cd"
169 # As with substring, a `from` index < 0 will be replaced by 0
170 fun substring_from
(from
: Int): SELFTYPE
173 return substring
(from
, length
- from
)
176 # Does self have a substring `str` starting from position `pos`?
178 # assert "abcd".has_substring("bc",1) == true
179 # assert "abcd".has_substring("bc",2) == false
180 fun has_substring
(str
: String, pos
: Int): Bool
182 var myiter
= self.chars
.iterator_from
(pos
)
183 var itsiter
= str
.iterator
184 while myiter
.is_ok
and itsiter
.is_ok
do
185 if myiter
.item
!= itsiter
.item
then return false
189 if itsiter
.is_ok
then return false
193 # Is this string prefixed by `prefix`?
195 # assert "abcd".has_prefix("ab") == true
196 # assert "abcbc".has_prefix("bc") == false
197 # assert "ab".has_prefix("abcd") == false
198 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
200 # Is this string suffixed by `suffix`?
202 # assert "abcd".has_suffix("abc") == false
203 # assert "abcd".has_suffix("bcd") == true
204 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
206 # If `self` contains only digits, return the corresponding integer
208 # assert "123".to_i == 123
209 # assert "-1".to_i == -1
213 return to_s
.to_cstring
.atoi
216 # If `self` contains a float, return the corresponding float
218 # assert "123".to_f == 123.0
219 # assert "-1".to_f == -1.0
220 # assert "-1.2e-3".to_f == -0.0012
224 return to_s
.to_cstring
.atof
227 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
228 fun to_hex
: Int do return a_to
(16)
230 # If `self` contains only digits and letters, return the corresponding integer in a given base
232 # assert "120".a_to(3) == 15
233 fun a_to
(base
: Int) : Int
260 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
262 # assert "123".is_numeric == true
263 # assert "1.2".is_numeric == true
264 # assert "1,2".is_numeric == true
265 # assert "1..2".is_numeric == false
268 var has_point_or_comma
= false
273 if (i
== '.' or i
== ',') and not has_point_or_comma
275 has_point_or_comma
= true
284 # A upper case version of `self`
286 # assert "Hello World!".to_upper == "HELLO WORLD!"
287 fun to_upper
: SELFTYPE is abstract
289 # A lower case version of `self`
291 # assert "Hello World!".to_lower == "hello world!"
292 fun to_lower
: SELFTYPE is abstract
294 # Removes the whitespaces at the beginning of self
297 var iter
= self.chars
.iterator
299 if iter
.item
.ascii
> 32 then break
302 if iter
.index
== length
then return self.empty
303 return self.substring_from
(iter
.index
)
306 # Removes the whitespaces at the end of self
309 var iter
= self.chars
.reverse_iterator
311 if iter
.item
.ascii
> 32 then break
314 if iter
.index
== length
then return self.empty
315 return self.substring
(0, iter
.index
+ 1)
318 # Trims trailing and preceding white spaces
319 # A whitespace is defined as any character which ascii value is less than or equal to 32
321 # assert " Hello World ! ".trim == "Hello World !"
322 # assert "\na\nb\tc\t".trim == "a\nb\tc"
323 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
325 # Mangle a string to be a unique string only made of alphanumeric characters
326 fun to_cmangle
: String
328 var res
= new FlatBuffer
329 var underscore
= false
330 for c
in self.chars
do
331 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
337 res
.append
('_'.ascii
.to_s
)
340 if c
>= '0' and c
<= '9' then
343 else if c
== '_' then
348 res
.append
(c
.ascii
.to_s
)
356 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
358 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
359 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
360 fun escape_to_c
: String
362 var b
= new FlatBuffer
363 for c
in self.chars
do
366 else if c
== '\0' then
368 else if c
== '"' then
370 else if c == '\'' then
372 else if c == '\\
' then
374 else if c.ascii < 32 then
375 b.append("\\{c.ascii.to_base(8, false)}")
383 # Escape additionnal characters
384 # The result might no be legal in C but be used in other languages
386 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
387 fun escape_more_to_c(chars: String): String
389 var b = new FlatBuffer
390 for c in escape_to_c do
391 if chars.chars.has(c) then
399 # Escape to c plus braces
401 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
402 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
404 # Return a string where Nit escape sequences are transformed.
408 # assert s.length == 2
409 # var u = s.unescape_nit
410 # assert u.length == 1
411 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
412 fun unescape_nit
: String
414 var res
= new FlatBuffer.with_capacity
(self.length
)
415 var was_slash
= false
417 if not was_slash
then
428 else if c
== 'r' then
430 else if c
== 't' then
432 else if c
== '0' then
443 if o
== null then return false
444 if not o
isa Text then return false
445 if self.is_same_instance
(o
) then return true
446 if self.length
!= o
.length
then return false
447 return self.chars
== o
.chars
452 return self.chars
< o
.chars
457 # All kinds of array-based text representations.
458 abstract class FlatText
461 private var items
: NativeString
463 redef var length
: Int
477 # Abstract class for the SequenceRead compatible
478 # views on String and Buffer objects
479 abstract class StringCharView
480 super SequenceRead[Char]
485 redef type OTHER: StringCharView
487 private var target
: SELFTYPE
489 private init(tgt
: SELFTYPE)
494 redef fun is_empty
do return target
.is_empty
496 redef fun length
do return target
.length
498 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
500 # Gets a new Iterator starting at position `pos`
503 # var iter = "abcd".iterator_from(2)
504 # while iter.is_ok do
510 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
512 # Gets an iterator starting at the end and going backwards
515 # var reviter = "now step live...".reverse_iterator
516 # while reviter.is_ok do
517 # printn reviter.item
521 # Outputs : ...evil pets won
522 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
524 # Gets an iterator on the chars of self starting from `pos`
527 # var iter = "abcd".reverse_iterator_from(1)
528 # while iter.is_ok do
534 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
536 redef fun has
(c
: Char): Bool
539 if i
== c
then return true
546 if other
== null then return false
547 if not other
isa StringCharView then return false
548 var other_chars
= other
.iterator
550 if i
!= other_chars
.item
then return false
558 var self_chars
= self.iterator
559 var other_chars
= other
.iterator
561 while self_chars
.is_ok
and other_chars
.is_ok
do
562 if self_chars
.item
< other_chars
.item
then return true
563 if self_chars
.item
> other_chars
.item
then return false
568 if self_chars
.is_ok
then
576 # View on Buffer objects, extends Sequence
577 # for mutation operations
578 abstract class BufferCharView
582 redef type SELFTYPE: Buffer
586 # Immutable strings of characters.
590 redef type SELFTYPE: String
591 redef type SELFVIEW: FlatStringCharView
593 # Index in _items of the start of the string
594 private var index_from
: Int
596 # Indes in _items of the last item of the string
597 private var index_to
: Int
599 redef var chars
: SELFVIEW = new FlatStringCharView(self)
601 ################################################
602 # AbstractString specific methods #
603 ################################################
605 redef fun [](index
) do
607 # Check that the index (+ index_from) is not larger than indexTo
608 # In other terms, if the index is valid
609 assert (index
+ index_from
) <= index_to
610 return items
[index
+ index_from
]
613 redef fun substring
(from
, count
)
619 if count
< 0 then count
= 0
623 var realFrom
= index_from
+ from
625 if (realFrom
+ count
) > index_to
then return new String.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
627 if count
== 0 then return ""
629 var to
= realFrom
+ count
- 1
631 return new String.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
634 redef fun empty
do return "".as(String)
638 var outstr
= calloc_string
(self.length
+ 1)
641 var myitems
= self.items
642 var index_from
= self.index_from
643 var max
= self.index_to
645 while index_from
<= max
do
646 outstr
[out_index
] = myitems
[index_from
].to_upper
651 outstr
[self.length
] = '\0'
653 return outstr
.to_s_with_length
(self.length
)
658 var outstr
= calloc_string
(self.length
+ 1)
661 var myitems
= self.items
662 var index_from
= self.index_from
663 var max
= self.index_to
665 while index_from
<= max
do
666 outstr
[out_index
] = myitems
[index_from
].to_lower
671 outstr
[self.length
] = '\0'
673 return outstr
.to_s_with_length
(self.length
)
678 var i
= self.index_from
679 var imax
= self.index_to
686 ##################################################
687 # String Specific Methods #
688 ##################################################
690 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
698 # Return a null terminated char *
699 fun to_cstring
: NativeString
701 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
702 var newItems
= calloc_string
(length
+ 1)
703 self.items
.copy_to
(newItems
, length
, index_from
, 0)
704 newItems
[length
] = '\0'
712 if not other
isa String then return super
714 if self.object_id
== other
.object_id
then return true
716 var my_length
= length
718 if other
.length
!= my_length
then return false
720 var my_index
= index_from
721 var its_index
= other
.index_from
723 var last_iteration
= my_index
+ my_length
725 var itsitems
= other
.items
726 var myitems
= self.items
728 while my_index
< last_iteration
do
729 if myitems
[my_index
] != itsitems
[its_index
] then return false
737 # The comparison between two strings is done on a lexicographical basis
739 # assert ("aa" < "b") == true
742 if not other
isa String then return super
744 if self.object_id
== other
.object_id
then return false
746 var my_curr_char
: Char
747 var its_curr_char
: Char
749 var curr_id_self
= self.index_from
750 var curr_id_other
= other
.index_from
752 var my_items
= self.items
753 var its_items
= other
.items
755 var my_length
= self.length
756 var its_length
= other
.length
758 var max_iterations
= curr_id_self
+ my_length
760 while curr_id_self
< max_iterations
do
761 my_curr_char
= my_items
[curr_id_self
]
762 its_curr_char
= its_items
[curr_id_other
]
764 if my_curr_char
!= its_curr_char
then
765 if my_curr_char
< its_curr_char
then return true
773 return my_length
< its_length
776 # The concatenation of `self` with `s`
778 # assert "hello " + "world!" == "hello world!"
781 var my_length
= self.length
782 var its_length
= s
.length
784 var total_length
= my_length
+ its_length
786 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
788 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
790 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
791 else if s
isa FlatBuffer then
792 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
794 var curr_pos
= my_length
796 target_string
[curr_pos
] = i
801 target_string
[total_length
] = '\0'
803 return target_string
.to_s_with_length
(total_length
)
806 # assert "abc"*3 == "abcabcabc"
807 # assert "abc"*1 == "abc"
808 # assert "abc"*0 == ""
813 var my_length
= self.length
815 var final_length
= my_length
* i
817 var my_items
= self.items
819 var target_string
= calloc_string
((final_length
) + 1)
821 target_string
[final_length
] = '\0'
825 for iteration
in [1 .. i
] do
826 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
827 current_last
+= my_length
830 return target_string
.to_s_with_length
(final_length
)
833 redef fun to_s
do return self
837 # djb2 hash algorythm
842 var strStart
= index_from
846 while i
>= strStart
do
847 h
= (h
* 32) + h
+ self.items
[i
].ascii
855 private class FlatStringReverseIterator
856 super IndexedIterator[Char]
860 var target_items
: NativeString
864 init with_pos
(tgt
: String, pos
: Int)
867 target_items
= tgt
.items
868 curr_pos
= pos
+ tgt
.index_from
871 redef fun is_ok
do return curr_pos
>= 0
873 redef fun item
do return target_items
[curr_pos
]
875 redef fun next
do curr_pos
-= 1
877 redef fun index
do return curr_pos
- target
.index_from
881 private class FlatStringIterator
882 super IndexedIterator[Char]
886 var target_items
: NativeString
890 init with_pos
(tgt
: String, pos
: Int)
893 target_items
= tgt
.items
894 curr_pos
= pos
+ target
.index_from
897 redef fun is_ok
do return curr_pos
<= target
.index_to
899 redef fun item
do return target_items
[curr_pos
]
901 redef fun next
do curr_pos
+= 1
903 redef fun index
do return curr_pos
- target
.index_from
907 private class FlatStringCharView
910 redef type SELFTYPE: String
914 # Check that the index (+ index_from) is not larger than indexTo
915 # In other terms, if the index is valid
917 assert (index
+ target
.index_from
) <= target
.index_to
918 return target
.items
[index
+ target
.index_from
]
921 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
923 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
927 abstract class Buffer
930 redef type SELFVIEW: BufferCharView
931 redef type SELFTYPE: Buffer
933 # Modifies the char contained at pos `index`
935 # DEPRECATED : Use self.chars.[]= instead
936 fun []=(index
: Int, item
: Char) is abstract
938 # Adds a char `c` at the end of self
940 # DEPRECATED : Use self.chars.add instead
941 fun add
(c
: Char) is abstract
944 fun clear
is abstract
946 # Enlarges the subsequent array containing the chars of self
947 fun enlarge
(cap
: Int) is abstract
949 # Adds the content of string `s` at the end of self
950 fun append
(s
: String) is abstract
954 # Mutable strings of characters.
959 redef type SELFVIEW: FlatBufferCharView
960 redef type SELFTYPE: FlatBuffer
962 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
966 redef fun []=(index
, item
)
968 if index
== length
then
972 assert index
>= 0 and index
< length
978 if capacity
<= length
then enlarge
(length
+ 5)
983 redef fun clear
do length
= 0
985 redef fun empty
do return new FlatBuffer
987 redef fun enlarge
(cap
)
990 if cap
<= c
then return
991 while c
<= cap
do c
= c
* 2 + 2
992 var a
= calloc_string
(c
+1)
993 items
.copy_to
(a
, length
, 0, 0)
996 items
.copy_to
(a
, length
, 0, 0)
999 redef fun to_s
: String
1002 var a
= calloc_string
(l
+1)
1003 items
.copy_to
(a
, l
, 0, 0)
1005 # Ensure the afterlast byte is '\0' to nul-terminated char *
1008 return a
.to_s_with_length
(length
)
1011 # Create a new empty string.
1017 init from
(s
: String)
1019 capacity
= s
.length
+ 1
1021 items
= calloc_string
(capacity
)
1022 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1025 # Create a new empty string with a given capacity.
1026 init with_capacity
(cap
: Int)
1029 # _items = new NativeString.calloc(cap)
1030 items
= calloc_string
(cap
+1)
1038 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1039 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1043 # Copies the content of self in `dest`
1044 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1046 var self_chars
= self.chars
1047 var dest_chars
= dest
.chars
1048 for i
in [0..len-1
] do
1049 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1053 redef fun substring
(from
, count
)
1057 if from
< 0 then from
= 0
1058 if count
> length
then count
= length
1059 if from
< count
then
1060 var r
= new FlatBuffer.with_capacity
(count
- from
)
1061 while from
< count
do
1062 r
.chars
.push
(items
[from
])
1067 return new FlatBuffer
1073 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1074 new_buf
.append
(self)
1075 new_buf
.append
(other
)
1079 redef fun *(repeats
)
1081 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1082 for i
in [0..repeats
[ do
1083 new_buf
.append
(self)
1089 private class FlatBufferReverseIterator
1090 super IndexedIterator[Char]
1092 var target
: FlatBuffer
1094 var target_items
: NativeString
1098 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1101 target_items
= tgt
.items
1105 redef fun index
do return curr_pos
1107 redef fun is_ok
do return curr_pos
>= 0
1109 redef fun item
do return target_items
[curr_pos
]
1111 redef fun next
do curr_pos
-= 1
1115 private class FlatBufferCharView
1116 super BufferCharView
1119 redef type SELFTYPE: FlatBuffer
1121 redef fun [](index
) do return target
.items
[index
]
1123 redef fun []=(index
, item
)
1125 assert index
>= 0 and index
<= length
1126 if index
== length
then
1130 target
.items
[index
] = item
1143 fun enlarge
(cap
: Int)
1150 var my_items
= target
.items
1151 var s_length
= s
.length
1152 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1155 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1157 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1161 private class FlatBufferIterator
1162 super IndexedIterator[Char]
1164 var target
: FlatBuffer
1166 var target_items
: NativeString
1170 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1173 target_items
= tgt
.items
1177 redef fun index
do return curr_pos
1179 redef fun is_ok
do return curr_pos
< target
.length
1181 redef fun item
do return target_items
[curr_pos
]
1183 redef fun next
do curr_pos
+= 1
1187 ###############################################################################
1189 ###############################################################################
1192 # User readable representation of `self`.
1193 fun to_s
: String do return inspect
1195 # The class name of the object in NativeString format.
1196 private fun native_class_name
: NativeString is intern
1198 # The class name of the object.
1200 # assert 5.class_name == "Int"
1201 fun class_name
: String do return native_class_name
.to_s
1203 # Developer readable representation of `self`.
1204 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1207 return "<{inspect_head}>"
1210 # Return "CLASSNAME:#OBJECTID".
1211 # This function is mainly used with the redefinition of the inspect method
1212 protected fun inspect_head
: String
1214 return "{class_name}:#{object_id.to_hex}"
1217 protected fun args
: Sequence[String]
1224 # assert true.to_s == "true"
1225 # assert false.to_s == "false"
1237 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1238 # assume < to_c max const of char
1239 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1246 else if self == 0 then
1253 var pos
= digit_count
(base
) - 1
1254 while pos
>= 0 and n
> 0 do
1255 s
.chars
[pos
] = (n
% base
).to_c
1261 # C function to convert an nit Int to a NativeString (char*)
1262 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1264 # return displayable int in base 10 and signed
1266 # assert 1.to_s == "1"
1267 # assert (-123).to_s == "-123"
1269 var len
= digit_count
(10)
1270 return native_int_to_s
(len
).to_s_with_length
(len
)
1273 # return displayable int in hexadecimal (unsigned (not now))
1274 fun to_hex
: String do return to_base
(16,false)
1276 # return displayable int in base base and signed
1277 fun to_base
(base
: Int, signed
: Bool): String
1279 var l
= digit_count
(base
)
1280 var s
= new FlatBuffer.from
(" " * l
)
1281 fill_buffer
(s
, base
, signed
)
1287 # Pretty print self, print needoed decimals up to a max of 3.
1289 var str
= to_precision
( 3 )
1290 if is_inf
!= 0 or is_nan
then return str
1291 var len
= str
.length
1292 for i
in [0..len-1
] do
1294 var c
= str
.chars
[j
]
1297 else if c
== '.' then
1298 return str
.substring
( 0, j
+2 )
1300 return str
.substring
( 0, j
+1 )
1306 # `self` representation with `nb` digits after the '.'.
1307 fun to_precision
(nb
: Int): String
1309 if is_nan
then return "nan"
1311 var isinf
= self.is_inf
1314 else if isinf
== -1 then
1318 if nb
== 0 then return self.to_i
.to_s
1320 for i
in [0..nb
[ do f
= f
* 10.0
1327 if i
== 0 then return "0.0"
1331 var p1
= s
.substring
(0, s
.length-nb
)
1332 var p2
= s
.substring
(s
.length-nb
, nb
)
1333 return p1
+ "." + p2
1335 return "0." + ("0"*(nb-sl
)) + s
1339 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1343 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1344 str = malloc(size + 1);
1345 sprintf(str, "%.*f", (int)nb, recv );
1347 return NativeString_to_s( str );
1352 # assert 'x'.to_s == "x"
1355 var s
= new FlatBuffer.with_capacity
(1)
1360 # Returns true if the char is a numerical digit
1361 fun is_numeric
: Bool
1363 if self >= '0' and self <= '9'
1370 # Returns true if the char is an alpha digit
1373 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1377 # Returns true if the char is an alpha or a numeric digit
1378 fun is_alphanumeric
: Bool
1380 if self.is_numeric
or self.is_alpha
then return true
1385 redef class Collection[E
]
1386 # Concatenate elements.
1389 var s
= new FlatBuffer
1390 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1394 # Concatenate and separate each elements with `sep`.
1396 # assert [1, 2, 3].join(":") == "1:2:3"
1397 # assert [1..3].join(":") == "1:2:3"
1398 fun join
(sep
: String): String
1400 if is_empty
then return ""
1402 var s
= new FlatBuffer # Result
1407 if e
!= null then s
.append
(e
.to_s
)
1409 # Concat other items
1414 if e
!= null then s
.append
(e
.to_s
)
1421 redef class Array[E
]
1422 # Fast implementation
1425 var s
= new FlatBuffer
1430 if e
!= null then s
.append
(e
.to_s
)
1437 redef class Map[K
,V
]
1438 # Concatenate couple of 'key value'.
1439 # key and value are separated by `couple_sep`.
1440 # each couple is separated each couple with `sep`.
1442 # var m = new ArrayMap[Int, String]
1445 # assert m.join("; ", "=") == "1=one; 10=ten"
1446 fun join
(sep
: String, couple_sep
: String): String
1448 if is_empty
then return ""
1450 var s
= new FlatBuffer # Result
1456 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1458 # Concat other items
1464 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1471 ###############################################################################
1473 ###############################################################################
1475 # Native strings are simple C char *
1479 fun [](index
: Int): Char is intern
1480 fun []=(index
: Int, item
: Char) is intern
1481 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1483 # Position of the first nul character.
1484 fun cstring_length
: Int
1487 while self[l
] != '\0' do l
+= 1
1490 fun atoi
: Int is intern
1491 fun atof
: Float is extern "atof"
1495 return to_s_with_length
(cstring_length
)
1498 fun to_s_with_length
(length
: Int): String
1501 return new String.with_infos
(self, length
, 0, length
- 1)
1504 fun to_s_with_copy
: String
1506 var length
= cstring_length
1507 var new_self
= calloc_string
(length
+ 1)
1508 copy_to
(new_self
, length
, 0, 0)
1509 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1514 # StringCapable objects can create native strings
1515 interface StringCapable
1516 protected fun calloc_string
(size
: Int): NativeString is intern
1520 var _args_cache
: nullable Sequence[String]
1522 redef fun args
: Sequence[String]
1524 if _args_cache
== null then init_args
1525 return _args_cache
.as(not null)
1528 # The name of the program as given by the OS
1529 fun program_name
: String
1531 return native_argv
(0).to_s
1534 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1535 private fun init_args
1537 var argc
= native_argc
1538 var args
= new Array[String].with_capacity
(0)
1541 args
[i-1
] = native_argv
(i
).to_s
1547 # First argument of the main C function.
1548 private fun native_argc
: Int is intern
1550 # Second argument of the main C function.
1551 private fun native_argv
(i
: Int): NativeString is intern