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 # Is the current Text empty (== "")
61 # assert not "foo".is_empty
62 fun is_empty
: Bool do return self.length
== 0
64 # Returns an empty Text of the right type
65 fun empty
: SELFTYPE is abstract
67 # Gets the first char of the Text
69 # DEPRECATED : Use self.chars.first instead
70 fun first
: Char do return self.chars
[0]
72 # Access a character at `index` in the string.
74 # assert "abcd"[2] == 'c'
76 # DEPRECATED : Use self.chars.[] instead
77 fun [](index
: Int): Char do return self.chars
[index
]
79 # Gets the index of the first occurence of 'c'
81 # Returns -1 if not found
83 # DEPRECATED : Use self.chars.index_of instead
84 fun index_of
(c
: Char): Int
86 return index_of_from
(c
, 0)
89 # Gets the last char of self
91 # DEPRECATED : Use self.chars.last instead
92 fun last
: Char do return self.chars
[length-1
]
94 # Gets the index of the first occurence of ´c´ starting from ´pos´
96 # Returns -1 if not found
98 # DEPRECATED : Use self.chars.index_of_from instead
99 fun index_of_from
(c
: Char, pos
: Int): Int
101 var iter
= self.chars
.iterator_from
(pos
)
103 if iter
.item
== c
then return iter
.index
108 # Gets the last index of char ´c´
110 # Returns -1 if not found
112 # DEPRECATED : Use self.chars.last_index_of instead
113 fun last_index_of
(c
: Char): Int
115 return last_index_of_from
(c
, length
- 1)
118 # The index of the last occurrence of an element starting from pos (in reverse order).
120 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
121 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
123 # Returns -1 if not found
125 # DEPRECATED : Use self.chars.last_index_of_from instead
126 fun last_index_of_from
(item
: Char, pos
: Int): Int
128 var iter
= self.chars
.reverse_iterator_from
(pos
)
130 if iter
.item
== item
then return iter
.index
136 # Gets an iterator on the chars of self
138 # DEPRECATED : Use self.chars.iterator instead
139 fun iterator
: Iterator[Char]
141 return self.chars
.iterator
144 # Is 'c' contained in self ?
146 # DEPRECATED : Use self.chars.has instead
147 fun has
(c
: Char): Bool
149 return self.chars
.has
(c
)
152 # Gets an Array containing the chars of self
154 # DEPRECATED : Use self.chars.to_a instead
155 fun to_a
: Array[Char] do return chars
.to_a
157 # Create a substring from `self` beginning at the `from` position
159 # assert "abcd".substring_from(1) == "bcd"
160 # assert "abcd".substring_from(-1) == "abcd"
161 # assert "abcd".substring_from(2) == "cd"
163 # As with substring, a `from` index < 0 will be replaced by 0
164 fun substring_from
(from
: Int): SELFTYPE
167 return substring
(from
, length
- from
)
170 # Does self have a substring `str` starting from position `pos`?
172 # assert "abcd".has_substring("bc",1) == true
173 # assert "abcd".has_substring("bc",2) == false
174 fun has_substring
(str
: String, pos
: Int): Bool
176 var myiter
= self.chars
.iterator_from
(pos
)
177 var itsiter
= str
.iterator
178 while myiter
.is_ok
and itsiter
.is_ok
do
179 if myiter
.item
!= itsiter
.item
then return false
183 if itsiter
.is_ok
then return false
187 # Is this string prefixed by `prefix`?
189 # assert "abcd".has_prefix("ab") == true
190 # assert "abcbc".has_prefix("bc") == false
191 # assert "ab".has_prefix("abcd") == false
192 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
194 # Is this string suffixed by `suffix`?
196 # assert "abcd".has_suffix("abc") == false
197 # assert "abcd".has_suffix("bcd") == true
198 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
200 # If `self` contains only digits, return the corresponding integer
202 # assert "123".to_i == 123
203 # assert "-1".to_i == -1
207 return to_s
.to_cstring
.atoi
210 # If `self` contains a float, return the corresponding float
212 # assert "123".to_f == 123.0
213 # assert "-1".to_f == -1.0
214 # assert "-1.2e-3".to_f == -0.0012
218 return to_s
.to_cstring
.atof
221 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
222 fun to_hex
: Int do return a_to
(16)
224 # If `self` contains only digits and letters, return the corresponding integer in a given base
226 # assert "120".a_to(3) == 15
227 fun a_to
(base
: Int) : Int
254 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
256 # assert "123".is_numeric == true
257 # assert "1.2".is_numeric == true
258 # assert "1,2".is_numeric == true
259 # assert "1..2".is_numeric == false
262 var has_point_or_comma
= false
267 if (i
== '.' or i
== ',') and not has_point_or_comma
269 has_point_or_comma
= true
278 # A upper case version of `self`
280 # assert "Hello World!".to_upper == "HELLO WORLD!"
281 fun to_upper
: SELFTYPE is abstract
283 # A lower case version of `self`
285 # assert "Hello World!".to_lower == "hello world!"
286 fun to_lower
: SELFTYPE is abstract
288 # Removes the whitespaces at the beginning of self
291 var iter
= self.chars
.iterator
293 if iter
.item
.ascii
> 32 then break
296 if iter
.index
== length
then return self.empty
297 return self.substring_from
(iter
.index
)
300 # Removes the whitespaces at the end of self
303 var iter
= self.chars
.reverse_iterator
305 if iter
.item
.ascii
> 32 then break
308 if iter
.index
== length
then return self.empty
309 return self.substring
(0, iter
.index
+ 1)
312 # Trims trailing and preceding white spaces
313 # A whitespace is defined as any character which ascii value is less than or equal to 32
315 # assert " Hello World ! ".trim == "Hello World !"
316 # assert "\na\nb\tc\t".trim == "a\nb\tc"
317 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
319 # Mangle a string to be a unique string only made of alphanumeric characters
320 fun to_cmangle
: String
322 var res
= new FlatBuffer
323 var underscore
= false
324 for c
in self.chars
do
325 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
331 res
.append
('_'.ascii
.to_s
)
334 if c
>= '0' and c
<= '9' then
337 else if c
== '_' then
342 res
.append
(c
.ascii
.to_s
)
350 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
352 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
353 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
354 fun escape_to_c
: String
356 var b
= new FlatBuffer
357 for c
in self.chars
do
360 else if c
== '\0' then
362 else if c
== '"' then
364 else if c == '\'' then
366 else if c == '\\
' then
368 else if c.ascii < 32 then
369 b.append("\\{c.ascii.to_base(8, false)}")
377 # Escape additionnal characters
378 # The result might no be legal in C but be used in other languages
380 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
381 fun escape_more_to_c(chars: String): String
383 var b = new FlatBuffer
384 for c in escape_to_c do
385 if chars.chars.has(c) then
393 # Escape to c plus braces
395 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
396 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
398 # Return a string where Nit escape sequences are transformed.
402 # assert s.length == 2
403 # var u = s.unescape_nit
404 # assert u.length == 1
405 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
406 fun unescape_nit
: String
408 var res
= new FlatBuffer.with_capacity
(self.length
)
409 var was_slash
= false
411 if not was_slash
then
422 else if c
== 'r' then
424 else if c
== 't' then
426 else if c
== '0' then
437 if o
== null then return false
438 if not o
isa Text then return false
439 if self.is_same_instance
(o
) then return true
440 if self.length
!= o
.length
then return false
441 return self.chars
== o
.chars
446 return self.chars
< o
.chars
451 # All kinds of array-based text representations.
452 abstract class FlatText
455 private var items
: NativeString
457 redef var length
: Int
471 # Abstract class for the SequenceRead compatible
472 # views on String and Buffer objects
473 abstract class StringCharView
474 super SequenceRead[Char]
479 redef type OTHER: StringCharView
481 private var target
: SELFTYPE
483 private init(tgt
: SELFTYPE)
488 redef fun is_empty
do return target
.is_empty
490 redef fun length
do return target
.length
492 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
494 # Gets a new Iterator starting at position `pos`
497 # var iter = "abcd".iterator_from(2)
498 # while iter.is_ok do
504 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
506 # Gets an iterator starting at the end and going backwards
509 # var reviter = "now step live...".reverse_iterator
510 # while reviter.is_ok do
511 # printn reviter.item
515 # Outputs : ...evil pets won
516 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
518 # Gets an iterator on the chars of self starting from `pos`
521 # var iter = "abcd".reverse_iterator_from(1)
522 # while iter.is_ok do
528 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
530 redef fun has
(c
: Char): Bool
533 if i
== c
then return true
540 if other
== null then return false
541 if not other
isa StringCharView then return false
542 var other_chars
= other
.iterator
544 if i
!= other_chars
.item
then return false
552 var self_chars
= self.iterator
553 var other_chars
= other
.iterator
555 while self_chars
.is_ok
and other_chars
.is_ok
do
556 if self_chars
.item
< other_chars
.item
then return true
557 if self_chars
.item
> other_chars
.item
then return false
562 if self_chars
.is_ok
then
570 # View on Buffer objects, extends Sequence
571 # for mutation operations
572 abstract class BufferCharView
576 redef type SELFTYPE: Buffer
580 # 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.
945 redef type SELFVIEW: FlatBufferCharView
946 redef type SELFTYPE: FlatBuffer
948 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
952 redef fun []=(index
, item
)
954 if index
== length
then
958 assert index
>= 0 and index
< length
964 if capacity
<= length
then enlarge
(length
+ 5)
969 redef fun clear
do length
= 0
971 redef fun empty
do return new FlatBuffer
973 redef fun enlarge
(cap
)
976 if cap
<= c
then return
977 while c
<= cap
do c
= c
* 2 + 2
978 var a
= calloc_string
(c
+1)
979 items
.copy_to
(a
, length
, 0, 0)
982 items
.copy_to
(a
, length
, 0, 0)
985 redef fun to_s
: String
988 var a
= calloc_string
(l
+1)
989 items
.copy_to
(a
, l
, 0, 0)
991 # Ensure the afterlast byte is '\0' to nul-terminated char *
994 return a
.to_s_with_length
(length
)
997 # Create a new empty string.
1003 init from
(s
: String)
1005 capacity
= s
.length
+ 1
1007 items
= calloc_string
(capacity
)
1008 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1011 # Create a new empty string with a given capacity.
1012 init with_capacity
(cap
: Int)
1015 # _items = new NativeString.calloc(cap)
1016 items
= calloc_string
(cap
+1)
1024 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1025 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1029 # Copies the content of self in `dest`
1030 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1032 var self_chars
= self.chars
1033 var dest_chars
= dest
.chars
1034 for i
in [0..len-1
] do
1035 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1039 redef fun substring
(from
, count
)
1043 if from
< 0 then from
= 0
1044 if count
> length
then count
= length
1045 if from
< count
then
1046 var r
= new FlatBuffer.with_capacity
(count
- from
)
1047 while from
< count
do
1048 r
.chars
.push
(items
[from
])
1053 return new FlatBuffer
1058 private class FlatBufferReverseIterator
1059 super IndexedIterator[Char]
1061 var target
: FlatBuffer
1063 var target_items
: NativeString
1067 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1070 target_items
= tgt
.items
1074 redef fun index
do return curr_pos
1076 redef fun is_ok
do return curr_pos
>= 0
1078 redef fun item
do return target_items
[curr_pos
]
1080 redef fun next
do curr_pos
-= 1
1084 private class FlatBufferCharView
1085 super BufferCharView
1088 redef type SELFTYPE: FlatBuffer
1090 redef fun [](index
) do return target
.items
[index
]
1092 redef fun []=(index
, item
)
1094 assert index
>= 0 and index
<= length
1095 if index
== length
then
1099 target
.items
[index
] = item
1112 fun enlarge
(cap
: Int)
1119 var my_items
= target
.items
1120 var s_length
= s
.length
1121 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1124 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1126 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1130 private class FlatBufferIterator
1131 super IndexedIterator[Char]
1133 var target
: FlatBuffer
1135 var target_items
: NativeString
1139 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1142 target_items
= tgt
.items
1146 redef fun index
do return curr_pos
1148 redef fun is_ok
do return curr_pos
< target
.length
1150 redef fun item
do return target_items
[curr_pos
]
1152 redef fun next
do curr_pos
+= 1
1156 ###############################################################################
1158 ###############################################################################
1161 # User readable representation of `self`.
1162 fun to_s
: String do return inspect
1164 # The class name of the object in NativeString format.
1165 private fun native_class_name
: NativeString is intern
1167 # The class name of the object.
1169 # assert 5.class_name == "Int"
1170 fun class_name
: String do return native_class_name
.to_s
1172 # Developer readable representation of `self`.
1173 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1176 return "<{inspect_head}>"
1179 # Return "CLASSNAME:#OBJECTID".
1180 # This function is mainly used with the redefinition of the inspect method
1181 protected fun inspect_head
: String
1183 return "{class_name}:#{object_id.to_hex}"
1186 protected fun args
: Sequence[String]
1193 # assert true.to_s == "true"
1194 # assert false.to_s == "false"
1206 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1207 # assume < to_c max const of char
1208 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1215 else if self == 0 then
1222 var pos
= digit_count
(base
) - 1
1223 while pos
>= 0 and n
> 0 do
1224 s
.chars
[pos
] = (n
% base
).to_c
1230 # C function to convert an nit Int to a NativeString (char*)
1231 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1233 # return displayable int in base 10 and signed
1235 # assert 1.to_s == "1"
1236 # assert (-123).to_s == "-123"
1238 var len
= digit_count
(10)
1239 return native_int_to_s
(len
).to_s_with_length
(len
)
1242 # return displayable int in hexadecimal (unsigned (not now))
1243 fun to_hex
: String do return to_base
(16,false)
1245 # return displayable int in base base and signed
1246 fun to_base
(base
: Int, signed
: Bool): String
1248 var l
= digit_count
(base
)
1249 var s
= new FlatBuffer.from
(" " * l
)
1250 fill_buffer
(s
, base
, signed
)
1256 # Pretty print self, print needoed decimals up to a max of 3.
1258 var str
= to_precision
( 3 )
1259 if is_inf
!= 0 or is_nan
then return str
1260 var len
= str
.length
1261 for i
in [0..len-1
] do
1263 var c
= str
.chars
[j
]
1266 else if c
== '.' then
1267 return str
.substring
( 0, j
+2 )
1269 return str
.substring
( 0, j
+1 )
1275 # `self` representation with `nb` digits after the '.'.
1276 fun to_precision
(nb
: Int): String
1278 if is_nan
then return "nan"
1280 var isinf
= self.is_inf
1283 else if isinf
== -1 then
1287 if nb
== 0 then return self.to_i
.to_s
1289 for i
in [0..nb
[ do f
= f
* 10.0
1296 if i
== 0 then return "0.0"
1300 var p1
= s
.substring
(0, s
.length-nb
)
1301 var p2
= s
.substring
(s
.length-nb
, nb
)
1302 return p1
+ "." + p2
1304 return "0." + ("0"*(nb-sl
)) + s
1308 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1312 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1313 str = malloc(size + 1);
1314 sprintf(str, "%.*f", (int)nb, recv );
1316 return NativeString_to_s( str );
1321 # assert 'x'.to_s == "x"
1324 var s
= new FlatBuffer.with_capacity
(1)
1329 # Returns true if the char is a numerical digit
1330 fun is_numeric
: Bool
1332 if self >= '0' and self <= '9'
1339 # Returns true if the char is an alpha digit
1342 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1346 # Returns true if the char is an alpha or a numeric digit
1347 fun is_alphanumeric
: Bool
1349 if self.is_numeric
or self.is_alpha
then return true
1354 redef class Collection[E
]
1355 # Concatenate elements.
1358 var s
= new FlatBuffer
1359 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1363 # Concatenate and separate each elements with `sep`.
1365 # assert [1, 2, 3].join(":") == "1:2:3"
1366 # assert [1..3].join(":") == "1:2:3"
1367 fun join
(sep
: String): String
1369 if is_empty
then return ""
1371 var s
= new FlatBuffer # Result
1376 if e
!= null then s
.append
(e
.to_s
)
1378 # Concat other items
1383 if e
!= null then s
.append
(e
.to_s
)
1390 redef class Array[E
]
1391 # Fast implementation
1394 var s
= new FlatBuffer
1399 if e
!= null then s
.append
(e
.to_s
)
1406 redef class Map[K
,V
]
1407 # Concatenate couple of 'key value'.
1408 # key and value are separated by `couple_sep`.
1409 # each couple is separated each couple with `sep`.
1411 # var m = new ArrayMap[Int, String]
1414 # assert m.join("; ", "=") == "1=one; 10=ten"
1415 fun join
(sep
: String, couple_sep
: String): String
1417 if is_empty
then return ""
1419 var s
= new FlatBuffer # Result
1425 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1427 # Concat other items
1433 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1440 ###############################################################################
1442 ###############################################################################
1444 # Native strings are simple C char *
1448 fun [](index
: Int): Char is intern
1449 fun []=(index
: Int, item
: Char) is intern
1450 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1452 # Position of the first nul character.
1453 fun cstring_length
: Int
1456 while self[l
] != '\0' do l
+= 1
1459 fun atoi
: Int is intern
1460 fun atof
: Float is extern "atof"
1464 return to_s_with_length
(cstring_length
)
1467 fun to_s_with_length
(length
: Int): String
1470 return new String.with_infos
(self, length
, 0, length
- 1)
1473 fun to_s_with_copy
: String
1475 var length
= cstring_length
1476 var new_self
= calloc_string
(length
+ 1)
1477 copy_to
(new_self
, length
, 0, 0)
1478 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1483 # StringCapable objects can create native strings
1484 interface StringCapable
1485 protected fun calloc_string
(size
: Int): NativeString is intern
1489 var _args_cache
: nullable Sequence[String]
1491 redef fun args
: Sequence[String]
1493 if _args_cache
== null then init_args
1494 return _args_cache
.as(not null)
1497 # The name of the program as given by the OS
1498 fun program_name
: String
1500 return native_argv
(0).to_s
1503 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1504 private fun init_args
1506 var argc
= native_argc
1507 var args
= new Array[String].with_capacity
(0)
1510 args
[i-1
] = native_argv
(i
).to_s
1516 # First argument of the main C function.
1517 private fun native_argc
: Int is intern
1519 # Second argument of the main C function.
1520 private fun native_argv
(i
: Int): NativeString is intern