d3b0eb90cb8b70454f3897326cc1f896a93f48a0
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
: StringCharView 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): String 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): String
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!"
282 var s
= new FlatBuffer.with_capacity
(length
)
283 for i
in self.chars
do s
.add
(i
.to_upper
)
287 # A lower case version of `self`
289 # assert "Hello World!".to_lower == "hello world!"
290 fun to_lower
: String
292 var s
= new FlatBuffer.with_capacity
(length
)
293 for i
in self.chars
do s
.add
(i
.to_lower
)
297 # Trims trailing and preceding white spaces
298 # A whitespace is defined as any character which ascii value is less than or equal to 32
300 # assert " Hello World ! ".trim == "Hello World !"
301 # assert "\na\nb\tc\t".trim == "a\nb\tc"
304 if self.length
== 0 then return self.to_s
305 # find position of the first non white space char (ascii < 32) from the start of the string
307 while self.chars
[start_pos
].ascii
<= 32 do
309 if start_pos
== length
then return ""
311 # find position of the first non white space char from the end of the string
312 var end_pos
= length
- 1
313 while self.chars
[end_pos
].ascii
<= 32 do
315 if end_pos
== start_pos
then return self.chars
[start_pos
].to_s
317 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
320 # Mangle a string to be a unique string only made of alphanumeric characters
321 fun to_cmangle
: String
323 var res
= new FlatBuffer
324 var underscore
= false
325 for c
in self.chars
do
326 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
332 res
.append
('_'.ascii
.to_s
)
335 if c
>= '0' and c
<= '9' then
338 else if c
== '_' then
343 res
.append
(c
.ascii
.to_s
)
351 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
353 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
354 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
355 fun escape_to_c
: String
357 var b
= new FlatBuffer
358 for c
in self.chars
do
361 else if c
== '\0' then
363 else if c
== '"' then
365 else if c == '\'' then
367 else if c == '\\
' then
369 else if c.ascii < 32 then
370 b.append("\\{c.ascii.to_base(8, false)}")
378 # Escape additionnal characters
379 # The result might no be legal in C but be used in other languages
381 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
382 fun escape_more_to_c(chars: String): String
384 var b = new FlatBuffer
385 for c in escape_to_c do
386 if chars.chars.has(c) then
394 # Escape to c plus braces
396 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
397 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
399 # Return a string where Nit escape sequences are transformed.
403 # assert s.length == 2
404 # var u = s.unescape_nit
405 # assert u.length == 1
406 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
407 fun unescape_nit
: String
409 var res
= new FlatBuffer.with_capacity
(self.length
)
410 var was_slash
= false
412 if not was_slash
then
423 else if c
== 'r' then
425 else if c
== 't' then
427 else if c
== '0' then
438 if o
== null then return false
439 if not o
isa Text then return false
440 if self.is_same_instance
(o
) then return true
441 if self.length
!= o
.length
then return false
442 return self.chars
== o
.chars
447 return self.chars
< o
.chars
452 # All kinds of array-based text representations.
453 abstract class FlatText
456 private var items
: NativeString
458 redef var length
: Int
472 # Abstract class for the SequenceRead compatible
473 # views on String and Buffer objects
474 abstract class StringCharView
475 super SequenceRead[Char]
480 redef type OTHER: StringCharView
482 private var target
: SELFTYPE
484 private init(tgt
: SELFTYPE)
489 redef fun is_empty
do return target
.is_empty
491 redef fun length
do return target
.length
493 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
495 # Gets a new Iterator starting at position `pos`
498 # var iter = "abcd".iterator_from(2)
499 # while iter.is_ok do
505 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
507 # Gets an iterator starting at the end and going backwards
510 # var reviter = "now step live...".reverse_iterator
511 # while reviter.is_ok do
512 # printn reviter.item
516 # Outputs : ...evil pets won
517 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
519 # Gets an iterator on the chars of self starting from `pos`
522 # var iter = "abcd".reverse_iterator_from(1)
523 # while iter.is_ok do
529 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
531 redef fun has
(c
: Char): Bool
534 if i
== c
then return true
541 if other
== null then return false
542 if not other
isa StringCharView then return false
543 var other_chars
= other
.iterator
545 if i
!= other_chars
.item
then return false
553 var self_chars
= self.iterator
554 var other_chars
= other
.iterator
556 while self_chars
.is_ok
and other_chars
.is_ok
do
557 if self_chars
.item
< other_chars
.item
then return true
558 if self_chars
.item
> other_chars
.item
then return false
563 if self_chars
.is_ok
then
571 # View on Buffer objects, extends Sequence
572 # for mutation operations
573 abstract class BufferCharView
577 redef type SELFTYPE: Buffer
581 # Immutable strings of characters.
586 redef type SELFTYPE: String
587 redef type SELFVIEW: FlatStringCharView
589 # Index in _items of the start of the string
590 private var index_from
: Int
592 # Indes in _items of the last item of the string
593 private var index_to
: Int
595 redef var chars
: StringCharView = new FlatStringCharView(self)
597 ################################################
598 # AbstractString specific methods #
599 ################################################
601 redef fun [](index
) do
603 # Check that the index (+ index_from) is not larger than indexTo
604 # In other terms, if the index is valid
605 assert (index
+ index_from
) <= index_to
606 return items
[index
+ index_from
]
609 redef fun substring
(from
: Int, count
: Int): String
615 if count
< 0 then count
= 0
619 var realFrom
= index_from
+ from
621 if (realFrom
+ count
) > index_to
then return new String.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
623 if count
== 0 then return ""
625 var to
= realFrom
+ count
- 1
627 return new String.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
630 redef fun empty
do return "".as(String)
632 redef fun to_upper
: String
634 var outstr
= calloc_string
(self.length
+ 1)
637 var myitems
= self.items
638 var index_from
= self.index_from
639 var max
= self.index_to
641 while index_from
<= max
do
642 outstr
[out_index
] = myitems
[index_from
].to_upper
647 outstr
[self.length
] = '\0'
649 return outstr
.to_s_with_length
(self.length
)
652 redef fun to_lower
: String
654 var outstr
= calloc_string
(self.length
+ 1)
657 var myitems
= self.items
658 var index_from
= self.index_from
659 var max
= self.index_to
661 while index_from
<= max
do
662 outstr
[out_index
] = myitems
[index_from
].to_lower
667 outstr
[self.length
] = '\0'
669 return outstr
.to_s_with_length
(self.length
)
672 redef fun trim
: String
674 if self.length
== 0 then return self
675 # find position of the first non white space char (ascii < 32) from the start of the string
676 var start_pos
= self.index_from
677 while items
[start_pos
].ascii
<= 32 do
679 if start_pos
== index_to
+ 1 then return ""
681 # find position of the first non white space char from the end of the string
682 var end_pos
= index_to
683 while items
[end_pos
].ascii
<= 32 do
685 if end_pos
== start_pos
then return items
[start_pos
].to_s
687 start_pos
-= index_from
688 end_pos
-= index_from
689 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
694 var i
= self.index_from
695 var imax
= self.index_to
702 ##################################################
703 # String Specific Methods #
704 ##################################################
706 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
714 # Return a null terminated char *
715 fun to_cstring
: NativeString
717 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
718 var newItems
= calloc_string
(length
+ 1)
719 self.items
.copy_to
(newItems
, length
, index_from
, 0)
720 newItems
[length
] = '\0'
728 if not other
isa String then return super
730 if self.object_id
== other
.object_id
then return true
732 var my_length
= length
734 if other
.length
!= my_length
then return false
736 var my_index
= index_from
737 var its_index
= other
.index_from
739 var last_iteration
= my_index
+ my_length
741 var itsitems
= other
.items
742 var myitems
= self.items
744 while my_index
< last_iteration
do
745 if myitems
[my_index
] != itsitems
[its_index
] then return false
753 # The comparison between two strings is done on a lexicographical basis
755 # assert ("aa" < "b") == true
758 if not other
isa String then return super
760 if self.object_id
== other
.object_id
then return false
762 var my_curr_char
: Char
763 var its_curr_char
: Char
765 var curr_id_self
= self.index_from
766 var curr_id_other
= other
.index_from
768 var my_items
= self.items
769 var its_items
= other
.items
771 var my_length
= self.length
772 var its_length
= other
.length
774 var max_iterations
= curr_id_self
+ my_length
776 while curr_id_self
< max_iterations
do
777 my_curr_char
= my_items
[curr_id_self
]
778 its_curr_char
= its_items
[curr_id_other
]
780 if my_curr_char
!= its_curr_char
then
781 if my_curr_char
< its_curr_char
then return true
789 return my_length
< its_length
792 # The concatenation of `self` with `s`
794 # assert "hello " + "world!" == "hello world!"
795 fun +(s
: String): String
797 var my_length
= self.length
798 var its_length
= s
.length
800 var total_length
= my_length
+ its_length
802 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
804 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
805 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
807 target_string
[total_length
] = '\0'
809 return target_string
.to_s_with_length
(total_length
)
812 # `i` repetitions of `self`
814 # assert "abc"*3 == "abcabcabc"
815 # assert "abc"*1 == "abc"
816 # assert "abc"*0 == ""
817 fun *(i
: Int): String
821 var my_length
= self.length
823 var final_length
= my_length
* i
825 var my_items
= self.items
827 var target_string
= calloc_string
((final_length
) + 1)
829 target_string
[final_length
] = '\0'
833 for iteration
in [1 .. i
] do
834 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
835 current_last
+= my_length
838 return target_string
.to_s_with_length
(final_length
)
841 redef fun to_s
do return self
845 # djb2 hash algorythm
850 var strStart
= index_from
854 while i
>= strStart
do
855 h
= (h
* 32) + h
+ self.items
[i
].ascii
863 private class FlatStringReverseIterator
864 super IndexedIterator[Char]
868 var target_items
: NativeString
872 init with_pos
(tgt
: String, pos
: Int)
875 target_items
= tgt
.items
876 curr_pos
= pos
+ tgt
.index_from
879 redef fun is_ok
do return curr_pos
>= 0
881 redef fun item
do return target_items
[curr_pos
]
883 redef fun next
do curr_pos
-= 1
885 redef fun index
do return curr_pos
- target
.index_from
889 private class FlatStringIterator
890 super IndexedIterator[Char]
894 var target_items
: NativeString
898 init with_pos
(tgt
: String, pos
: Int)
901 target_items
= tgt
.items
902 curr_pos
= pos
+ target
.index_from
905 redef fun is_ok
do return curr_pos
<= target
.index_to
907 redef fun item
do return target_items
[curr_pos
]
909 redef fun next
do curr_pos
+= 1
911 redef fun index
do return curr_pos
- target
.index_from
915 private class FlatStringCharView
918 redef type SELFTYPE: String
922 # Check that the index (+ index_from) is not larger than indexTo
923 # In other terms, if the index is valid
925 assert (index
+ target
.index_from
) <= target
.index_to
926 return target
.items
[index
+ target
.index_from
]
929 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
931 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
935 abstract class Buffer
938 redef type SELFVIEW: BufferCharView
939 redef type SELFTYPE: Buffer
941 # Modifies the char contained at pos `index`
943 # DEPRECATED : Use self.chars.[]= instead
944 fun []=(index
: Int, item
: Char) is abstract
946 # Adds a char `c` at the end of self
948 # DEPRECATED : Use self.chars.add instead
949 fun add
(c
: Char) is abstract
952 fun clear
is abstract
954 # Enlarges the subsequent array containing the chars of self
955 fun enlarge
(cap
: Int) is abstract
957 # Adds the content of string `s` at the end of self
958 fun append
(s
: String) is abstract
960 redef fun chars
: BufferCharView is abstract
963 # Mutable strings of characters.
969 redef type SELFVIEW: FlatBufferCharView
970 redef type SELFTYPE: FlatBuffer
972 redef var chars
: FlatBufferCharView = new FlatBufferCharView(self)
976 redef fun []=(index
, item
)
978 if index
== length
then
982 assert index
>= 0 and index
< length
988 if capacity
<= length
then enlarge
(length
+ 5)
993 redef fun clear
do length
= 0
995 redef fun empty
do return new FlatBuffer
997 redef fun enlarge
(cap
)
1000 if cap
<= c
then return
1001 while c
<= cap
do c
= c
* 2 + 2
1002 var a
= calloc_string
(c
+1)
1003 items
.copy_to
(a
, length
, 0, 0)
1006 items
.copy_to
(a
, length
, 0, 0)
1009 redef fun to_s
: String
1012 var a
= calloc_string
(l
+1)
1013 items
.copy_to
(a
, l
, 0, 0)
1015 # Ensure the afterlast byte is '\0' to nul-terminated char *
1018 return a
.to_s_with_length
(length
)
1021 # Create a new empty string.
1027 init from
(s
: String)
1029 capacity
= s
.length
+ 1
1031 items
= calloc_string
(capacity
)
1032 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1035 # Create a new empty string with a given capacity.
1036 init with_capacity
(cap
: Int)
1039 # _items = new NativeString.calloc(cap)
1040 items
= calloc_string
(cap
+1)
1048 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1049 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1053 # Copies the content of self in `dest`
1054 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1056 var self_chars
= self.chars
1057 var dest_chars
= dest
.chars
1058 for i
in [0..len-1
] do
1059 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1063 redef fun substring
(from
, count
)
1067 if from
< 0 then from
= 0
1068 if count
> length
then count
= length
1069 if from
< count
then
1070 var r
= new FlatBuffer.with_capacity
(count
- from
)
1071 while from
< count
do
1072 r
.chars
.push
(items
[from
])
1082 private class FlatBufferReverseIterator
1083 super IndexedIterator[Char]
1085 var target
: FlatBuffer
1087 var target_items
: NativeString
1091 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1094 target_items
= tgt
.items
1098 redef fun index
do return curr_pos
1100 redef fun is_ok
do return curr_pos
>= 0
1102 redef fun item
do return target_items
[curr_pos
]
1104 redef fun next
do curr_pos
-= 1
1108 private class FlatBufferCharView
1109 super BufferCharView
1112 redef type SELFTYPE: FlatBuffer
1114 redef fun [](index
) do return target
.items
[index
]
1116 redef fun []=(index
, item
)
1118 assert index
>= 0 and index
<= length
1119 if index
== length
then
1123 target
.items
[index
] = item
1136 fun enlarge
(cap
: Int)
1143 var my_items
= target
.items
1144 var s_length
= s
.length
1145 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1148 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1150 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1154 private class FlatBufferIterator
1155 super IndexedIterator[Char]
1157 var target
: FlatBuffer
1159 var target_items
: NativeString
1163 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1166 target_items
= tgt
.items
1170 redef fun index
do return curr_pos
1172 redef fun is_ok
do return curr_pos
< target
.length
1174 redef fun item
do return target_items
[curr_pos
]
1176 redef fun next
do curr_pos
+= 1
1180 ###############################################################################
1182 ###############################################################################
1185 # User readable representation of `self`.
1186 fun to_s
: String do return inspect
1188 # The class name of the object in NativeString format.
1189 private fun native_class_name
: NativeString is intern
1191 # The class name of the object.
1193 # assert 5.class_name == "Int"
1194 fun class_name
: String do return native_class_name
.to_s
1196 # Developer readable representation of `self`.
1197 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1200 return "<{inspect_head}>"
1203 # Return "CLASSNAME:#OBJECTID".
1204 # This function is mainly used with the redefinition of the inspect method
1205 protected fun inspect_head
: String
1207 return "{class_name}:#{object_id.to_hex}"
1210 protected fun args
: Sequence[String]
1217 # assert true.to_s == "true"
1218 # assert false.to_s == "false"
1230 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1231 # assume < to_c max const of char
1232 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1239 else if self == 0 then
1246 var pos
= digit_count
(base
) - 1
1247 while pos
>= 0 and n
> 0 do
1248 s
.chars
[pos
] = (n
% base
).to_c
1254 # C function to convert an nit Int to a NativeString (char*)
1255 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1257 # return displayable int in base 10 and signed
1259 # assert 1.to_s == "1"
1260 # assert (-123).to_s == "-123"
1262 var len
= digit_count
(10)
1263 return native_int_to_s
(len
).to_s_with_length
(len
)
1266 # return displayable int in hexadecimal (unsigned (not now))
1267 fun to_hex
: String do return to_base
(16,false)
1269 # return displayable int in base base and signed
1270 fun to_base
(base
: Int, signed
: Bool): String
1272 var l
= digit_count
(base
)
1273 var s
= new FlatBuffer.from
(" " * l
)
1274 fill_buffer
(s
, base
, signed
)
1280 # Pretty print self, print needoed decimals up to a max of 3.
1282 var str
= to_precision
( 3 )
1283 if is_inf
!= 0 or is_nan
then return str
1284 var len
= str
.length
1285 for i
in [0..len-1
] do
1287 var c
= str
.chars
[j
]
1290 else if c
== '.' then
1291 return str
.substring
( 0, j
+2 )
1293 return str
.substring
( 0, j
+1 )
1299 # `self` representation with `nb` digits after the '.'.
1300 fun to_precision
(nb
: Int): String
1302 if is_nan
then return "nan"
1304 var isinf
= self.is_inf
1307 else if isinf
== -1 then
1311 if nb
== 0 then return self.to_i
.to_s
1313 for i
in [0..nb
[ do f
= f
* 10.0
1320 if i
== 0 then return "0.0"
1324 var p1
= s
.substring
(0, s
.length-nb
)
1325 var p2
= s
.substring
(s
.length-nb
, nb
)
1326 return p1
+ "." + p2
1328 return "0." + ("0"*(nb-sl
)) + s
1332 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1336 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1337 str = malloc(size + 1);
1338 sprintf(str, "%.*f", (int)nb, recv );
1340 return NativeString_to_s( str );
1345 # assert 'x'.to_s == "x"
1348 var s
= new FlatBuffer.with_capacity
(1)
1353 # Returns true if the char is a numerical digit
1354 fun is_numeric
: Bool
1356 if self >= '0' and self <= '9'
1363 # Returns true if the char is an alpha digit
1366 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1370 # Returns true if the char is an alpha or a numeric digit
1371 fun is_alphanumeric
: Bool
1373 if self.is_numeric
or self.is_alpha
then return true
1378 redef class Collection[E
]
1379 # Concatenate elements.
1382 var s
= new FlatBuffer
1383 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1387 # Concatenate and separate each elements with `sep`.
1389 # assert [1, 2, 3].join(":") == "1:2:3"
1390 # assert [1..3].join(":") == "1:2:3"
1391 fun join
(sep
: String): String
1393 if is_empty
then return ""
1395 var s
= new FlatBuffer # Result
1400 if e
!= null then s
.append
(e
.to_s
)
1402 # Concat other items
1407 if e
!= null then s
.append
(e
.to_s
)
1414 redef class Array[E
]
1415 # Fast implementation
1418 var s
= new FlatBuffer
1423 if e
!= null then s
.append
(e
.to_s
)
1430 redef class Map[K
,V
]
1431 # Concatenate couple of 'key value'.
1432 # key and value are separated by `couple_sep`.
1433 # each couple is separated each couple with `sep`.
1435 # var m = new ArrayMap[Int, String]
1438 # assert m.join("; ", "=") == "1=one; 10=ten"
1439 fun join
(sep
: String, couple_sep
: String): String
1441 if is_empty
then return ""
1443 var s
= new FlatBuffer # Result
1449 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1451 # Concat other items
1457 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1464 ###############################################################################
1466 ###############################################################################
1468 # Native strings are simple C char *
1472 fun [](index
: Int): Char is intern
1473 fun []=(index
: Int, item
: Char) is intern
1474 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1476 # Position of the first nul character.
1477 fun cstring_length
: Int
1480 while self[l
] != '\0' do l
+= 1
1483 fun atoi
: Int is intern
1484 fun atof
: Float is extern "atof"
1488 return to_s_with_length
(cstring_length
)
1491 fun to_s_with_length
(length
: Int): String
1494 return new String.with_infos
(self, length
, 0, length
- 1)
1497 fun to_s_with_copy
: String
1499 var length
= cstring_length
1500 var new_self
= calloc_string
(length
+ 1)
1501 copy_to
(new_self
, length
, 0, 0)
1502 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1507 # StringCapable objects can create native strings
1508 interface StringCapable
1509 protected fun calloc_string
(size
: Int): NativeString is intern
1513 var _args_cache
: nullable Sequence[String]
1515 redef fun args
: Sequence[String]
1517 if _args_cache
== null then init_args
1518 return _args_cache
.as(not null)
1521 # The name of the program as given by the OS
1522 fun program_name
: String
1524 return native_argv
(0).to_s
1527 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1528 private fun init_args
1530 var argc
= native_argc
1531 var args
= new Array[String].with_capacity
(0)
1534 args
[i-1
] = native_argv
(i
).to_s
1540 # First argument of the main C function.
1541 private fun native_argc
: Int is intern
1543 # Second argument of the main C function.
1544 private fun native_argv
(i
: Int): NativeString is intern