d41600003f9e3e4a4035733797f1245517a3f851
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 abstract class String
589 redef type SELFTYPE: String
591 redef fun to_s
do return self
595 # Immutable strings of characters.
600 redef type SELFTYPE: FlatString
601 redef type SELFVIEW: FlatStringCharView
603 # Index in _items of the start of the string
604 private var index_from
: Int
606 # Indes in _items of the last item of the string
607 private var index_to
: Int
609 redef var chars
: SELFVIEW = new FlatStringCharView(self)
611 ################################################
612 # AbstractString specific methods #
613 ################################################
615 redef fun [](index
) do
617 # Check that the index (+ index_from) is not larger than indexTo
618 # In other terms, if the index is valid
619 assert (index
+ index_from
) <= index_to
620 return items
[index
+ index_from
]
623 redef fun substring
(from
, count
)
629 if count
< 0 then count
= 0
633 var realFrom
= index_from
+ from
635 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
637 if count
== 0 then return empty
639 var to
= realFrom
+ count
- 1
641 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
644 redef fun empty
do return "".as(FlatString)
648 var outstr
= calloc_string
(self.length
+ 1)
651 var myitems
= self.items
652 var index_from
= self.index_from
653 var max
= self.index_to
655 while index_from
<= max
do
656 outstr
[out_index
] = myitems
[index_from
].to_upper
661 outstr
[self.length
] = '\0'
663 return outstr
.to_s_with_length
(self.length
)
668 var outstr
= calloc_string
(self.length
+ 1)
671 var myitems
= self.items
672 var index_from
= self.index_from
673 var max
= self.index_to
675 while index_from
<= max
do
676 outstr
[out_index
] = myitems
[index_from
].to_lower
681 outstr
[self.length
] = '\0'
683 return outstr
.to_s_with_length
(self.length
)
688 var i
= self.index_from
689 var imax
= self.index_to
696 ##################################################
697 # String Specific Methods #
698 ##################################################
700 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
708 # Return a null terminated char *
709 fun to_cstring
: NativeString
711 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
712 var newItems
= calloc_string
(length
+ 1)
713 self.items
.copy_to
(newItems
, length
, index_from
, 0)
714 newItems
[length
] = '\0'
722 if not other
isa FlatString then return super
724 if self.object_id
== other
.object_id
then return true
726 var my_length
= length
728 if other
.length
!= my_length
then return false
730 var my_index
= index_from
731 var its_index
= other
.index_from
733 var last_iteration
= my_index
+ my_length
735 var itsitems
= other
.items
736 var myitems
= self.items
738 while my_index
< last_iteration
do
739 if myitems
[my_index
] != itsitems
[its_index
] then return false
747 # The comparison between two strings is done on a lexicographical basis
749 # assert ("aa" < "b") == true
752 if not other
isa FlatString then return super
754 if self.object_id
== other
.object_id
then return false
756 var my_curr_char
: Char
757 var its_curr_char
: Char
759 var curr_id_self
= self.index_from
760 var curr_id_other
= other
.index_from
762 var my_items
= self.items
763 var its_items
= other
.items
765 var my_length
= self.length
766 var its_length
= other
.length
768 var max_iterations
= curr_id_self
+ my_length
770 while curr_id_self
< max_iterations
do
771 my_curr_char
= my_items
[curr_id_self
]
772 its_curr_char
= its_items
[curr_id_other
]
774 if my_curr_char
!= its_curr_char
then
775 if my_curr_char
< its_curr_char
then return true
783 return my_length
< its_length
786 # The concatenation of `self` with `s`
788 # assert "hello " + "world!" == "hello world!"
791 var my_length
= self.length
792 var its_length
= s
.length
794 var total_length
= my_length
+ its_length
796 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
798 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
799 if s
isa FlatString then
800 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
801 else if s
isa FlatBuffer then
802 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
804 var curr_pos
= my_length
806 target_string
[curr_pos
] = i
811 target_string
[total_length
] = '\0'
813 return target_string
.to_s_with_length
(total_length
)
816 # assert "abc"*3 == "abcabcabc"
817 # assert "abc"*1 == "abc"
818 # assert "abc"*0 == ""
823 var my_length
= self.length
825 var final_length
= my_length
* i
827 var my_items
= self.items
829 var target_string
= calloc_string
((final_length
) + 1)
831 target_string
[final_length
] = '\0'
835 for iteration
in [1 .. i
] do
836 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
837 current_last
+= my_length
840 return target_string
.to_s_with_length
(final_length
)
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]
866 var target
: FlatString
868 var target_items
: NativeString
872 init with_pos
(tgt
: FlatString, 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]
892 var target
: FlatString
894 var target_items
: NativeString
898 init with_pos
(tgt
: FlatString, 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: FlatString
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 text `s` at the end of self
958 fun append
(s
: Text) is abstract
962 # Mutable strings of characters.
967 redef type SELFVIEW: FlatBufferCharView
968 redef type SELFTYPE: FlatBuffer
970 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
974 redef fun []=(index
, item
)
976 if index
== length
then
980 assert index
>= 0 and index
< length
986 if capacity
<= length
then enlarge
(length
+ 5)
991 redef fun clear
do length
= 0
993 redef fun empty
do return new FlatBuffer
995 redef fun enlarge
(cap
)
998 if cap
<= c
then return
999 while c
<= cap
do c
= c
* 2 + 2
1000 var a
= calloc_string
(c
+1)
1001 items
.copy_to
(a
, length
, 0, 0)
1004 items
.copy_to
(a
, length
, 0, 0)
1007 redef fun to_s
: String
1010 var a
= calloc_string
(l
+1)
1011 items
.copy_to
(a
, l
, 0, 0)
1013 # Ensure the afterlast byte is '\0' to nul-terminated char *
1016 return a
.to_s_with_length
(length
)
1019 # Create a new empty string.
1025 init from
(s
: String)
1027 capacity
= s
.length
+ 1
1029 items
= calloc_string
(capacity
)
1030 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1033 # Create a new empty string with a given capacity.
1034 init with_capacity
(cap
: Int)
1037 # _items = new NativeString.calloc(cap)
1038 items
= calloc_string
(cap
+1)
1046 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1047 if s
isa FlatString then
1048 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1049 else if s
isa FlatBuffer then
1050 s
.items
.copy_to
(items
, sl
, 0, length
)
1052 var curr_pos
= self.length
1061 # Copies the content of self in `dest`
1062 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1064 var self_chars
= self.chars
1065 var dest_chars
= dest
.chars
1066 for i
in [0..len-1
] do
1067 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1071 redef fun substring
(from
, count
)
1075 if from
< 0 then from
= 0
1076 if count
> length
then count
= length
1077 if from
< count
then
1078 var r
= new FlatBuffer.with_capacity
(count
- from
)
1079 while from
< count
do
1080 r
.chars
.push
(items
[from
])
1085 return new FlatBuffer
1091 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1092 new_buf
.append
(self)
1093 new_buf
.append
(other
)
1097 redef fun *(repeats
)
1099 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1100 for i
in [0..repeats
[ do
1101 new_buf
.append
(self)
1107 private class FlatBufferReverseIterator
1108 super IndexedIterator[Char]
1110 var target
: FlatBuffer
1112 var target_items
: NativeString
1116 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1119 target_items
= tgt
.items
1123 redef fun index
do return curr_pos
1125 redef fun is_ok
do return curr_pos
>= 0
1127 redef fun item
do return target_items
[curr_pos
]
1129 redef fun next
do curr_pos
-= 1
1133 private class FlatBufferCharView
1134 super BufferCharView
1137 redef type SELFTYPE: FlatBuffer
1139 redef fun [](index
) do return target
.items
[index
]
1141 redef fun []=(index
, item
)
1143 assert index
>= 0 and index
<= length
1144 if index
== length
then
1148 target
.items
[index
] = item
1161 fun enlarge
(cap
: Int)
1168 var my_items
= target
.items
1169 var s_length
= s
.length
1170 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1173 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1175 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1179 private class FlatBufferIterator
1180 super IndexedIterator[Char]
1182 var target
: FlatBuffer
1184 var target_items
: NativeString
1188 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1191 target_items
= tgt
.items
1195 redef fun index
do return curr_pos
1197 redef fun is_ok
do return curr_pos
< target
.length
1199 redef fun item
do return target_items
[curr_pos
]
1201 redef fun next
do curr_pos
+= 1
1205 ###############################################################################
1207 ###############################################################################
1210 # User readable representation of `self`.
1211 fun to_s
: String do return inspect
1213 # The class name of the object in NativeString format.
1214 private fun native_class_name
: NativeString is intern
1216 # The class name of the object.
1218 # assert 5.class_name == "Int"
1219 fun class_name
: String do return native_class_name
.to_s
1221 # Developer readable representation of `self`.
1222 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1225 return "<{inspect_head}>"
1228 # Return "CLASSNAME:#OBJECTID".
1229 # This function is mainly used with the redefinition of the inspect method
1230 protected fun inspect_head
: String
1232 return "{class_name}:#{object_id.to_hex}"
1235 protected fun args
: Sequence[String]
1242 # assert true.to_s == "true"
1243 # assert false.to_s == "false"
1255 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1256 # assume < to_c max const of char
1257 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1264 else if self == 0 then
1271 var pos
= digit_count
(base
) - 1
1272 while pos
>= 0 and n
> 0 do
1273 s
.chars
[pos
] = (n
% base
).to_c
1279 # C function to convert an nit Int to a NativeString (char*)
1280 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1282 # return displayable int in base 10 and signed
1284 # assert 1.to_s == "1"
1285 # assert (-123).to_s == "-123"
1287 var len
= digit_count
(10)
1288 return native_int_to_s
(len
).to_s_with_length
(len
)
1291 # return displayable int in hexadecimal (unsigned (not now))
1292 fun to_hex
: String do return to_base
(16,false)
1294 # return displayable int in base base and signed
1295 fun to_base
(base
: Int, signed
: Bool): String
1297 var l
= digit_count
(base
)
1298 var s
= new FlatBuffer.from
(" " * l
)
1299 fill_buffer
(s
, base
, signed
)
1305 # Pretty print self, print needoed decimals up to a max of 3.
1307 var str
= to_precision
( 3 )
1308 if is_inf
!= 0 or is_nan
then return str
1309 var len
= str
.length
1310 for i
in [0..len-1
] do
1312 var c
= str
.chars
[j
]
1315 else if c
== '.' then
1316 return str
.substring
( 0, j
+2 )
1318 return str
.substring
( 0, j
+1 )
1324 # `self` representation with `nb` digits after the '.'.
1325 fun to_precision
(nb
: Int): String
1327 if is_nan
then return "nan"
1329 var isinf
= self.is_inf
1332 else if isinf
== -1 then
1336 if nb
== 0 then return self.to_i
.to_s
1338 for i
in [0..nb
[ do f
= f
* 10.0
1345 if i
== 0 then return "0.0"
1349 var p1
= s
.substring
(0, s
.length-nb
)
1350 var p2
= s
.substring
(s
.length-nb
, nb
)
1351 return p1
+ "." + p2
1353 return "0." + ("0"*(nb-sl
)) + s
1357 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1361 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1362 str = malloc(size + 1);
1363 sprintf(str, "%.*f", (int)nb, recv );
1365 return NativeString_to_s( str );
1370 # assert 'x'.to_s == "x"
1373 var s
= new FlatBuffer.with_capacity
(1)
1378 # Returns true if the char is a numerical digit
1379 fun is_numeric
: Bool
1381 if self >= '0' and self <= '9'
1388 # Returns true if the char is an alpha digit
1391 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1395 # Returns true if the char is an alpha or a numeric digit
1396 fun is_alphanumeric
: Bool
1398 if self.is_numeric
or self.is_alpha
then return true
1403 redef class Collection[E
]
1404 # Concatenate elements.
1407 var s
= new FlatBuffer
1408 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1412 # Concatenate and separate each elements with `sep`.
1414 # assert [1, 2, 3].join(":") == "1:2:3"
1415 # assert [1..3].join(":") == "1:2:3"
1416 fun join
(sep
: String): String
1418 if is_empty
then return ""
1420 var s
= new FlatBuffer # Result
1425 if e
!= null then s
.append
(e
.to_s
)
1427 # Concat other items
1432 if e
!= null then s
.append
(e
.to_s
)
1439 redef class Array[E
]
1440 # Fast implementation
1443 var s
= new FlatBuffer
1448 if e
!= null then s
.append
(e
.to_s
)
1455 redef class Map[K
,V
]
1456 # Concatenate couple of 'key value'.
1457 # key and value are separated by `couple_sep`.
1458 # each couple is separated each couple with `sep`.
1460 # var m = new ArrayMap[Int, String]
1463 # assert m.join("; ", "=") == "1=one; 10=ten"
1464 fun join
(sep
: String, couple_sep
: String): String
1466 if is_empty
then return ""
1468 var s
= new FlatBuffer # Result
1474 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1476 # Concat other items
1482 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1489 ###############################################################################
1491 ###############################################################################
1493 # Native strings are simple C char *
1497 fun [](index
: Int): Char is intern
1498 fun []=(index
: Int, item
: Char) is intern
1499 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1501 # Position of the first nul character.
1502 fun cstring_length
: Int
1505 while self[l
] != '\0' do l
+= 1
1508 fun atoi
: Int is intern
1509 fun atof
: Float is extern "atof"
1513 return to_s_with_length
(cstring_length
)
1516 fun to_s_with_length
(length
: Int): FlatString
1519 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1522 fun to_s_with_copy
: FlatString
1524 var length
= cstring_length
1525 var new_self
= calloc_string
(length
+ 1)
1526 copy_to
(new_self
, length
, 0, 0)
1527 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1532 # StringCapable objects can create native strings
1533 interface StringCapable
1534 protected fun calloc_string
(size
: Int): NativeString is intern
1538 var _args_cache
: nullable Sequence[String]
1540 redef fun args
: Sequence[String]
1542 if _args_cache
== null then init_args
1543 return _args_cache
.as(not null)
1546 # The name of the program as given by the OS
1547 fun program_name
: String
1549 return native_argv
(0).to_s
1552 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1553 private fun init_args
1555 var argc
= native_argc
1556 var args
= new Array[String].with_capacity
(0)
1559 args
[i-1
] = native_argv
(i
).to_s
1565 # First argument of the main C function.
1566 private fun native_argc
: Int is intern
1568 # Second argument of the main C function.
1569 private fun native_argv
(i
: Int): NativeString is intern