38bd492dafb5d5fd478cb2464397b5e16e2f0e4a
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
19 intrude import collection
::array
26 ###############################################################################
28 ###############################################################################
30 # High-level abstraction for all text representations
35 redef type OTHER: Text
37 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
40 # Gets a view on the chars of the Text object
42 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
43 fun chars
: SequenceRead[Char] is abstract
45 # Number of characters contained in self.
47 # assert "12345".length == 5
48 # assert "".length == 0
49 fun length
: Int is abstract
53 # assert "abcd".substring(1, 2) == "bc"
54 # assert "abcd".substring(-1, 2) == "a"
55 # assert "abcd".substring(1, 0) == ""
56 # assert "abcd".substring(2, 5) == "cd"
58 # A `from` index < 0 will be replaced by 0.
59 # Unless a `count` value is > 0 at the same time.
60 # In this case, `from += count` and `count -= from`.
61 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
63 # Iterates on the substrings of self if any
64 fun substrings
: Iterator[Text] is abstract
66 # Is the current Text empty (== "")
69 # assert not "foo".is_empty
70 fun is_empty
: Bool do return self.length
== 0
72 # Returns an empty Text of the right type
74 # This method is used internally to get the right
75 # implementation of an empty string.
76 protected fun empty
: SELFTYPE is abstract
78 # Gets the first char of the Text
80 # DEPRECATED : Use self.chars.first instead
81 fun first
: Char do return self.chars
[0]
83 # Access a character at `index` in the string.
85 # assert "abcd"[2] == 'c'
87 # DEPRECATED : Use self.chars.[] instead
88 fun [](index
: Int): Char do return self.chars
[index
]
90 # Gets the index of the first occurence of 'c'
92 # Returns -1 if not found
94 # DEPRECATED : Use self.chars.index_of instead
95 fun index_of
(c
: Char): Int
97 return index_of_from
(c
, 0)
100 # Gets the last char of self
102 # DEPRECATED : Use self.chars.last instead
103 fun last
: Char do return self.chars
[length-1
]
105 # Gets the index of the first occurence of ´c´ starting from ´pos´
107 # Returns -1 if not found
109 # DEPRECATED : Use self.chars.index_of_from instead
110 fun index_of_from
(c
: Char, pos
: Int): Int
112 var iter
= self.chars
.iterator_from
(pos
)
114 if iter
.item
== c
then return iter
.index
120 # Gets the last index of char ´c´
122 # Returns -1 if not found
124 # DEPRECATED : Use self.chars.last_index_of instead
125 fun last_index_of
(c
: Char): Int
127 return last_index_of_from
(c
, length
- 1)
130 # Return a null terminated char *
131 fun to_cstring
: NativeString do return flatten
.to_cstring
133 # The index of the last occurrence of an element starting from pos (in reverse order).
135 # var s = "/etc/bin/test/test.nit"
136 # assert s.last_index_of_from('/', s.length-1) == 13
137 # assert s.last_index_of_from('/', 12) == 8
139 # Returns -1 if not found
141 # DEPRECATED : Use self.chars.last_index_of_from instead
142 fun last_index_of_from
(item
: Char, pos
: Int): Int
144 var iter
= self.chars
.reverse_iterator_from
(pos
)
146 if iter
.item
== item
then return iter
.index
152 # Gets an iterator on the chars of self
154 # DEPRECATED : Use self.chars.iterator instead
155 fun iterator
: Iterator[Char]
157 return self.chars
.iterator
161 # Gets an Array containing the chars of self
163 # DEPRECATED : Use self.chars.to_a instead
164 fun to_a
: Array[Char] do return chars
.to_a
166 # Create a substring from `self` beginning at the `from` position
168 # assert "abcd".substring_from(1) == "bcd"
169 # assert "abcd".substring_from(-1) == "abcd"
170 # assert "abcd".substring_from(2) == "cd"
172 # As with substring, a `from` index < 0 will be replaced by 0
173 fun substring_from
(from
: Int): SELFTYPE
175 if from
>= self.length
then return empty
176 if from
< 0 then from
= 0
177 return substring
(from
, length
- from
)
180 # Does self have a substring `str` starting from position `pos`?
182 # assert "abcd".has_substring("bc",1) == true
183 # assert "abcd".has_substring("bc",2) == false
184 fun has_substring
(str
: String, pos
: Int): Bool
186 var myiter
= self.chars
.iterator_from
(pos
)
187 var itsiter
= str
.chars
.iterator
188 while myiter
.is_ok
and itsiter
.is_ok
do
189 if myiter
.item
!= itsiter
.item
then return false
193 if itsiter
.is_ok
then return false
197 # Is this string prefixed by `prefix`?
199 # assert "abcd".has_prefix("ab") == true
200 # assert "abcbc".has_prefix("bc") == false
201 # assert "ab".has_prefix("abcd") == false
202 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
204 # Is this string suffixed by `suffix`?
206 # assert "abcd".has_suffix("abc") == false
207 # assert "abcd".has_suffix("bcd") == true
208 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
210 # If `self` contains only digits, return the corresponding integer
212 # assert "123".to_i == 123
213 # assert "-1".to_i == -1
217 return to_s
.to_cstring
.atoi
220 # If `self` contains a float, return the corresponding float
222 # assert "123".to_f == 123.0
223 # assert "-1".to_f == -1.0
224 # assert "-1.2e-3".to_f == -0.0012
228 return to_s
.to_cstring
.atof
231 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
233 # assert "ff".to_hex == 255
234 fun to_hex
: Int do return a_to
(16)
236 # If `self` contains only digits and letters, return the corresponding integer in a given base
238 # assert "120".a_to(3) == 15
239 fun a_to
(base
: Int) : Int
244 for j
in [0..length
[ do
266 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
268 # assert "123".is_numeric == true
269 # assert "1.2".is_numeric == true
270 # assert "1,2".is_numeric == true
271 # assert "1..2".is_numeric == false
274 var has_point_or_comma
= false
275 for i
in [0..length
[ do
277 if not c
.is_numeric
then
278 if (c
== '.' or c
== ',') and not has_point_or_comma
then
279 has_point_or_comma
= true
288 # Returns `true` if the string contains only Hex chars
290 # assert "048bf".is_hex == true
291 # assert "ABCDEF".is_hex == true
292 # assert "0G".is_hex == false
295 for i
in [0..length
[ do
297 if not (c
>= 'a' and c
<= 'f') and
298 not (c
>= 'A' and c
<= 'F') and
299 not (c
>= '0' and c
<= '9') then return false
304 # Are all letters in `self` upper-case ?
306 # assert "HELLO WORLD".is_upper == true
307 # assert "%$&%!".is_upper == true
308 # assert "hello world".is_upper == false
309 # assert "Hello World".is_upper == false
312 for i
in [0..length
[ do
314 if char
.is_lower
then return false
319 # Are all letters in `self` lower-case ?
321 # assert "hello world".is_lower == true
322 # assert "%$&%!".is_lower == true
323 # assert "Hello World".is_lower == false
326 for i
in [0..length
[ do
328 if char
.is_upper
then return false
333 # Removes the whitespaces at the beginning of self
335 # assert " \n\thello \n\t".l_trim == "hello \n\t"
337 # A whitespace is defined as any character which ascii value is less than or equal to 32
340 var iter
= self.chars
.iterator
342 if iter
.item
.ascii
> 32 then break
345 if iter
.index
== length
then return self.empty
346 return self.substring_from
(iter
.index
)
349 # Removes the whitespaces at the end of self
351 # assert " \n\thello \n\t".r_trim == " \n\thello"
353 # A whitespace is defined as any character which ascii value is less than or equal to 32
356 var iter
= self.chars
.reverse_iterator
358 if iter
.item
.ascii
> 32 then break
361 if iter
.index
< 0 then return self.empty
362 return self.substring
(0, iter
.index
+ 1)
365 # Trims trailing and preceding white spaces
366 # A whitespace is defined as any character which ascii value is less than or equal to 32
368 # assert " Hello World ! ".trim == "Hello World !"
369 # assert "\na\nb\tc\t".trim == "a\nb\tc"
370 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
372 # Mangle a string to be a unique string only made of alphanumeric characters
373 fun to_cmangle
: String
375 var res
= new FlatBuffer
376 var underscore
= false
377 for i
in [0..length
[ do
379 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
385 res
.append
('_'.ascii
.to_s
)
388 if c
>= '0' and c
<= '9' then
391 else if c
== '_' then
396 res
.append
(c
.ascii
.to_s
)
404 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
406 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
407 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
408 fun escape_to_c
: String
410 var b
= new FlatBuffer
411 for i
in [0..length
[ do
415 else if c
== '\0' then
417 else if c
== '"' then
419 else if c == '\'' then
421 else if c == '\\
' then
423 else if c.ascii < 32 then
424 b.append("\\{c.ascii.to_base(8, false)}")
432 # Escape additionnal characters
433 # The result might no be legal in C but be used in other languages
435 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
436 fun escape_more_to_c(chars: String): String
438 var b = new FlatBuffer
439 for c in escape_to_c.chars do
440 if chars.chars.has(c) then
448 # Escape to C plus braces
450 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
451 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
453 # Return a string where Nit escape sequences are transformed.
456 # assert s.length == 2
457 # var u = s.unescape_nit
458 # assert u.length == 1
459 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
460 fun unescape_nit
: String
462 var res
= new FlatBuffer.with_capacity
(self.length
)
463 var was_slash
= false
464 for i
in [0..length
[ do
466 if not was_slash
then
477 else if c
== 'r' then
479 else if c
== 't' then
481 else if c
== '0' then
490 # Encode `self` to percent (or URL) encoding
492 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
493 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
494 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
495 fun to_percent_encoding
: String
497 var buf
= new FlatBuffer
499 for i
in [0..length
[ do
501 if (c
>= '0' and c
<= '9') or
502 (c
>= 'a' and c
<= 'z') or
503 (c
>= 'A' and c
<= 'Z') or
504 c
== '-' or c
== '.' or
508 else buf
.append
"%{c.ascii.to_hex}"
514 # Decode `self` from percent (or URL) encoding to a clear string
516 # Replace invalid use of '%' with '?'.
518 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
519 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
520 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
521 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
522 # assert "incomplete %".from_percent_encoding == "incomplete ?"
523 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
524 fun from_percent_encoding
: String
526 var buf
= new FlatBuffer
532 if i
+ 2 >= length
then
533 # What follows % has been cut off
537 var hex_s
= substring
(i
, 2)
539 var hex_i
= hex_s
.to_hex
543 # What follows a % is not Hex
556 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
558 # assert "a&b->\"x\"".html_escape == "a&b->"x""
559 fun html_escape
: SELFTYPE
561 var buf
= new FlatBuffer
563 for i
in [0..length
[ do
567 else if c
== '<' then
569 else if c
== '>' then
571 else if c
== '"' then
580 # Two pieces of text are equals if thez have the same characters in the same order.
582 # assert "hello" == "hello"
583 # assert "hello" != "HELLO"
584 # assert "hello" == "hel"+"lo"
586 # Things that are not Text are not equal.
589 # assert "9" != ['9']
592 # assert "9".chars.first == '9' # equality of Char
593 # assert "9".chars == ['9'] # equality of Sequence
594 # assert "9".to_i == 9 # equality of Int
597 if o
== null then return false
598 if not o
isa Text then return false
599 if self.is_same_instance
(o
) then return true
600 if self.length
!= o
.length
then return false
601 return self.chars
== o
.chars
604 # Lexicographical comparaison
606 # assert "abc" < "xy"
607 # assert "ABC" < "abc"
610 var self_chars
= self.chars
.iterator
611 var other_chars
= other
.chars
.iterator
613 while self_chars
.is_ok
and other_chars
.is_ok
do
614 if self_chars
.item
< other_chars
.item
then return true
615 if self_chars
.item
> other_chars
.item
then return false
620 if self_chars
.is_ok
then
627 # Flat representation of self
628 fun flatten
: FlatText is abstract
630 private var hash_cache
: nullable Int = null
634 if hash_cache
== null then
635 # djb2 hash algorithm
638 for i
in [0..length
[ do
640 h
= h
.lshift
(5) + h
+ char
.ascii
645 return hash_cache
.as(not null)
650 # All kinds of array-based text representations.
651 abstract class FlatText
654 private var items
: NativeString
656 # Real items, used as cache for to_cstring is called
657 private var real_items
: nullable NativeString = null
659 redef var length
: Int = 0
672 redef fun flatten
do return self
675 # Abstract class for the SequenceRead compatible
676 # views on String and Buffer objects
677 private abstract class StringCharView
678 super SequenceRead[Char]
682 private var target
: SELFTYPE
684 private init(tgt
: SELFTYPE)
689 redef fun is_empty
do return target
.is_empty
691 redef fun length
do return target
.length
693 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
695 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
698 # View on Buffer objects, extends Sequence
699 # for mutation operations
700 private abstract class BufferCharView
704 redef type SELFTYPE: Buffer
708 abstract class String
711 redef type SELFTYPE: String
713 redef fun to_s
do return self
715 # Concatenates `o` to `self`
717 # assert "hello" + "world" == "helloworld"
718 # assert "" + "hello" + "" == "hello"
719 fun +(o
: Text): SELFTYPE is abstract
721 # Concatenates self `i` times
723 # assert "abc" * 4 == "abcabcabcabc"
724 # assert "abc" * 1 == "abc"
725 # assert "abc" * 0 == ""
726 fun *(i
: Int): SELFTYPE is abstract
728 fun insert_at
(s
: String, pos
: Int): SELFTYPE is abstract
730 # Returns a reversed version of self
732 # assert "hello".reversed == "olleh"
733 # assert "bob".reversed == "bob"
734 # assert "".reversed == ""
735 fun reversed
: SELFTYPE is abstract
737 # A upper case version of `self`
739 # assert "Hello World!".to_upper == "HELLO WORLD!"
740 fun to_upper
: SELFTYPE is abstract
742 # A lower case version of `self`
744 # assert "Hello World!".to_lower == "hello world!"
745 fun to_lower
: SELFTYPE is abstract
747 # Takes a camel case `self` and converts it to snake case
749 # assert "randomMethodId".to_snake_case == "random_method_id"
751 # If `self` is upper, it is returned unchanged
753 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
755 # If the identifier is prefixed by an underscore, the underscore is ignored
757 # assert "_privateField".to_snake_case == "_private_field"
758 fun to_snake_case
: SELFTYPE
760 if self.is_upper
then return self
762 var new_str
= new FlatBuffer.with_capacity
(self.length
)
763 var is_first_char
= true
765 for i
in [0..length
[ do
767 if is_first_char
then
768 new_str
.add
(char
.to_lower
)
769 is_first_char
= false
770 else if char
.is_upper
then
772 new_str
.add
(char
.to_lower
)
781 # Takes a snake case `self` and converts it to camel case
783 # assert "random_method_id".to_camel_case == "randomMethodId"
785 # If the identifier is prefixed by an underscore, the underscore is ignored
787 # assert "_private_field".to_camel_case == "_privateField"
789 # If `self` is upper, it is returned unchanged
791 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
793 # If there are several consecutive underscores, they are considered as a single one
795 # assert "random__method_id".to_camel_case == "randomMethodId"
796 fun to_camel_case
: SELFTYPE
798 if self.is_upper
then return self
800 var new_str
= new FlatBuffer
801 var is_first_char
= true
802 var follows_us
= false
804 for i
in [0..length
[ do
806 if is_first_char
then
808 is_first_char
= false
809 else if char
== '_' then
811 else if follows_us
then
812 new_str
.add
(char
.to_upper
)
823 private class FlatSubstringsIter
824 super Iterator[FlatText]
826 var tgt
: nullable FlatText
828 init(tgt
: FlatText) do self.tgt
= tgt
832 return tgt
.as(not null)
835 redef fun is_ok
do return tgt
!= null
837 redef fun next
do tgt
= null
840 # Immutable strings of characters.
845 # Index in _items of the start of the string
846 private var index_from
: Int
848 # Indes in _items of the last item of the string
849 private var index_to
: Int
851 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
855 # Check that the index (+ index_from) is not larger than indexTo
856 # In other terms, if the index is valid
858 assert (index
+ index_from
) <= index_to
859 return items
[index
+ index_from
]
862 ################################################
863 # AbstractString specific methods #
864 ################################################
868 var native
= calloc_string
(self.length
+ 1)
869 var length
= self.length
870 var items
= self.items
873 while pos
< length
do
874 native
[pos
] = items
[ipos
]
878 return native
.to_s_with_length
(self.length
)
881 redef fun substring
(from
, count
)
887 if count
< 0 then count
= 0
891 var realFrom
= index_from
+ from
893 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
895 if count
== 0 then return empty
897 var to
= realFrom
+ count
- 1
899 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
902 redef fun empty
do return "".as(FlatString)
906 var outstr
= calloc_string
(self.length
+ 1)
909 var myitems
= self.items
910 var index_from
= self.index_from
911 var max
= self.index_to
913 while index_from
<= max
do
914 outstr
[out_index
] = myitems
[index_from
].to_upper
919 outstr
[self.length
] = '\0'
921 return outstr
.to_s_with_length
(self.length
)
926 var outstr
= calloc_string
(self.length
+ 1)
929 var myitems
= self.items
930 var index_from
= self.index_from
931 var max
= self.index_to
933 while index_from
<= max
do
934 outstr
[out_index
] = myitems
[index_from
].to_lower
939 outstr
[self.length
] = '\0'
941 return outstr
.to_s_with_length
(self.length
)
946 var i
= self.index_from
947 var imax
= self.index_to
954 ##################################################
955 # String Specific Methods #
956 ##################################################
958 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
966 redef fun to_cstring
: NativeString
968 if real_items
!= null then return real_items
.as(not null)
969 if index_from
> 0 or index_to
!= items
.cstring_length
- 1 then
970 var newItems
= calloc_string
(length
+ 1)
971 self.items
.copy_to
(newItems
, length
, index_from
, 0)
972 newItems
[length
] = '\0'
973 self.real_items
= newItems
981 if not other
isa FlatString then return super
983 if self.object_id
== other
.object_id
then return true
985 var my_length
= length
987 if other
.length
!= my_length
then return false
989 var my_index
= index_from
990 var its_index
= other
.index_from
992 var last_iteration
= my_index
+ my_length
994 var itsitems
= other
.items
995 var myitems
= self.items
997 while my_index
< last_iteration
do
998 if myitems
[my_index
] != itsitems
[its_index
] then return false
1008 if not other
isa FlatString then return super
1010 if self.object_id
== other
.object_id
then return false
1012 var my_curr_char
: Char
1013 var its_curr_char
: Char
1015 var curr_id_self
= self.index_from
1016 var curr_id_other
= other
.index_from
1018 var my_items
= self.items
1019 var its_items
= other
.items
1021 var my_length
= self.length
1022 var its_length
= other
.length
1024 var max_iterations
= curr_id_self
+ my_length
1026 while curr_id_self
< max_iterations
do
1027 my_curr_char
= my_items
[curr_id_self
]
1028 its_curr_char
= its_items
[curr_id_other
]
1030 if my_curr_char
!= its_curr_char
then
1031 if my_curr_char
< its_curr_char
then return true
1039 return my_length
< its_length
1044 var my_length
= self.length
1045 var its_length
= s
.length
1047 var total_length
= my_length
+ its_length
1049 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
1051 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
1052 if s
isa FlatString then
1053 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
1054 else if s
isa FlatBuffer then
1055 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
1057 var curr_pos
= my_length
1058 for i
in [0..s
.length
[ do
1060 target_string
[curr_pos
] = c
1065 target_string
[total_length
] = '\0'
1067 return target_string
.to_s_with_length
(total_length
)
1074 var my_length
= self.length
1076 var final_length
= my_length
* i
1078 var my_items
= self.items
1080 var target_string
= calloc_string
((final_length
) + 1)
1082 target_string
[final_length
] = '\0'
1084 var current_last
= 0
1086 for iteration
in [1 .. i
] do
1087 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
1088 current_last
+= my_length
1091 return target_string
.to_s_with_length
(final_length
)
1096 if hash_cache
== null then
1097 # djb2 hash algorithm
1103 while i
<= index_to
do
1104 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
1111 return hash_cache
.as(not null)
1114 redef fun substrings
do return new FlatSubstringsIter(self)
1117 private class FlatStringReverseIterator
1118 super IndexedIterator[Char]
1120 var target
: FlatString
1122 var target_items
: NativeString
1126 init with_pos
(tgt
: FlatString, pos
: Int)
1129 target_items
= tgt
.items
1130 curr_pos
= pos
+ tgt
.index_from
1133 redef fun is_ok
do return curr_pos
>= target
.index_from
1135 redef fun item
do return target_items
[curr_pos
]
1137 redef fun next
do curr_pos
-= 1
1139 redef fun index
do return curr_pos
- target
.index_from
1143 private class FlatStringIterator
1144 super IndexedIterator[Char]
1146 var target
: FlatString
1148 var target_items
: NativeString
1152 init with_pos
(tgt
: FlatString, pos
: Int)
1155 target_items
= tgt
.items
1156 curr_pos
= pos
+ target
.index_from
1159 redef fun is_ok
do return curr_pos
<= target
.index_to
1161 redef fun item
do return target_items
[curr_pos
]
1163 redef fun next
do curr_pos
+= 1
1165 redef fun index
do return curr_pos
- target
.index_from
1169 private class FlatStringCharView
1170 super StringCharView
1172 redef type SELFTYPE: FlatString
1176 # Check that the index (+ index_from) is not larger than indexTo
1177 # In other terms, if the index is valid
1179 var target
= self.target
1180 assert (index
+ target
.index_from
) <= target
.index_to
1181 return target
.items
[index
+ target
.index_from
]
1184 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
1186 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
1190 abstract class Buffer
1193 redef type SELFTYPE: Buffer
1195 # Specific implementations MUST set this to `true` in order to invalidate caches
1196 protected var is_dirty
= true
1198 # Modifies the char contained at pos `index`
1200 # DEPRECATED : Use self.chars.[]= instead
1201 fun []=(index
: Int, item
: Char) is abstract
1203 # Adds a char `c` at the end of self
1205 # DEPRECATED : Use self.chars.add instead
1206 fun add
(c
: Char) is abstract
1210 # var b = new FlatBuffer
1212 # assert not b.is_empty
1215 fun clear
is abstract
1217 # Enlarges the subsequent array containing the chars of self
1218 fun enlarge
(cap
: Int) is abstract
1220 # Adds the content of text `s` at the end of self
1222 # var b = new FlatBuffer
1225 # assert b == "helloworld"
1226 fun append
(s
: Text) is abstract
1228 # `self` is appended in such a way that `self` is repeated `r` times
1230 # var b = new FlatBuffer
1233 # assert b == "hellohellohello"
1234 fun times
(r
: Int) is abstract
1236 # Reverses itself in-place
1238 # var b = new FlatBuffer
1241 # assert b == "olleh"
1242 fun reverse
is abstract
1244 # Changes each lower-case char in `self` by its upper-case variant
1246 # var b = new FlatBuffer
1247 # b.append("Hello World!")
1249 # assert b == "HELLO WORLD!"
1250 fun upper
is abstract
1252 # Changes each upper-case char in `self` by its lower-case variant
1254 # var b = new FlatBuffer
1255 # b.append("Hello World!")
1257 # assert b == "hello world!"
1258 fun lower
is abstract
1262 if is_dirty
then hash_cache
= null
1266 # In Buffers, the internal sequence of character is mutable
1267 # Thus, `chars` can be used to modify the buffer.
1268 redef fun chars
: Sequence[Char] is abstract
1271 # Mutable strings of characters.
1276 redef type SELFTYPE: FlatBuffer
1278 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1280 private var capacity
: Int = 0
1282 redef fun substrings
do return new FlatSubstringsIter(self)
1287 assert index
< length
1291 redef fun []=(index
, item
)
1294 if index
== length
then
1298 assert index
>= 0 and index
< length
1305 if capacity
<= length
then enlarge
(length
+ 5)
1315 redef fun empty
do return new FlatBuffer
1317 redef fun enlarge
(cap
)
1320 if cap
<= c
then return
1321 while c
<= cap
do c
= c
* 2 + 2
1322 var a
= calloc_string
(c
+1)
1323 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1328 redef fun to_s
: String
1330 return to_cstring
.to_s_with_length
(length
)
1333 redef fun to_cstring
1336 var new_native
= calloc_string
(length
+ 1)
1337 new_native
[length
] = '\0'
1338 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1339 real_items
= new_native
1342 return real_items
.as(not null)
1345 # Create a new empty string.
1350 capacity
= s
.length
+ 1
1352 items
= calloc_string
(capacity
)
1353 if s
isa FlatString then
1354 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1355 else if s
isa FlatBuffer then
1356 s
.items
.copy_to
(items
, length
, 0, 0)
1359 for i
in [0..s
.length
[ do
1367 # Create a new empty string with a given capacity.
1368 init with_capacity
(cap
: Int)
1371 # _items = new NativeString.calloc(cap)
1372 items
= calloc_string
(cap
+1)
1379 if s
.is_empty
then return
1382 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1383 if s
isa FlatString then
1384 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1385 else if s
isa FlatBuffer then
1386 s
.items
.copy_to
(items
, sl
, 0, length
)
1388 var curr_pos
= self.length
1389 for i
in [0..s
.length
[ do
1398 # Copies the content of self in `dest`
1399 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1401 var self_chars
= self.chars
1402 var dest_chars
= dest
.chars
1403 for i
in [0..len-1
] do
1404 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1408 redef fun substring
(from
, count
)
1412 if from
< 0 then from
= 0
1413 if count
> length
then count
= length
1414 if from
< count
then
1415 var r
= new FlatBuffer.with_capacity
(count
- from
)
1416 while from
< count
do
1417 r
.chars
.push
(items
[from
])
1422 return new FlatBuffer
1428 var ns
= calloc_string
(capacity
)
1440 redef fun times
(repeats
)
1442 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1443 for i
in [1..repeats
[ do
1453 it
[id
] = it
[id
].to_upper
1463 it
[id
] = it
[id
].to_lower
1469 private class FlatBufferReverseIterator
1470 super IndexedIterator[Char]
1472 var target
: FlatBuffer
1474 var target_items
: NativeString
1478 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1481 if tgt
.length
> 0 then target_items
= tgt
.items
1485 redef fun index
do return curr_pos
1487 redef fun is_ok
do return curr_pos
>= 0
1489 redef fun item
do return target_items
[curr_pos
]
1491 redef fun next
do curr_pos
-= 1
1495 private class FlatBufferCharView
1496 super BufferCharView
1499 redef type SELFTYPE: FlatBuffer
1501 redef fun [](index
) do return target
.items
[index
]
1503 redef fun []=(index
, item
)
1505 assert index
>= 0 and index
<= length
1506 if index
== length
then
1510 target
.items
[index
] = item
1523 fun enlarge
(cap
: Int)
1530 var my_items
= target
.items
1531 var s_length
= s
.length
1532 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1535 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1537 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1541 private class FlatBufferIterator
1542 super IndexedIterator[Char]
1544 var target
: FlatBuffer
1546 var target_items
: NativeString
1550 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1553 if tgt
.length
> 0 then target_items
= tgt
.items
1557 redef fun index
do return curr_pos
1559 redef fun is_ok
do return curr_pos
< target
.length
1561 redef fun item
do return target_items
[curr_pos
]
1563 redef fun next
do curr_pos
+= 1
1567 ###############################################################################
1569 ###############################################################################
1572 # User readable representation of `self`.
1573 fun to_s
: String do return inspect
1575 # The class name of the object in NativeString format.
1576 private fun native_class_name
: NativeString is intern
1578 # The class name of the object.
1580 # assert 5.class_name == "Int"
1581 fun class_name
: String do return native_class_name
.to_s
1583 # Developer readable representation of `self`.
1584 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1587 return "<{inspect_head}>"
1590 # Return "CLASSNAME:#OBJECTID".
1591 # This function is mainly used with the redefinition of the inspect method
1592 protected fun inspect_head
: String
1594 return "{class_name}:#{object_id.to_hex}"
1599 # assert true.to_s == "true"
1600 # assert false.to_s == "false"
1613 # Wrapper of strerror C function
1614 private fun strerror_ext
: NativeString is extern `{
1615 return strerror(recv);
1618 # Returns a string describing error number
1619 fun strerror
: String do return strerror_ext
.to_s
1621 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1622 # assume < to_c max const of char
1623 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1630 else if self == 0 then
1637 var pos
= digit_count
(base
) - 1
1638 while pos
>= 0 and n
> 0 do
1639 s
.chars
[pos
] = (n
% base
).to_c
1645 # C function to convert an nit Int to a NativeString (char*)
1646 private fun native_int_to_s
: NativeString is extern "native_int_to_s"
1648 # return displayable int in base 10 and signed
1650 # assert 1.to_s == "1"
1651 # assert (-123).to_s == "-123"
1653 return native_int_to_s
.to_s
1656 # return displayable int in hexadecimal
1658 # assert 1.to_hex == "1"
1659 # assert (-255).to_hex == "-ff"
1660 fun to_hex
: String do return to_base
(16,false)
1662 # return displayable int in base base and signed
1663 fun to_base
(base
: Int, signed
: Bool): String
1665 var l
= digit_count
(base
)
1666 var s
= new FlatBuffer.from
(" " * l
)
1667 fill_buffer
(s
, base
, signed
)
1673 # Pretty print self, print needoed decimals up to a max of 3.
1675 # assert 12.34.to_s == "12.34"
1676 # assert (-0120.03450).to_s == "-120.035"
1678 # see `to_precision` for a different precision.
1680 var str
= to_precision
( 3 )
1681 if is_inf
!= 0 or is_nan
then return str
1682 var len
= str
.length
1683 for i
in [0..len-1
] do
1685 var c
= str
.chars
[j
]
1688 else if c
== '.' then
1689 return str
.substring
( 0, j
+2 )
1691 return str
.substring
( 0, j
+1 )
1697 # `self` representation with `nb` digits after the '.'.
1699 # assert 12.345.to_precision(1) == "12.3"
1700 # assert 12.345.to_precision(2) == "12.35"
1701 # assert 12.345.to_precision(3) == "12.345"
1702 # assert 12.345.to_precision(4) == "12.3450"
1703 fun to_precision
(nb
: Int): String
1705 if is_nan
then return "nan"
1707 var isinf
= self.is_inf
1710 else if isinf
== -1 then
1714 if nb
== 0 then return self.to_i
.to_s
1716 for i
in [0..nb
[ do f
= f
* 10.0
1723 if i
== 0 then return "0.0"
1727 var p1
= s
.substring
(0, s
.length-nb
)
1728 var p2
= s
.substring
(s
.length-nb
, nb
)
1729 return p1
+ "." + p2
1731 return "0." + ("0"*(nb-sl
)) + s
1735 # `self` representation with `nb` digits after the '.'.
1737 # assert 12.345.to_precision_native(1) == "12.3"
1738 # assert 12.345.to_precision_native(2) == "12.35"
1739 # assert 12.345.to_precision_native(3) == "12.345"
1740 # assert 12.345.to_precision_native(4) == "12.3450"
1741 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1745 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1746 str = malloc(size + 1);
1747 sprintf(str, "%.*f", (int)nb, recv );
1749 return NativeString_to_s( str );
1754 # assert 'x'.to_s == "x"
1757 var s
= new FlatBuffer.with_capacity
(1)
1762 # Returns true if the char is a numerical digit
1764 # assert '0'.is_numeric
1765 # assert '9'.is_numeric
1766 # assert not 'a'.is_numeric
1767 # assert not '?'.is_numeric
1768 fun is_numeric
: Bool
1770 return self >= '0' and self <= '9'
1773 # Returns true if the char is an alpha digit
1775 # assert 'a'.is_alpha
1776 # assert 'Z'.is_alpha
1777 # assert not '0'.is_alpha
1778 # assert not '?'.is_alpha
1781 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1784 # Returns true if the char is an alpha or a numeric digit
1786 # assert 'a'.is_alphanumeric
1787 # assert 'Z'.is_alphanumeric
1788 # assert '0'.is_alphanumeric
1789 # assert '9'.is_alphanumeric
1790 # assert not '?'.is_alphanumeric
1791 fun is_alphanumeric
: Bool
1793 return self.is_numeric
or self.is_alpha
1797 redef class Collection[E
]
1798 # Concatenate elements.
1801 var s
= new FlatBuffer
1802 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1806 # Concatenate and separate each elements with `sep`.
1808 # assert [1, 2, 3].join(":") == "1:2:3"
1809 # assert [1..3].join(":") == "1:2:3"
1810 fun join
(sep
: Text): String
1812 if is_empty
then return ""
1814 var s
= new FlatBuffer # Result
1819 if e
!= null then s
.append
(e
.to_s
)
1821 # Concat other items
1826 if e
!= null then s
.append
(e
.to_s
)
1833 redef class Array[E
]
1835 # Fast implementation
1839 if l
== 0 then return ""
1840 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
1842 var na
= new NativeArray[String](l
)
1848 if itsi
== null then
1858 var ns
= new NativeString(sl
+ 1)
1864 var tpl
= tmp
.length
1865 if tmp
isa FlatString then
1866 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
1869 for j
in tmp
.substrings
do
1870 var s
= j
.as(FlatString)
1872 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
1878 return ns
.to_s_with_length
(sl
)
1882 redef class Map[K
,V
]
1883 # Concatenate couple of 'key value'.
1884 # key and value are separated by `couple_sep`.
1885 # each couple is separated each couple with `sep`.
1887 # var m = new ArrayMap[Int, String]
1890 # assert m.join("; ", "=") == "1=one; 10=ten"
1891 fun join
(sep
: String, couple_sep
: String): String
1893 if is_empty
then return ""
1895 var s
= new FlatBuffer # Result
1901 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1903 # Concat other items
1909 s
.append
("{k}{couple_sep}{e or else "<null>"}")
1916 ###############################################################################
1918 ###############################################################################
1920 # Native strings are simple C char *
1921 extern class NativeString `{ char* `}
1923 # Creates a new NativeString with a capacity of `length
`
1924 new(length: Int) is intern
1925 fun [](index: Int): Char is intern
1926 fun []=(index: Int, item: Char) is intern
1927 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
1929 # Position of the first nul character.
1930 fun cstring_length: Int
1933 while self[l] != '\0' do l += 1
1936 fun atoi: Int is intern
1937 fun atof: Float is extern "atof"
1941 return to_s_with_length(cstring_length)
1944 fun to_s_with_length(length: Int): FlatString
1947 return new FlatString.with_infos(self, length, 0, length - 1)
1950 fun to_s_with_copy: FlatString
1952 var length = cstring_length
1953 var new_self = calloc_string(length + 1)
1954 copy_to(new_self, length, 0, 0)
1955 return new FlatString.with_infos(new_self, length, 0, length - 1)
1959 # StringCapable objects can create native strings
1960 interface StringCapable
1961 protected fun calloc_string(size: Int): NativeString is intern
1965 private var args_cache: nullable Sequence[String]
1967 # The arguments of the program as given by the OS
1968 fun program_args: Sequence[String]
1970 if _args_cache == null then init_args
1971 return _args_cache.as(not null)
1974 # The name of the program as given by the OS
1975 fun program_name: String
1977 return native_argv(0).to_s
1980 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
1981 private fun init_args
1983 var argc = native_argc
1984 var args = new Array[String].with_capacity(0)
1987 args[i-1] = native_argv(i).to_s
1993 # First argument of the main C function.
1994 private fun native_argc: Int is intern
1996 # Second argument of the main C function.
1997 private fun native_argv(i: Int): NativeString is intern
2000 # Comparator that efficienlty use `to_s
` to compare things
2002 # The comparaison call `to_s
` on object and use the result to order things.
2004 # var a = [1, 2, 3, 10, 20]
2005 # (new CachedAlphaComparator).sort(a)
2006 # assert a == [1, 10, 2, 20, 3]
2008 # Internally the result of `to_s
` is cached in a HashMap to counter
2009 # uneficient implementation of `to_s
`.
2011 # Note: it caching is not usefull, see `alpha_comparator
`
2012 class CachedAlphaComparator
2013 super Comparator[Object]
2015 private var cache = new HashMap[Object, String]
2017 private fun do_to_s(a: Object): String do
2018 if cache.has_key(a) then return cache[a]
2024 redef fun compare(a, b) do
2025 return do_to_s(a) <=> do_to_s(b)
2029 # see `alpha_comparator
`
2030 private class AlphaComparator
2031 super Comparator[Object]
2032 redef fun compare(a, b) do return a.to_s <=> b.to_s
2035 # Stateless comparator that naively use `to_s
` to compare things.
2037 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2038 # on a single instace. See `CachedAlphaComparator` as an alternative.
2040 # var a = [1, 2, 3, 10, 20]
2041 # alpha_comparator.sort(a)
2042 # assert a == [1, 10, 2, 20, 3]
2043 fun alpha_comparator: Comparator[Object] do return once new AlphaComparator
2045 # The arguments of the program as given by the OS
2046 fun args: Sequence[String]
2048 return sys.program_args