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
31 # Gets a view on the chars of the Text object
32 fun chars
: StringCharView is abstract
34 # Number of characters contained in self.
35 fun length
: Int is abstract
39 # assert "abcd".substring(1, 2) == "bc"
40 # assert "abcd".substring(-1, 2) == "a"
41 # assert "abcd".substring(1, 0) == ""
42 # assert "abcd".substring(2, 5) == "cd"
44 # A `from` index < 0 will be replaced by 0.
45 # Unless a `count` value is > 0 at the same time.
46 # In this case, `from += count` and `count -= from`.
47 fun substring
(from
: Int, count
: Int): String is abstract
49 # Is the current Text empty (== "")
51 # assert not "foo".is_empty
52 fun is_empty
: Bool do return self.length
== 0
54 # Gets the first char of the Text
56 # DEPRECATED : Use self.chars.first instead
57 fun first
: Char do return self.chars
[0]
59 # Access a character at `index` in the string.
61 # assert "abcd"[2] == 'c'
63 # DEPRECATED : Use self.chars.[] instead
64 fun [](index
: Int): Char do return self.chars
[index
]
66 # Gets the index of the first occurence of 'c'
68 # Returns -1 if not found
70 # DEPRECATED : Use self.chars.index_of instead
71 fun index_of
(c
: Char): Int
73 return index_of_from
(c
, 0)
76 # Gets the last char of self
78 # DEPRECATED : Use self.chars.last instead
79 fun last
: Char do return self.chars
[length-1
]
81 # Gets the index of the first occurence of ´c´ starting from ´pos´
83 # Returns -1 if not found
85 # DEPRECATED : Use self.chars.index_of_from instead
86 fun index_of_from
(c
: Char, pos
: Int): Int
88 var iter
= self.chars
.iterator_from
(pos
)
90 if iter
.item
== c
then return iter
.index
95 # Gets the last index of char ´c´
97 # Returns -1 if not found
99 # DEPRECATED : Use self.chars.last_index_of instead
100 fun last_index_of
(c
: Char): Int
102 return last_index_of_from
(c
, length
- 1)
105 # The index of the last occurrence of an element starting from pos (in reverse order).
107 # assert "/etc/bin/test/test.nit".last_index_of_from('/', length-1) == 13
108 # assert "/etc/bin/test/test.nit".last_index_of_from('/', 12) == 8
110 # Returns -1 if not found
112 # DEPRECATED : Use self.chars.last_index_of_from instead
113 fun last_index_of_from
(item
: Char, pos
: Int): Int
115 var iter
= self.chars
.reverse_iterator_from
(pos
)
117 if iter
.item
== item
then return iter
.index
123 # Gets an iterator on the chars of self
125 # DEPRECATED : Use self.chars.iterator instead
126 fun iterator
: Iterator[Char]
128 return self.chars
.iterator
131 # Is 'c' contained in self ?
133 # DEPRECATED : Use self.chars.has instead
134 fun has
(c
: Char): Bool
136 return self.chars
.has
(c
)
139 # Gets an Array containing the chars of self
141 # DEPRECATED : Use self.chars.to_a instead
142 fun to_a
: Array[Char] do return chars
.to_a
144 # Create a substring from `self` beginning at the `from` position
146 # assert "abcd".substring_from(1) == "bcd"
147 # assert "abcd".substring_from(-1) == "abcd"
148 # assert "abcd".substring_from(2) == "cd"
150 # As with substring, a `from` index < 0 will be replaced by 0
151 fun substring_from
(from
: Int): String
154 return substring
(from
, length
- from
)
157 # Does self have a substring `str` starting from position `pos`?
159 # assert "abcd".has_substring("bc",1) == true
160 # assert "abcd".has_substring("bc",2) == false
161 fun has_substring
(str
: String, pos
: Int): Bool
163 var myiter
= self.chars
.iterator_from
(pos
)
164 var itsiter
= str
.iterator
165 while myiter
.is_ok
and itsiter
.is_ok
do
166 if myiter
.item
!= itsiter
.item
then return false
170 if itsiter
.is_ok
then return false
174 # Is this string prefixed by `prefix`?
176 # assert "abcd".has_prefix("ab") == true
177 # assert "abcbc".has_prefix("bc") == false
178 # assert "ab".has_prefix("abcd") == false
179 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
181 # Is this string suffixed by `suffix`?
183 # assert "abcd".has_suffix("abc") == false
184 # assert "abcd".has_suffix("bcd") == true
185 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
187 # If `self` contains only digits, return the corresponding integer
189 # assert "123".to_i == 123
190 # assert "-1".to_i == -1
194 return to_s
.to_cstring
.atoi
197 # If `self` contains a float, return the corresponding float
199 # assert "123".to_f == 123.0
200 # assert "-1".to_f == -1.0
201 # assert "-1.2e-3".to_f == -0.0012
205 return to_s
.to_cstring
.atof
208 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
209 fun to_hex
: Int do return a_to
(16)
211 # If `self` contains only digits and letters, return the corresponding integer in a given base
213 # assert "120".a_to(3) == 15
214 fun a_to
(base
: Int) : Int
241 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
243 # assert "123".is_numeric == true
244 # assert "1.2".is_numeric == true
245 # assert "1,2".is_numeric == true
246 # assert "1..2".is_numeric == false
249 var has_point_or_comma
= false
254 if (i
== '.' or i
== ',') and not has_point_or_comma
256 has_point_or_comma
= true
265 # A upper case version of `self`
267 # assert "Hello World!".to_upper == "HELLO WORLD!"
270 var s
= new FlatBuffer.with_capacity
(length
)
271 for i
in self.chars
do s
.add
(i
.to_upper
)
275 # A lower case version of `self`
277 # assert "Hello World!".to_lower == "hello world!"
278 fun to_lower
: String
280 var s
= new FlatBuffer.with_capacity
(length
)
281 for i
in self.chars
do s
.add
(i
.to_lower
)
285 # Trims trailing and preceding white spaces
286 # A whitespace is defined as any character which ascii value is less than or equal to 32
288 # assert " Hello World ! ".trim == "Hello World !"
289 # assert "\na\nb\tc\t".trim == "a\nb\tc"
292 if self.length
== 0 then return self.to_s
293 # find position of the first non white space char (ascii < 32) from the start of the string
295 while self.chars
[start_pos
].ascii
<= 32 do
297 if start_pos
== length
then return ""
299 # find position of the first non white space char from the end of the string
300 var end_pos
= length
- 1
301 while self.chars
[end_pos
].ascii
<= 32 do
303 if end_pos
== start_pos
then return self.chars
[start_pos
].to_s
305 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
308 # Mangle a string to be a unique string only made of alphanumeric characters
309 fun to_cmangle
: String
311 var res
= new FlatBuffer
312 var underscore
= false
313 for c
in self.chars
do
314 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
320 res
.append
('_'.ascii
.to_s
)
323 if c
>= '0' and c
<= '9' then
326 else if c
== '_' then
331 res
.append
(c
.ascii
.to_s
)
339 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
341 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
342 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
343 fun escape_to_c
: String
345 var b
= new FlatBuffer
346 for c
in self.chars
do
349 else if c
== '\0' then
351 else if c
== '"' then
353 else if c == '\'' then
355 else if c == '\\
' then
357 else if c.ascii < 32 then
358 b.append("\\{c.ascii.to_base(8, false)}")
366 # Escape additionnal characters
367 # The result might no be legal in C but be used in other languages
369 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
370 fun escape_more_to_c(chars: String): String
372 var b = new FlatBuffer
373 for c in escape_to_c do
374 if chars.chars.has(c) then
382 # Escape to c plus braces
384 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
385 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
387 # Return a string where Nit escape sequences are transformed.
391 # assert s.length == 2
392 # var u = s.unescape_nit
393 # assert u.length == 1
394 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
395 fun unescape_nit
: String
397 var res
= new FlatBuffer.with_capacity
(self.length
)
398 var was_slash
= false
400 if not was_slash
then
411 else if c
== 'r' then
413 else if c
== 't' then
415 else if c
== '0' then
426 # Common subclass for String and Buffer
427 abstract class AbstractString
430 private var items
: NativeString
432 redef var length
: Int
446 # Abstract class for the SequenceRead compatible
447 # views on String and Buffer objects
448 abstract class StringCharView
449 super SequenceRead[Char]
453 private var target
: SELFTYPE
455 private init(tgt
: SELFTYPE)
460 redef fun is_empty
do return target
.is_empty
462 redef fun length
do return target
.length
464 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
466 # Gets a new Iterator starting at position `pos`
469 # var iter = "abcd".iterator_from(2)
470 # while iter.is_ok do
476 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
478 # Gets an iterator starting at the end and going backwards
481 # var reviter = "now step live...".reverse_iterator
482 # while reviter.is_ok do
483 # printn reviter.item
487 # Outputs : ...evil pets won
488 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
490 # Gets an iterator on the chars of self starting from `pos`
493 # var iter = "abcd".reverse_iterator_from(1)
494 # while iter.is_ok do
500 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
502 redef fun has
(c
: Char): Bool
505 if i
== c
then return true
512 # View on Buffer objects, extends Sequence
513 # for mutation operations
514 abstract class BufferCharView
518 redef type SELFTYPE: Buffer
522 # Immutable strings of characters.
528 redef type OTHER: String
530 # Index in _items of the start of the string
531 private var index_from
: Int
533 # Indes in _items of the last item of the string
534 private var index_to
: Int
536 redef var chars
: StringCharView = new FlatStringCharView(self)
538 ################################################
539 # AbstractString specific methods #
540 ################################################
542 redef fun [](index
) do
544 # Check that the index (+ index_from) is not larger than indexTo
545 # In other terms, if the index is valid
546 assert (index
+ index_from
) <= index_to
547 return items
[index
+ index_from
]
550 redef fun substring
(from
: Int, count
: Int): String
556 if count
< 0 then count
= 0
560 var realFrom
= index_from
+ from
562 if (realFrom
+ count
) > index_to
then return new String.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
564 if count
== 0 then return ""
566 var to
= realFrom
+ count
- 1
568 return new String.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
571 redef fun to_upper
: String
573 var outstr
= calloc_string
(self.length
+ 1)
576 var myitems
= self.items
577 var index_from
= self.index_from
578 var max
= self.index_to
580 while index_from
<= max
do
581 outstr
[out_index
] = myitems
[index_from
].to_upper
586 outstr
[self.length
] = '\0'
588 return outstr
.to_s_with_length
(self.length
)
591 redef fun to_lower
: String
593 var outstr
= calloc_string
(self.length
+ 1)
596 var myitems
= self.items
597 var index_from
= self.index_from
598 var max
= self.index_to
600 while index_from
<= max
do
601 outstr
[out_index
] = myitems
[index_from
].to_lower
606 outstr
[self.length
] = '\0'
608 return outstr
.to_s_with_length
(self.length
)
611 redef fun trim
: String
613 if self.length
== 0 then return self
614 # find position of the first non white space char (ascii < 32) from the start of the string
615 var start_pos
= self.index_from
616 while items
[start_pos
].ascii
<= 32 do
618 if start_pos
== index_to
+ 1 then return ""
620 # find position of the first non white space char from the end of the string
621 var end_pos
= index_to
622 while items
[end_pos
].ascii
<= 32 do
624 if end_pos
== start_pos
then return items
[start_pos
].to_s
626 start_pos
-= index_from
627 end_pos
-= index_from
628 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
633 var i
= self.index_from
634 var imax
= self.index_to
641 ##################################################
642 # String Specific Methods #
643 ##################################################
645 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
653 # Return a null terminated char *
654 fun to_cstring
: NativeString
656 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
657 var newItems
= calloc_string
(length
+ 1)
658 self.items
.copy_to
(newItems
, length
, index_from
, 0)
659 newItems
[length
] = '\0'
667 if not other
isa String then return false
669 if self.object_id
== other
.object_id
then return true
671 var my_length
= length
673 if other
.length
!= my_length
then return false
675 var my_index
= index_from
676 var its_index
= other
.index_from
678 var last_iteration
= my_index
+ my_length
680 var itsitems
= other
.items
681 var myitems
= self.items
683 while my_index
< last_iteration
do
684 if myitems
[my_index
] != itsitems
[its_index
] then return false
692 # The comparison between two strings is done on a lexicographical basis
694 # assert ("aa" < "b") == true
697 if self.object_id
== other
.object_id
then return false
699 var my_curr_char
: Char
700 var its_curr_char
: Char
702 var curr_id_self
= self.index_from
703 var curr_id_other
= other
.index_from
705 var my_items
= self.items
706 var its_items
= other
.items
708 var my_length
= self.length
709 var its_length
= other
.length
711 var max_iterations
= curr_id_self
+ my_length
713 while curr_id_self
< max_iterations
do
714 my_curr_char
= my_items
[curr_id_self
]
715 its_curr_char
= its_items
[curr_id_other
]
717 if my_curr_char
!= its_curr_char
then
718 if my_curr_char
< its_curr_char
then return true
726 return my_length
< its_length
729 # The concatenation of `self` with `s`
731 # assert "hello " + "world!" == "hello world!"
732 fun +(s
: String): String
734 var my_length
= self.length
735 var its_length
= s
.length
737 var total_length
= my_length
+ its_length
739 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
741 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
742 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
744 target_string
[total_length
] = '\0'
746 return target_string
.to_s_with_length
(total_length
)
749 # `i` repetitions of `self`
751 # assert "abc"*3 == "abcabcabc"
752 # assert "abc"*1 == "abc"
753 # assert "abc"*0 == ""
754 fun *(i
: Int): String
758 var my_length
= self.length
760 var final_length
= my_length
* i
762 var my_items
= self.items
764 var target_string
= calloc_string
((final_length
) + 1)
766 target_string
[final_length
] = '\0'
770 for iteration
in [1 .. i
] do
771 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
772 current_last
+= my_length
775 return target_string
.to_s_with_length
(final_length
)
778 redef fun to_s
do return self
782 # djb2 hash algorythm
787 var strStart
= index_from
791 while i
>= strStart
do
792 h
= (h
* 32) + h
+ self.items
[i
].ascii
800 private class FlatStringReverseIterator
801 super IndexedIterator[Char]
805 var target_items
: NativeString
809 init with_pos
(tgt
: String, pos
: Int)
812 target_items
= tgt
.items
813 curr_pos
= pos
+ tgt
.index_from
816 redef fun is_ok
do return curr_pos
>= 0
818 redef fun item
do return target_items
[curr_pos
]
820 redef fun next
do curr_pos
-= 1
822 redef fun index
do return curr_pos
- target
.index_from
826 private class FlatStringIterator
827 super IndexedIterator[Char]
831 var target_items
: NativeString
835 init with_pos
(tgt
: String, pos
: Int)
838 target_items
= tgt
.items
839 curr_pos
= pos
+ target
.index_from
842 redef fun is_ok
do return curr_pos
<= target
.index_to
844 redef fun item
do return target_items
[curr_pos
]
846 redef fun next
do curr_pos
+= 1
848 redef fun index
do return curr_pos
- target
.index_from
852 private class FlatStringCharView
855 redef type SELFTYPE: String
859 # Check that the index (+ index_from) is not larger than indexTo
860 # In other terms, if the index is valid
862 assert (index
+ target
.index_from
) <= target
.index_to
863 return target
.items
[index
+ target
.index_from
]
866 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
868 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
872 abstract class Buffer
875 # Modifies the char contained at pos `index`
877 # DEPRECATED : Use self.chars.[]= instead
878 fun []=(index
: Int, item
: Char) is abstract
880 # Adds a char `c` at the end of self
882 # DEPRECATED : Use self.chars.add instead
883 fun add
(c
: Char) is abstract
886 fun clear
is abstract
888 # Enlarges the subsequent array containing the chars of self
889 fun enlarge
(cap
: Int) is abstract
891 # Adds the content of string `s` at the end of self
892 fun append
(s
: String) is abstract
894 redef fun chars
: BufferCharView is abstract
897 # Mutable strings of characters.
904 redef type OTHER: String
906 redef var chars
: FlatBufferCharView = new FlatBufferCharView(self)
910 redef fun []=(index
, item
)
912 if index
== length
then
916 assert index
>= 0 and index
< length
922 if capacity
<= length
then enlarge
(length
+ 5)
927 redef fun clear
do length
= 0
929 redef fun enlarge
(cap
)
932 if cap
<= c
then return
933 while c
<= cap
do c
= c
* 2 + 2
934 var a
= calloc_string
(c
+1)
935 items
.copy_to
(a
, length
, 0, 0)
938 items
.copy_to
(a
, length
, 0, 0)
941 redef fun to_s
: String
944 var a
= calloc_string
(l
+1)
945 items
.copy_to
(a
, l
, 0, 0)
947 # Ensure the afterlast byte is '\0' to nul-terminated char *
950 return a
.to_s_with_length
(length
)
958 while i
< l1
and i
< l2
do
959 var c1
= self.chars
[i
].ascii
960 var c2
= s
.chars
[i
].ascii
975 # Create a new empty string.
983 capacity
= s
.length
+ 1
985 items
= calloc_string
(capacity
)
986 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
989 # Create a new empty string with a given capacity.
990 init with_capacity
(cap
: Int)
993 # _items = new NativeString.calloc(cap)
994 items
= calloc_string
(cap
+1)
1002 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1003 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1009 if not o
isa FlatBuffer then return false
1011 if o
.length
!= l
then return false
1016 if it
[i
] != oit
[i
] then return false
1022 # Copies the content of self in `dest`
1023 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1025 var self_chars
= self.chars
1026 var dest_chars
= dest
.chars
1027 for i
in [0..len-1
] do
1028 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1032 redef fun substring
(from
, count
)
1036 if from
< 0 then from
= 0
1037 if count
> length
then count
= length
1038 if from
< count
then
1039 var r
= new FlatBuffer.with_capacity
(count
- from
)
1040 while from
< count
do
1041 r
.chars
.push
(items
[from
])
1051 private class FlatBufferReverseIterator
1052 super IndexedIterator[Char]
1054 var target
: FlatBuffer
1056 var target_items
: NativeString
1060 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1063 target_items
= tgt
.items
1067 redef fun index
do return curr_pos
1069 redef fun is_ok
do return curr_pos
>= 0
1071 redef fun item
do return target_items
[curr_pos
]
1073 redef fun next
do curr_pos
-= 1
1077 private class FlatBufferCharView
1078 super BufferCharView
1081 redef type SELFTYPE: FlatBuffer
1083 redef fun [](index
) do return target
.items
[index
]
1085 redef fun []=(index
, item
)
1087 assert index
>= 0 and index
<= length
1088 if index
== length
then
1092 target
.items
[index
] = item
1105 fun enlarge
(cap
: Int)
1112 var my_items
= target
.items
1113 var s_length
= s
.length
1114 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1117 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1119 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1123 private class FlatBufferIterator
1124 super IndexedIterator[Char]
1126 var target
: FlatBuffer
1128 var target_items
: NativeString
1132 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1135 target_items
= tgt
.items
1139 redef fun index
do return curr_pos
1141 redef fun is_ok
do return curr_pos
< target
.length
1143 redef fun item
do return target_items
[curr_pos
]
1145 redef fun next
do curr_pos
+= 1
1149 ###############################################################################
1151 ###############################################################################
1154 # User readable representation of `self`.
1155 fun to_s
: String do return inspect
1157 # The class name of the object in NativeString format.
1158 private fun native_class_name
: NativeString is intern
1160 # The class name of the object.
1162 # assert 5.class_name == "Int"
1163 fun class_name
: String do return native_class_name
.to_s
1165 # Developer readable representation of `self`.
1166 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1169 return "<{inspect_head}>"
1172 # Return "CLASSNAME:#OBJECTID".
1173 # This function is mainly used with the redefinition of the inspect method
1174 protected fun inspect_head
: String
1176 return "{class_name}:#{object_id.to_hex}"
1179 protected fun args
: Sequence[String]
1186 # assert true.to_s == "true"
1187 # assert false.to_s == "false"
1199 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1200 # assume < to_c max const of char
1201 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1208 else if self == 0 then
1215 var pos
= digit_count
(base
) - 1
1216 while pos
>= 0 and n
> 0 do
1217 s
.chars
[pos
] = (n
% base
).to_c
1223 # C function to convert an nit Int to a NativeString (char*)
1224 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1226 # return displayable int in base 10 and signed
1228 # assert 1.to_s == "1"
1229 # assert (-123).to_s == "-123"
1231 var len
= digit_count
(10)
1232 return native_int_to_s
(len
).to_s_with_length
(len
)
1235 # return displayable int in hexadecimal (unsigned (not now))
1236 fun to_hex
: String do return to_base
(16,false)
1238 # return displayable int in base base and signed
1239 fun to_base
(base
: Int, signed
: Bool): String
1241 var l
= digit_count
(base
)
1242 var s
= new FlatBuffer.from
(" " * l
)
1243 fill_buffer
(s
, base
, signed
)
1249 # Pretty print self, print needoed decimals up to a max of 3.
1251 var str
= to_precision
( 3 )
1252 if is_inf
!= 0 or is_nan
then return str
1253 var len
= str
.length
1254 for i
in [0..len-1
] do
1256 var c
= str
.chars
[j
]
1259 else if c
== '.' then
1260 return str
.substring
( 0, j
+2 )
1262 return str
.substring
( 0, j
+1 )
1268 # `self` representation with `nb` digits after the '.'.
1269 fun to_precision
(nb
: Int): String
1271 if is_nan
then return "nan"
1273 var isinf
= self.is_inf
1276 else if isinf
== -1 then
1280 if nb
== 0 then return self.to_i
.to_s
1282 for i
in [0..nb
[ do f
= f
* 10.0
1289 if i
== 0 then return "0.0"
1293 var p1
= s
.substring
(0, s
.length-nb
)
1294 var p2
= s
.substring
(s
.length-nb
, nb
)
1295 return p1
+ "." + p2
1297 return "0." + ("0"*(nb-sl
)) + s
1301 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1305 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1306 str = malloc(size + 1);
1307 sprintf(str, "%.*f", (int)nb, recv );
1309 return NativeString_to_s( str );
1314 # assert 'x'.to_s == "x"
1317 var s
= new FlatBuffer.with_capacity
(1)
1322 # Returns true if the char is a numerical digit
1323 fun is_numeric
: Bool
1325 if self >= '0' and self <= '9'
1332 # Returns true if the char is an alpha digit
1335 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1339 # Returns true if the char is an alpha or a numeric digit
1340 fun is_alphanumeric
: Bool
1342 if self.is_numeric
or self.is_alpha
then return true
1347 redef class Collection[E
]
1348 # Concatenate elements.
1351 var s
= new FlatBuffer
1352 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1356 # Concatenate and separate each elements with `sep`.
1358 # assert [1, 2, 3].join(":") == "1:2:3"
1359 # assert [1..3].join(":") == "1:2:3"
1360 fun join
(sep
: String): String
1362 if is_empty
then return ""
1364 var s
= new FlatBuffer # Result
1369 if e
!= null then s
.append
(e
.to_s
)
1371 # Concat other items
1376 if e
!= null then s
.append
(e
.to_s
)
1383 redef class Array[E
]
1384 # Fast implementation
1387 var s
= new FlatBuffer
1392 if e
!= null then s
.append
(e
.to_s
)
1399 redef class Map[K
,V
]
1400 # Concatenate couple of 'key value'.
1401 # key and value are separated by `couple_sep`.
1402 # each couple is separated each couple with `sep`.
1404 # var m = new ArrayMap[Int, String]
1407 # assert m.join("; ", "=") == "1=one; 10=ten"
1408 fun join
(sep
: String, couple_sep
: String): String
1410 if is_empty
then return ""
1412 var s
= new FlatBuffer # Result
1418 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1420 # Concat other items
1426 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1433 ###############################################################################
1435 ###############################################################################
1437 # Native strings are simple C char *
1441 fun [](index
: Int): Char is intern
1442 fun []=(index
: Int, item
: Char) is intern
1443 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1445 # Position of the first nul character.
1446 fun cstring_length
: Int
1449 while self[l
] != '\0' do l
+= 1
1452 fun atoi
: Int is intern
1453 fun atof
: Float is extern "atof"
1457 return to_s_with_length
(cstring_length
)
1460 fun to_s_with_length
(length
: Int): String
1463 return new String.with_infos
(self, length
, 0, length
- 1)
1466 fun to_s_with_copy
: String
1468 var length
= cstring_length
1469 var new_self
= calloc_string
(length
+ 1)
1470 copy_to
(new_self
, length
, 0, 0)
1471 return new String.with_infos
(new_self
, length
, 0, length
- 1)
1476 # StringCapable objects can create native strings
1477 interface StringCapable
1478 protected fun calloc_string
(size
: Int): NativeString is intern
1482 var _args_cache
: nullable Sequence[String]
1484 redef fun args
: Sequence[String]
1486 if _args_cache
== null then init_args
1487 return _args_cache
.as(not null)
1490 # The name of the program as given by the OS
1491 fun program_name
: String
1493 return native_argv
(0).to_s
1496 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1497 private fun init_args
1499 var argc
= native_argc
1500 var args
= new Array[String].with_capacity
(0)
1503 args
[i-1
] = native_argv
(i
).to_s
1509 # First argument of the main C function.
1510 private fun native_argc
: Int is intern
1512 # Second argument of the main C function.
1513 private fun native_argv
(i
: Int): NativeString is intern