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
172 if from
> self.length
then return empty
173 if from
< 0 then from
= 0
174 return substring
(from
, length
- from
)
177 # Does self have a substring `str` starting from position `pos`?
179 # assert "abcd".has_substring("bc",1) == true
180 # assert "abcd".has_substring("bc",2) == false
181 fun has_substring
(str
: String, pos
: Int): Bool
183 var myiter
= self.chars
.iterator_from
(pos
)
184 var itsiter
= str
.iterator
185 while myiter
.is_ok
and itsiter
.is_ok
do
186 if myiter
.item
!= itsiter
.item
then return false
190 if itsiter
.is_ok
then return false
194 # Is this string prefixed by `prefix`?
196 # assert "abcd".has_prefix("ab") == true
197 # assert "abcbc".has_prefix("bc") == false
198 # assert "ab".has_prefix("abcd") == false
199 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
201 # Is this string suffixed by `suffix`?
203 # assert "abcd".has_suffix("abc") == false
204 # assert "abcd".has_suffix("bcd") == true
205 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
207 # If `self` contains only digits, return the corresponding integer
209 # assert "123".to_i == 123
210 # assert "-1".to_i == -1
214 return to_s
.to_cstring
.atoi
217 # If `self` contains a float, return the corresponding float
219 # assert "123".to_f == 123.0
220 # assert "-1".to_f == -1.0
221 # assert "-1.2e-3".to_f == -0.0012
225 return to_s
.to_cstring
.atof
228 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
229 fun to_hex
: Int do return a_to
(16)
231 # If `self` contains only digits and letters, return the corresponding integer in a given base
233 # assert "120".a_to(3) == 15
234 fun a_to
(base
: Int) : Int
261 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
263 # assert "123".is_numeric == true
264 # assert "1.2".is_numeric == true
265 # assert "1,2".is_numeric == true
266 # assert "1..2".is_numeric == false
269 var has_point_or_comma
= false
274 if (i
== '.' or i
== ',') and not has_point_or_comma
276 has_point_or_comma
= true
285 # A upper case version of `self`
287 # assert "Hello World!".to_upper == "HELLO WORLD!"
288 fun to_upper
: SELFTYPE is abstract
290 # A lower case version of `self`
292 # assert "Hello World!".to_lower == "hello world!"
293 fun to_lower
: SELFTYPE is abstract
295 # Removes the whitespaces at the beginning of self
298 var iter
= self.chars
.iterator
300 if iter
.item
.ascii
> 32 then break
303 if iter
.index
== length
then return self.empty
304 return self.substring_from
(iter
.index
)
307 # Removes the whitespaces at the end of self
310 var iter
= self.chars
.reverse_iterator
312 if iter
.item
.ascii
> 32 then break
315 if iter
.index
== length
then return self.empty
316 return self.substring
(0, iter
.index
+ 1)
319 # Trims trailing and preceding white spaces
320 # A whitespace is defined as any character which ascii value is less than or equal to 32
322 # assert " Hello World ! ".trim == "Hello World !"
323 # assert "\na\nb\tc\t".trim == "a\nb\tc"
324 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
326 # Mangle a string to be a unique string only made of alphanumeric characters
327 fun to_cmangle
: String
329 var res
= new FlatBuffer
330 var underscore
= false
331 for c
in self.chars
do
332 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
338 res
.append
('_'.ascii
.to_s
)
341 if c
>= '0' and c
<= '9' then
344 else if c
== '_' then
349 res
.append
(c
.ascii
.to_s
)
357 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
359 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
360 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
361 fun escape_to_c
: String
363 var b
= new FlatBuffer
364 for c
in self.chars
do
367 else if c
== '\0' then
369 else if c
== '"' then
371 else if c == '\'' then
373 else if c == '\\
' then
375 else if c.ascii < 32 then
376 b.append("\\{c.ascii.to_base(8, false)}")
384 # Escape additionnal characters
385 # The result might no be legal in C but be used in other languages
387 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
388 fun escape_more_to_c(chars: String): String
390 var b = new FlatBuffer
391 for c in escape_to_c do
392 if chars.chars.has(c) then
400 # Escape to c plus braces
402 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
403 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
405 # Return a string where Nit escape sequences are transformed.
409 # assert s.length == 2
410 # var u = s.unescape_nit
411 # assert u.length == 1
412 # assert u[0].ascii == 10 # (the ASCII value of the "new line" character)
413 fun unescape_nit
: String
415 var res
= new FlatBuffer.with_capacity
(self.length
)
416 var was_slash
= false
418 if not was_slash
then
429 else if c
== 'r' then
431 else if c
== 't' then
433 else if c
== '0' then
444 if o
== null then return false
445 if not o
isa Text then return false
446 if self.is_same_instance
(o
) then return true
447 if self.length
!= o
.length
then return false
448 return self.chars
== o
.chars
453 return self.chars
< o
.chars
458 # All kinds of array-based text representations.
459 abstract class FlatText
462 private var items
: NativeString
464 redef var length
: Int
478 # Abstract class for the SequenceRead compatible
479 # views on String and Buffer objects
480 abstract class StringCharView
481 super SequenceRead[Char]
486 redef type OTHER: StringCharView
488 private var target
: SELFTYPE
490 private init(tgt
: SELFTYPE)
495 redef fun is_empty
do return target
.is_empty
497 redef fun length
do return target
.length
499 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
501 # Gets a new Iterator starting at position `pos`
504 # var iter = "abcd".iterator_from(2)
505 # while iter.is_ok do
511 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
513 # Gets an iterator starting at the end and going backwards
516 # var reviter = "now step live...".reverse_iterator
517 # while reviter.is_ok do
518 # printn reviter.item
522 # Outputs : ...evil pets won
523 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
525 # Gets an iterator on the chars of self starting from `pos`
528 # var iter = "abcd".reverse_iterator_from(1)
529 # while iter.is_ok do
535 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
537 redef fun has
(c
: Char): Bool
540 if i
== c
then return true
547 if other
== null then return false
548 if not other
isa StringCharView then return false
549 var other_chars
= other
.iterator
551 if i
!= other_chars
.item
then return false
559 var self_chars
= self.iterator
560 var other_chars
= other
.iterator
562 while self_chars
.is_ok
and other_chars
.is_ok
do
563 if self_chars
.item
< other_chars
.item
then return true
564 if self_chars
.item
> other_chars
.item
then return false
569 if self_chars
.is_ok
then
577 # View on Buffer objects, extends Sequence
578 # for mutation operations
579 abstract class BufferCharView
583 redef type SELFTYPE: Buffer
587 abstract class String
590 redef type SELFTYPE: String
592 redef fun to_s
do return self
596 # Immutable strings of characters.
601 redef type SELFTYPE: FlatString
602 redef type SELFVIEW: FlatStringCharView
604 # Index in _items of the start of the string
605 private var index_from
: Int
607 # Indes in _items of the last item of the string
608 private var index_to
: Int
610 redef var chars
: SELFVIEW = new FlatStringCharView(self)
612 ################################################
613 # AbstractString specific methods #
614 ################################################
616 redef fun [](index
) do
618 # Check that the index (+ index_from) is not larger than indexTo
619 # In other terms, if the index is valid
620 assert (index
+ index_from
) <= index_to
621 return items
[index
+ index_from
]
624 redef fun substring
(from
, count
)
630 if count
< 0 then count
= 0
634 var realFrom
= index_from
+ from
636 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
638 if count
== 0 then return empty
640 var to
= realFrom
+ count
- 1
642 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
645 redef fun empty
do return "".as(FlatString)
649 var outstr
= calloc_string
(self.length
+ 1)
652 var myitems
= self.items
653 var index_from
= self.index_from
654 var max
= self.index_to
656 while index_from
<= max
do
657 outstr
[out_index
] = myitems
[index_from
].to_upper
662 outstr
[self.length
] = '\0'
664 return outstr
.to_s_with_length
(self.length
)
669 var outstr
= calloc_string
(self.length
+ 1)
672 var myitems
= self.items
673 var index_from
= self.index_from
674 var max
= self.index_to
676 while index_from
<= max
do
677 outstr
[out_index
] = myitems
[index_from
].to_lower
682 outstr
[self.length
] = '\0'
684 return outstr
.to_s_with_length
(self.length
)
689 var i
= self.index_from
690 var imax
= self.index_to
697 ##################################################
698 # String Specific Methods #
699 ##################################################
701 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
709 # Return a null terminated char *
710 fun to_cstring
: NativeString
712 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
713 var newItems
= calloc_string
(length
+ 1)
714 self.items
.copy_to
(newItems
, length
, index_from
, 0)
715 newItems
[length
] = '\0'
723 if not other
isa FlatString then return super
725 if self.object_id
== other
.object_id
then return true
727 var my_length
= length
729 if other
.length
!= my_length
then return false
731 var my_index
= index_from
732 var its_index
= other
.index_from
734 var last_iteration
= my_index
+ my_length
736 var itsitems
= other
.items
737 var myitems
= self.items
739 while my_index
< last_iteration
do
740 if myitems
[my_index
] != itsitems
[its_index
] then return false
748 # The comparison between two strings is done on a lexicographical basis
750 # assert ("aa" < "b") == true
753 if not other
isa FlatString then return super
755 if self.object_id
== other
.object_id
then return false
757 var my_curr_char
: Char
758 var its_curr_char
: Char
760 var curr_id_self
= self.index_from
761 var curr_id_other
= other
.index_from
763 var my_items
= self.items
764 var its_items
= other
.items
766 var my_length
= self.length
767 var its_length
= other
.length
769 var max_iterations
= curr_id_self
+ my_length
771 while curr_id_self
< max_iterations
do
772 my_curr_char
= my_items
[curr_id_self
]
773 its_curr_char
= its_items
[curr_id_other
]
775 if my_curr_char
!= its_curr_char
then
776 if my_curr_char
< its_curr_char
then return true
784 return my_length
< its_length
787 # The concatenation of `self` with `s`
789 # assert "hello " + "world!" == "hello world!"
792 var my_length
= self.length
793 var its_length
= s
.length
795 var total_length
= my_length
+ its_length
797 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
799 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
800 if s
isa FlatString then
801 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
802 else if s
isa FlatBuffer then
803 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
805 var curr_pos
= my_length
807 target_string
[curr_pos
] = i
812 target_string
[total_length
] = '\0'
814 return target_string
.to_s_with_length
(total_length
)
817 # assert "abc"*3 == "abcabcabc"
818 # assert "abc"*1 == "abc"
819 # assert "abc"*0 == ""
824 var my_length
= self.length
826 var final_length
= my_length
* i
828 var my_items
= self.items
830 var target_string
= calloc_string
((final_length
) + 1)
832 target_string
[final_length
] = '\0'
836 for iteration
in [1 .. i
] do
837 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
838 current_last
+= my_length
841 return target_string
.to_s_with_length
(final_length
)
846 # djb2 hash algorythm
851 var strStart
= index_from
855 while i
>= strStart
do
856 h
= (h
* 32) + h
+ self.items
[i
].ascii
864 private class FlatStringReverseIterator
865 super IndexedIterator[Char]
867 var target
: FlatString
869 var target_items
: NativeString
873 init with_pos
(tgt
: FlatString, pos
: Int)
876 target_items
= tgt
.items
877 curr_pos
= pos
+ tgt
.index_from
880 redef fun is_ok
do return curr_pos
>= 0
882 redef fun item
do return target_items
[curr_pos
]
884 redef fun next
do curr_pos
-= 1
886 redef fun index
do return curr_pos
- target
.index_from
890 private class FlatStringIterator
891 super IndexedIterator[Char]
893 var target
: FlatString
895 var target_items
: NativeString
899 init with_pos
(tgt
: FlatString, pos
: Int)
902 target_items
= tgt
.items
903 curr_pos
= pos
+ target
.index_from
906 redef fun is_ok
do return curr_pos
<= target
.index_to
908 redef fun item
do return target_items
[curr_pos
]
910 redef fun next
do curr_pos
+= 1
912 redef fun index
do return curr_pos
- target
.index_from
916 private class FlatStringCharView
919 redef type SELFTYPE: FlatString
923 # Check that the index (+ index_from) is not larger than indexTo
924 # In other terms, if the index is valid
926 assert (index
+ target
.index_from
) <= target
.index_to
927 return target
.items
[index
+ target
.index_from
]
930 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
932 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
936 abstract class Buffer
939 redef type SELFVIEW: BufferCharView
940 redef type SELFTYPE: Buffer
942 # Modifies the char contained at pos `index`
944 # DEPRECATED : Use self.chars.[]= instead
945 fun []=(index
: Int, item
: Char) is abstract
947 # Adds a char `c` at the end of self
949 # DEPRECATED : Use self.chars.add instead
950 fun add
(c
: Char) is abstract
953 fun clear
is abstract
955 # Enlarges the subsequent array containing the chars of self
956 fun enlarge
(cap
: Int) is abstract
958 # Adds the content of text `s` at the end of self
959 fun append
(s
: Text) is abstract
963 # Mutable strings of characters.
968 redef type SELFVIEW: FlatBufferCharView
969 redef type SELFTYPE: FlatBuffer
971 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
975 redef fun []=(index
, item
)
977 if index
== length
then
981 assert index
>= 0 and index
< length
987 if capacity
<= length
then enlarge
(length
+ 5)
992 redef fun clear
do length
= 0
994 redef fun empty
do return new FlatBuffer
996 redef fun enlarge
(cap
)
999 if cap
<= c
then return
1000 while c
<= cap
do c
= c
* 2 + 2
1001 var a
= calloc_string
(c
+1)
1002 items
.copy_to
(a
, length
, 0, 0)
1005 items
.copy_to
(a
, length
, 0, 0)
1008 redef fun to_s
: String
1011 var a
= calloc_string
(l
+1)
1012 items
.copy_to
(a
, l
, 0, 0)
1014 # Ensure the afterlast byte is '\0' to nul-terminated char *
1017 return a
.to_s_with_length
(length
)
1020 # Create a new empty string.
1028 capacity
= s
.length
+ 1
1030 items
= calloc_string
(capacity
)
1031 if s
isa FlatString then
1032 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1033 else if s
isa FlatBuffer then
1034 s
.items
.copy_to
(items
, length
, 0, 0)
1044 # Create a new empty string with a given capacity.
1045 init with_capacity
(cap
: Int)
1048 # _items = new NativeString.calloc(cap)
1049 items
= calloc_string
(cap
+1)
1057 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1058 if s
isa FlatString then
1059 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1060 else if s
isa FlatBuffer then
1061 s
.items
.copy_to
(items
, sl
, 0, length
)
1063 var curr_pos
= self.length
1072 # Copies the content of self in `dest`
1073 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1075 var self_chars
= self.chars
1076 var dest_chars
= dest
.chars
1077 for i
in [0..len-1
] do
1078 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1082 redef fun substring
(from
, count
)
1086 if from
< 0 then from
= 0
1087 if count
> length
then count
= length
1088 if from
< count
then
1089 var r
= new FlatBuffer.with_capacity
(count
- from
)
1090 while from
< count
do
1091 r
.chars
.push
(items
[from
])
1096 return new FlatBuffer
1102 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1103 new_buf
.append
(self)
1104 new_buf
.append
(other
)
1108 redef fun *(repeats
)
1110 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1111 for i
in [0..repeats
[ do
1112 new_buf
.append
(self)
1118 private class FlatBufferReverseIterator
1119 super IndexedIterator[Char]
1121 var target
: FlatBuffer
1123 var target_items
: NativeString
1127 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1130 target_items
= tgt
.items
1134 redef fun index
do return curr_pos
1136 redef fun is_ok
do return curr_pos
>= 0
1138 redef fun item
do return target_items
[curr_pos
]
1140 redef fun next
do curr_pos
-= 1
1144 private class FlatBufferCharView
1145 super BufferCharView
1148 redef type SELFTYPE: FlatBuffer
1150 redef fun [](index
) do return target
.items
[index
]
1152 redef fun []=(index
, item
)
1154 assert index
>= 0 and index
<= length
1155 if index
== length
then
1159 target
.items
[index
] = item
1172 fun enlarge
(cap
: Int)
1179 var my_items
= target
.items
1180 var s_length
= s
.length
1181 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1184 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1186 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1190 private class FlatBufferIterator
1191 super IndexedIterator[Char]
1193 var target
: FlatBuffer
1195 var target_items
: NativeString
1199 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1202 target_items
= tgt
.items
1206 redef fun index
do return curr_pos
1208 redef fun is_ok
do return curr_pos
< target
.length
1210 redef fun item
do return target_items
[curr_pos
]
1212 redef fun next
do curr_pos
+= 1
1216 ###############################################################################
1218 ###############################################################################
1221 # User readable representation of `self`.
1222 fun to_s
: String do return inspect
1224 # The class name of the object in NativeString format.
1225 private fun native_class_name
: NativeString is intern
1227 # The class name of the object.
1229 # assert 5.class_name == "Int"
1230 fun class_name
: String do return native_class_name
.to_s
1232 # Developer readable representation of `self`.
1233 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1236 return "<{inspect_head}>"
1239 # Return "CLASSNAME:#OBJECTID".
1240 # This function is mainly used with the redefinition of the inspect method
1241 protected fun inspect_head
: String
1243 return "{class_name}:#{object_id.to_hex}"
1246 protected fun args
: Sequence[String]
1253 # assert true.to_s == "true"
1254 # assert false.to_s == "false"
1266 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1267 # assume < to_c max const of char
1268 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1275 else if self == 0 then
1282 var pos
= digit_count
(base
) - 1
1283 while pos
>= 0 and n
> 0 do
1284 s
.chars
[pos
] = (n
% base
).to_c
1290 # C function to convert an nit Int to a NativeString (char*)
1291 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1293 # return displayable int in base 10 and signed
1295 # assert 1.to_s == "1"
1296 # assert (-123).to_s == "-123"
1298 var len
= digit_count
(10)
1299 return native_int_to_s
(len
).to_s_with_length
(len
)
1302 # return displayable int in hexadecimal (unsigned (not now))
1303 fun to_hex
: String do return to_base
(16,false)
1305 # return displayable int in base base and signed
1306 fun to_base
(base
: Int, signed
: Bool): String
1308 var l
= digit_count
(base
)
1309 var s
= new FlatBuffer.from
(" " * l
)
1310 fill_buffer
(s
, base
, signed
)
1316 # Pretty print self, print needoed decimals up to a max of 3.
1318 var str
= to_precision
( 3 )
1319 if is_inf
!= 0 or is_nan
then return str
1320 var len
= str
.length
1321 for i
in [0..len-1
] do
1323 var c
= str
.chars
[j
]
1326 else if c
== '.' then
1327 return str
.substring
( 0, j
+2 )
1329 return str
.substring
( 0, j
+1 )
1335 # `self` representation with `nb` digits after the '.'.
1336 fun to_precision
(nb
: Int): String
1338 if is_nan
then return "nan"
1340 var isinf
= self.is_inf
1343 else if isinf
== -1 then
1347 if nb
== 0 then return self.to_i
.to_s
1349 for i
in [0..nb
[ do f
= f
* 10.0
1356 if i
== 0 then return "0.0"
1360 var p1
= s
.substring
(0, s
.length-nb
)
1361 var p2
= s
.substring
(s
.length-nb
, nb
)
1362 return p1
+ "." + p2
1364 return "0." + ("0"*(nb-sl
)) + s
1368 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1372 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1373 str = malloc(size + 1);
1374 sprintf(str, "%.*f", (int)nb, recv );
1376 return NativeString_to_s( str );
1381 # assert 'x'.to_s == "x"
1384 var s
= new FlatBuffer.with_capacity
(1)
1389 # Returns true if the char is a numerical digit
1390 fun is_numeric
: Bool
1392 if self >= '0' and self <= '9'
1399 # Returns true if the char is an alpha digit
1402 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1406 # Returns true if the char is an alpha or a numeric digit
1407 fun is_alphanumeric
: Bool
1409 if self.is_numeric
or self.is_alpha
then return true
1414 redef class Collection[E
]
1415 # Concatenate elements.
1418 var s
= new FlatBuffer
1419 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1423 # Concatenate and separate each elements with `sep`.
1425 # assert [1, 2, 3].join(":") == "1:2:3"
1426 # assert [1..3].join(":") == "1:2:3"
1427 fun join
(sep
: String): String
1429 if is_empty
then return ""
1431 var s
= new FlatBuffer # Result
1436 if e
!= null then s
.append
(e
.to_s
)
1438 # Concat other items
1443 if e
!= null then s
.append
(e
.to_s
)
1450 redef class Array[E
]
1451 # Fast implementation
1454 var s
= new FlatBuffer
1459 if e
!= null then s
.append
(e
.to_s
)
1466 redef class Map[K
,V
]
1467 # Concatenate couple of 'key value'.
1468 # key and value are separated by `couple_sep`.
1469 # each couple is separated each couple with `sep`.
1471 # var m = new ArrayMap[Int, String]
1474 # assert m.join("; ", "=") == "1=one; 10=ten"
1475 fun join
(sep
: String, couple_sep
: String): String
1477 if is_empty
then return ""
1479 var s
= new FlatBuffer # Result
1485 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1487 # Concat other items
1493 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1500 ###############################################################################
1502 ###############################################################################
1504 # Native strings are simple C char *
1508 fun [](index
: Int): Char is intern
1509 fun []=(index
: Int, item
: Char) is intern
1510 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1512 # Position of the first nul character.
1513 fun cstring_length
: Int
1516 while self[l
] != '\0' do l
+= 1
1519 fun atoi
: Int is intern
1520 fun atof
: Float is extern "atof"
1524 return to_s_with_length
(cstring_length
)
1527 fun to_s_with_length
(length
: Int): FlatString
1530 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1533 fun to_s_with_copy
: FlatString
1535 var length
= cstring_length
1536 var new_self
= calloc_string
(length
+ 1)
1537 copy_to
(new_self
, length
, 0, 0)
1538 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1543 # StringCapable objects can create native strings
1544 interface StringCapable
1545 protected fun calloc_string
(size
: Int): NativeString is intern
1549 var _args_cache
: nullable Sequence[String]
1551 redef fun args
: Sequence[String]
1553 if _args_cache
== null then init_args
1554 return _args_cache
.as(not null)
1557 # The name of the program as given by the OS
1558 fun program_name
: String
1560 return native_argv
(0).to_s
1563 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1564 private fun init_args
1566 var argc
= native_argc
1567 var args
= new Array[String].with_capacity
(0)
1570 args
[i-1
] = native_argv
(i
).to_s
1576 # First argument of the main C function.
1577 private fun native_argc
: Int is intern
1579 # Second argument of the main C function.
1580 private fun native_argv
(i
: Int): NativeString is intern