e47399b9d4830748e78d8e61d6ba48786de16f8c
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
456 # Flat representation of self
457 fun flatten
: FlatText is abstract
461 # All kinds of array-based text representations.
462 abstract class FlatText
465 private var items
: NativeString
467 redef var length
: Int
480 redef fun flatten
do return self
483 # Abstract class for the SequenceRead compatible
484 # views on String and Buffer objects
485 abstract class StringCharView
486 super SequenceRead[Char]
491 redef type OTHER: StringCharView
493 private var target
: SELFTYPE
495 private init(tgt
: SELFTYPE)
500 redef fun is_empty
do return target
.is_empty
502 redef fun length
do return target
.length
504 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
506 # Gets a new Iterator starting at position `pos`
509 # var iter = "abcd".iterator_from(2)
510 # while iter.is_ok do
516 fun iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
518 # Gets an iterator starting at the end and going backwards
521 # var reviter = "now step live...".reverse_iterator
522 # while reviter.is_ok do
523 # printn reviter.item
527 # Outputs : ...evil pets won
528 fun reverse_iterator
: IndexedIterator[Char] do return self.reverse_iterator_from
(self.length
- 1)
530 # Gets an iterator on the chars of self starting from `pos`
533 # var iter = "abcd".reverse_iterator_from(1)
534 # while iter.is_ok do
540 fun reverse_iterator_from
(pos
: Int): IndexedIterator[Char] is abstract
542 redef fun has
(c
: Char): Bool
545 if i
== c
then return true
552 if other
== null then return false
553 if not other
isa StringCharView then return false
554 var other_chars
= other
.iterator
556 if i
!= other_chars
.item
then return false
564 var self_chars
= self.iterator
565 var other_chars
= other
.iterator
567 while self_chars
.is_ok
and other_chars
.is_ok
do
568 if self_chars
.item
< other_chars
.item
then return true
569 if self_chars
.item
> other_chars
.item
then return false
574 if self_chars
.is_ok
then
582 # View on Buffer objects, extends Sequence
583 # for mutation operations
584 abstract class BufferCharView
588 redef type SELFTYPE: Buffer
592 abstract class String
595 redef type SELFTYPE: String
597 redef fun to_s
do return self
601 # Immutable strings of characters.
606 redef type SELFTYPE: FlatString
607 redef type SELFVIEW: FlatStringCharView
609 # Index in _items of the start of the string
610 private var index_from
: Int
612 # Indes in _items of the last item of the string
613 private var index_to
: Int
615 redef var chars
: SELFVIEW = new FlatStringCharView(self)
617 ################################################
618 # AbstractString specific methods #
619 ################################################
621 redef fun [](index
) do
623 # Check that the index (+ index_from) is not larger than indexTo
624 # In other terms, if the index is valid
625 assert (index
+ index_from
) <= index_to
626 return items
[index
+ index_from
]
629 redef fun substring
(from
, count
)
635 if count
< 0 then count
= 0
639 var realFrom
= index_from
+ from
641 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
643 if count
== 0 then return empty
645 var to
= realFrom
+ count
- 1
647 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
650 redef fun empty
do return "".as(FlatString)
654 var outstr
= calloc_string
(self.length
+ 1)
657 var myitems
= self.items
658 var index_from
= self.index_from
659 var max
= self.index_to
661 while index_from
<= max
do
662 outstr
[out_index
] = myitems
[index_from
].to_upper
667 outstr
[self.length
] = '\0'
669 return outstr
.to_s_with_length
(self.length
)
674 var outstr
= calloc_string
(self.length
+ 1)
677 var myitems
= self.items
678 var index_from
= self.index_from
679 var max
= self.index_to
681 while index_from
<= max
do
682 outstr
[out_index
] = myitems
[index_from
].to_lower
687 outstr
[self.length
] = '\0'
689 return outstr
.to_s_with_length
(self.length
)
694 var i
= self.index_from
695 var imax
= self.index_to
702 ##################################################
703 # String Specific Methods #
704 ##################################################
706 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
714 # Return a null terminated char *
715 fun to_cstring
: NativeString
717 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
718 var newItems
= calloc_string
(length
+ 1)
719 self.items
.copy_to
(newItems
, length
, index_from
, 0)
720 newItems
[length
] = '\0'
728 if not other
isa FlatString then return super
730 if self.object_id
== other
.object_id
then return true
732 var my_length
= length
734 if other
.length
!= my_length
then return false
736 var my_index
= index_from
737 var its_index
= other
.index_from
739 var last_iteration
= my_index
+ my_length
741 var itsitems
= other
.items
742 var myitems
= self.items
744 while my_index
< last_iteration
do
745 if myitems
[my_index
] != itsitems
[its_index
] then return false
753 # The comparison between two strings is done on a lexicographical basis
755 # assert ("aa" < "b") == true
758 if not other
isa FlatString then return super
760 if self.object_id
== other
.object_id
then return false
762 var my_curr_char
: Char
763 var its_curr_char
: Char
765 var curr_id_self
= self.index_from
766 var curr_id_other
= other
.index_from
768 var my_items
= self.items
769 var its_items
= other
.items
771 var my_length
= self.length
772 var its_length
= other
.length
774 var max_iterations
= curr_id_self
+ my_length
776 while curr_id_self
< max_iterations
do
777 my_curr_char
= my_items
[curr_id_self
]
778 its_curr_char
= its_items
[curr_id_other
]
780 if my_curr_char
!= its_curr_char
then
781 if my_curr_char
< its_curr_char
then return true
789 return my_length
< its_length
792 # The concatenation of `self` with `s`
794 # assert "hello " + "world!" == "hello world!"
797 var my_length
= self.length
798 var its_length
= s
.length
800 var total_length
= my_length
+ its_length
802 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
804 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
805 if s
isa FlatString then
806 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
807 else if s
isa FlatBuffer then
808 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
810 var curr_pos
= my_length
812 target_string
[curr_pos
] = i
817 target_string
[total_length
] = '\0'
819 return target_string
.to_s_with_length
(total_length
)
822 # assert "abc"*3 == "abcabcabc"
823 # assert "abc"*1 == "abc"
824 # assert "abc"*0 == ""
829 var my_length
= self.length
831 var final_length
= my_length
* i
833 var my_items
= self.items
835 var target_string
= calloc_string
((final_length
) + 1)
837 target_string
[final_length
] = '\0'
841 for iteration
in [1 .. i
] do
842 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
843 current_last
+= my_length
846 return target_string
.to_s_with_length
(final_length
)
851 # djb2 hash algorythm
856 var strStart
= index_from
860 while i
>= strStart
do
861 h
= (h
* 32) + h
+ self.items
[i
].ascii
869 private class FlatStringReverseIterator
870 super IndexedIterator[Char]
872 var target
: FlatString
874 var target_items
: NativeString
878 init with_pos
(tgt
: FlatString, pos
: Int)
881 target_items
= tgt
.items
882 curr_pos
= pos
+ tgt
.index_from
885 redef fun is_ok
do return curr_pos
>= 0
887 redef fun item
do return target_items
[curr_pos
]
889 redef fun next
do curr_pos
-= 1
891 redef fun index
do return curr_pos
- target
.index_from
895 private class FlatStringIterator
896 super IndexedIterator[Char]
898 var target
: FlatString
900 var target_items
: NativeString
904 init with_pos
(tgt
: FlatString, pos
: Int)
907 target_items
= tgt
.items
908 curr_pos
= pos
+ target
.index_from
911 redef fun is_ok
do return curr_pos
<= target
.index_to
913 redef fun item
do return target_items
[curr_pos
]
915 redef fun next
do curr_pos
+= 1
917 redef fun index
do return curr_pos
- target
.index_from
921 private class FlatStringCharView
924 redef type SELFTYPE: FlatString
928 # Check that the index (+ index_from) is not larger than indexTo
929 # In other terms, if the index is valid
931 assert (index
+ target
.index_from
) <= target
.index_to
932 return target
.items
[index
+ target
.index_from
]
935 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
937 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
941 abstract class Buffer
944 redef type SELFVIEW: BufferCharView
945 redef type SELFTYPE: Buffer
947 # Modifies the char contained at pos `index`
949 # DEPRECATED : Use self.chars.[]= instead
950 fun []=(index
: Int, item
: Char) is abstract
952 # Adds a char `c` at the end of self
954 # DEPRECATED : Use self.chars.add instead
955 fun add
(c
: Char) is abstract
958 fun clear
is abstract
960 # Enlarges the subsequent array containing the chars of self
961 fun enlarge
(cap
: Int) is abstract
963 # Adds the content of text `s` at the end of self
964 fun append
(s
: Text) is abstract
968 # Mutable strings of characters.
973 redef type SELFVIEW: FlatBufferCharView
974 redef type SELFTYPE: FlatBuffer
976 redef var chars
: SELFVIEW = new FlatBufferCharView(self)
980 redef fun []=(index
, item
)
982 if index
== length
then
986 assert index
>= 0 and index
< length
992 if capacity
<= length
then enlarge
(length
+ 5)
997 redef fun clear
do length
= 0
999 redef fun empty
do return new FlatBuffer
1001 redef fun enlarge
(cap
)
1004 if cap
<= c
then return
1005 while c
<= cap
do c
= c
* 2 + 2
1006 var a
= calloc_string
(c
+1)
1007 items
.copy_to
(a
, length
, 0, 0)
1010 items
.copy_to
(a
, length
, 0, 0)
1013 redef fun to_s
: String
1016 var a
= calloc_string
(l
+1)
1017 items
.copy_to
(a
, l
, 0, 0)
1019 # Ensure the afterlast byte is '\0' to nul-terminated char *
1022 return a
.to_s_with_length
(length
)
1025 # Create a new empty string.
1033 capacity
= s
.length
+ 1
1035 items
= calloc_string
(capacity
)
1036 if s
isa FlatString then
1037 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1038 else if s
isa FlatBuffer then
1039 s
.items
.copy_to
(items
, length
, 0, 0)
1049 # Create a new empty string with a given capacity.
1050 init with_capacity
(cap
: Int)
1053 # _items = new NativeString.calloc(cap)
1054 items
= calloc_string
(cap
+1)
1062 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1063 if s
isa FlatString then
1064 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1065 else if s
isa FlatBuffer then
1066 s
.items
.copy_to
(items
, sl
, 0, length
)
1068 var curr_pos
= self.length
1077 # Copies the content of self in `dest`
1078 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1080 var self_chars
= self.chars
1081 var dest_chars
= dest
.chars
1082 for i
in [0..len-1
] do
1083 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1087 redef fun substring
(from
, count
)
1091 if from
< 0 then from
= 0
1092 if count
> length
then count
= length
1093 if from
< count
then
1094 var r
= new FlatBuffer.with_capacity
(count
- from
)
1095 while from
< count
do
1096 r
.chars
.push
(items
[from
])
1101 return new FlatBuffer
1107 var new_buf
= new FlatBuffer.with_capacity
(self.length
+ other
.length
)
1108 new_buf
.append
(self)
1109 new_buf
.append
(other
)
1113 redef fun *(repeats
)
1115 var new_buf
= new FlatBuffer.with_capacity
(self.length
* repeats
)
1116 for i
in [0..repeats
[ do
1117 new_buf
.append
(self)
1123 private class FlatBufferReverseIterator
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
>= 0
1143 redef fun item
do return target_items
[curr_pos
]
1145 redef fun next
do curr_pos
-= 1
1149 private class FlatBufferCharView
1150 super BufferCharView
1153 redef type SELFTYPE: FlatBuffer
1155 redef fun [](index
) do return target
.items
[index
]
1157 redef fun []=(index
, item
)
1159 assert index
>= 0 and index
<= length
1160 if index
== length
then
1164 target
.items
[index
] = item
1177 fun enlarge
(cap
: Int)
1184 var my_items
= target
.items
1185 var s_length
= s
.length
1186 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1189 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1191 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1195 private class FlatBufferIterator
1196 super IndexedIterator[Char]
1198 var target
: FlatBuffer
1200 var target_items
: NativeString
1204 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1207 target_items
= tgt
.items
1211 redef fun index
do return curr_pos
1213 redef fun is_ok
do return curr_pos
< target
.length
1215 redef fun item
do return target_items
[curr_pos
]
1217 redef fun next
do curr_pos
+= 1
1221 ###############################################################################
1223 ###############################################################################
1226 # User readable representation of `self`.
1227 fun to_s
: String do return inspect
1229 # The class name of the object in NativeString format.
1230 private fun native_class_name
: NativeString is intern
1232 # The class name of the object.
1234 # assert 5.class_name == "Int"
1235 fun class_name
: String do return native_class_name
.to_s
1237 # Developer readable representation of `self`.
1238 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1241 return "<{inspect_head}>"
1244 # Return "CLASSNAME:#OBJECTID".
1245 # This function is mainly used with the redefinition of the inspect method
1246 protected fun inspect_head
: String
1248 return "{class_name}:#{object_id.to_hex}"
1251 protected fun args
: Sequence[String]
1258 # assert true.to_s == "true"
1259 # assert false.to_s == "false"
1271 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1272 # assume < to_c max const of char
1273 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1280 else if self == 0 then
1287 var pos
= digit_count
(base
) - 1
1288 while pos
>= 0 and n
> 0 do
1289 s
.chars
[pos
] = (n
% base
).to_c
1295 # C function to convert an nit Int to a NativeString (char*)
1296 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
1298 # return displayable int in base 10 and signed
1300 # assert 1.to_s == "1"
1301 # assert (-123).to_s == "-123"
1303 var len
= digit_count
(10)
1304 return native_int_to_s
(len
).to_s_with_length
(len
)
1307 # return displayable int in hexadecimal (unsigned (not now))
1308 fun to_hex
: String do return to_base
(16,false)
1310 # return displayable int in base base and signed
1311 fun to_base
(base
: Int, signed
: Bool): String
1313 var l
= digit_count
(base
)
1314 var s
= new FlatBuffer.from
(" " * l
)
1315 fill_buffer
(s
, base
, signed
)
1321 # Pretty print self, print needoed decimals up to a max of 3.
1323 var str
= to_precision
( 3 )
1324 if is_inf
!= 0 or is_nan
then return str
1325 var len
= str
.length
1326 for i
in [0..len-1
] do
1328 var c
= str
.chars
[j
]
1331 else if c
== '.' then
1332 return str
.substring
( 0, j
+2 )
1334 return str
.substring
( 0, j
+1 )
1340 # `self` representation with `nb` digits after the '.'.
1341 fun to_precision
(nb
: Int): String
1343 if is_nan
then return "nan"
1345 var isinf
= self.is_inf
1348 else if isinf
== -1 then
1352 if nb
== 0 then return self.to_i
.to_s
1354 for i
in [0..nb
[ do f
= f
* 10.0
1361 if i
== 0 then return "0.0"
1365 var p1
= s
.substring
(0, s
.length-nb
)
1366 var p2
= s
.substring
(s
.length-nb
, nb
)
1367 return p1
+ "." + p2
1369 return "0." + ("0"*(nb-sl
)) + s
1373 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1377 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1378 str = malloc(size + 1);
1379 sprintf(str, "%.*f", (int)nb, recv );
1381 return NativeString_to_s( str );
1386 # assert 'x'.to_s == "x"
1389 var s
= new FlatBuffer.with_capacity
(1)
1394 # Returns true if the char is a numerical digit
1395 fun is_numeric
: Bool
1397 if self >= '0' and self <= '9'
1404 # Returns true if the char is an alpha digit
1407 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
1411 # Returns true if the char is an alpha or a numeric digit
1412 fun is_alphanumeric
: Bool
1414 if self.is_numeric
or self.is_alpha
then return true
1419 redef class Collection[E
]
1420 # Concatenate elements.
1423 var s
= new FlatBuffer
1424 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1428 # Concatenate and separate each elements with `sep`.
1430 # assert [1, 2, 3].join(":") == "1:2:3"
1431 # assert [1..3].join(":") == "1:2:3"
1432 fun join
(sep
: String): String
1434 if is_empty
then return ""
1436 var s
= new FlatBuffer # Result
1441 if e
!= null then s
.append
(e
.to_s
)
1443 # Concat other items
1448 if e
!= null then s
.append
(e
.to_s
)
1455 redef class Array[E
]
1456 # Fast implementation
1459 var s
= new FlatBuffer
1464 if e
!= null then s
.append
(e
.to_s
)
1471 redef class Map[K
,V
]
1472 # Concatenate couple of 'key value'.
1473 # key and value are separated by `couple_sep`.
1474 # each couple is separated each couple with `sep`.
1476 # var m = new ArrayMap[Int, String]
1479 # assert m.join("; ", "=") == "1=one; 10=ten"
1480 fun join
(sep
: String, couple_sep
: String): String
1482 if is_empty
then return ""
1484 var s
= new FlatBuffer # Result
1490 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1492 # Concat other items
1498 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1505 ###############################################################################
1507 ###############################################################################
1509 # Native strings are simple C char *
1513 fun [](index
: Int): Char is intern
1514 fun []=(index
: Int, item
: Char) is intern
1515 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
1517 # Position of the first nul character.
1518 fun cstring_length
: Int
1521 while self[l
] != '\0' do l
+= 1
1524 fun atoi
: Int is intern
1525 fun atof
: Float is extern "atof"
1529 return to_s_with_length
(cstring_length
)
1532 fun to_s_with_length
(length
: Int): FlatString
1535 return new FlatString.with_infos
(self, length
, 0, length
- 1)
1538 fun to_s_with_copy
: FlatString
1540 var length
= cstring_length
1541 var new_self
= calloc_string
(length
+ 1)
1542 copy_to
(new_self
, length
, 0, 0)
1543 return new FlatString.with_infos
(new_self
, length
, 0, length
- 1)
1548 # StringCapable objects can create native strings
1549 interface StringCapable
1550 protected fun calloc_string
(size
: Int): NativeString is intern
1554 var _args_cache
: nullable Sequence[String]
1556 redef fun args
: Sequence[String]
1558 if _args_cache
== null then init_args
1559 return _args_cache
.as(not null)
1562 # The name of the program as given by the OS
1563 fun program_name
: String
1565 return native_argv
(0).to_s
1568 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1569 private fun init_args
1571 var argc
= native_argc
1572 var args
= new Array[String].with_capacity
(0)
1575 args
[i-1
] = native_argv
(i
).to_s
1581 # First argument of the main C function.
1582 private fun native_argc
: Int is intern
1584 # Second argument of the main C function.
1585 private fun native_argv
(i
: Int): NativeString is intern