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
185 # Returns true iff all characters of `str` are presents
186 # at the expected index in `self.`
187 # The first character of `str` being at `pos`, the second
188 # character being at `pos+1` and so on...
190 # This means that all characters of `str` need to be inside `self`.
192 # assert "abcd".has_substring("xab", -1) == false
193 # assert "abcd".has_substring("cdx", 2) == false
195 # And that the empty string is always a valid substring.
197 # assert "abcd".has_substring("", 2) == true
198 # assert "abcd".has_substring("", 200) == true
199 fun has_substring
(str
: String, pos
: Int): Bool
201 if str
.is_empty
then return true
202 if pos
< 0 or pos
+ str
.length
> length
then return false
203 var myiter
= self.chars
.iterator_from
(pos
)
204 var itsiter
= str
.chars
.iterator
205 while myiter
.is_ok
and itsiter
.is_ok
do
206 if myiter
.item
!= itsiter
.item
then return false
210 if itsiter
.is_ok
then return false
214 # Is this string prefixed by `prefix`?
216 # assert "abcd".has_prefix("ab") == true
217 # assert "abcbc".has_prefix("bc") == false
218 # assert "ab".has_prefix("abcd") == false
219 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
221 # Is this string suffixed by `suffix`?
223 # assert "abcd".has_suffix("abc") == false
224 # assert "abcd".has_suffix("bcd") == true
225 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
227 # If `self` contains only digits, return the corresponding integer
229 # assert "123".to_i == 123
230 # assert "-1".to_i == -1
234 return to_s
.to_cstring
.atoi
237 # If `self` contains a float, return the corresponding float
239 # assert "123".to_f == 123.0
240 # assert "-1".to_f == -1.0
241 # assert "-1.2e-3".to_f == -0.0012
245 return to_s
.to_cstring
.atof
248 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
250 # assert "ff".to_hex == 255
251 fun to_hex
: Int do return a_to
(16)
253 # If `self` contains only digits and letters, return the corresponding integer in a given base
255 # assert "120".a_to(3) == 15
256 fun a_to
(base
: Int) : Int
261 for j
in [0..length
[ do
283 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
285 # assert "123".is_numeric == true
286 # assert "1.2".is_numeric == true
287 # assert "1,2".is_numeric == true
288 # assert "1..2".is_numeric == false
291 var has_point_or_comma
= false
292 for i
in [0..length
[ do
294 if not c
.is_numeric
then
295 if (c
== '.' or c
== ',') and not has_point_or_comma
then
296 has_point_or_comma
= true
305 # Returns `true` if the string contains only Hex chars
307 # assert "048bf".is_hex == true
308 # assert "ABCDEF".is_hex == true
309 # assert "0G".is_hex == false
312 for i
in [0..length
[ do
314 if not (c
>= 'a' and c
<= 'f') and
315 not (c
>= 'A' and c
<= 'F') and
316 not (c
>= '0' and c
<= '9') then return false
321 # Are all letters in `self` upper-case ?
323 # assert "HELLO WORLD".is_upper == true
324 # assert "%$&%!".is_upper == true
325 # assert "hello world".is_upper == false
326 # assert "Hello World".is_upper == false
329 for i
in [0..length
[ do
331 if char
.is_lower
then return false
336 # Are all letters in `self` lower-case ?
338 # assert "hello world".is_lower == true
339 # assert "%$&%!".is_lower == true
340 # assert "Hello World".is_lower == false
343 for i
in [0..length
[ do
345 if char
.is_upper
then return false
350 # Removes the whitespaces at the beginning of self
352 # assert " \n\thello \n\t".l_trim == "hello \n\t"
354 # A whitespace is defined as any character which ascii value is less than or equal to 32
357 var iter
= self.chars
.iterator
359 if iter
.item
.ascii
> 32 then break
362 if iter
.index
== length
then return self.empty
363 return self.substring_from
(iter
.index
)
366 # Removes the whitespaces at the end of self
368 # assert " \n\thello \n\t".r_trim == " \n\thello"
370 # A whitespace is defined as any character which ascii value is less than or equal to 32
373 var iter
= self.chars
.reverse_iterator
375 if iter
.item
.ascii
> 32 then break
378 if iter
.index
< 0 then return self.empty
379 return self.substring
(0, iter
.index
+ 1)
382 # Trims trailing and preceding white spaces
383 # A whitespace is defined as any character which ascii value is less than or equal to 32
385 # assert " Hello World ! ".trim == "Hello World !"
386 # assert "\na\nb\tc\t".trim == "a\nb\tc"
387 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
389 # Justify a self in a space of `length`
391 # `left` is the space ratio on the left side.
392 # * 0.0 for left-justified (no space at the left)
393 # * 1.0 for right-justified (all spaces at the left)
394 # * 0.5 for centered (half the spaces at the left)
396 # assert "hello".justify(10, 0.0) == "hello "
397 # assert "hello".justify(10, 1.0) == " hello"
398 # assert "hello".justify(10, 0.5) == " hello "
400 # If `length` is not enough, `self` is returned as is.
402 # assert "hello".justify(2, 0.0) == "hello"
404 # REQUIRE: left >= 0.0 and left <= 1.0
405 # ENSURE: `self.length <= length implies result.length == length`
406 # ENSURE: `self.length >= length implies result == self
407 fun justify
(length
: Int, left
: Float): SELFTYPE
409 var diff
= length
- self.length
410 if diff
<= 0 then return self
411 assert left
>= 0.0 and left
<= 1.0
412 var before
= (diff
.to_f
* left
).to_i
413 return " " * before
+ self + " " * (diff-before
)
416 # Mangle a string to be a unique string only made of alphanumeric characters
417 fun to_cmangle
: String
419 var res
= new FlatBuffer
420 var underscore
= false
421 for i
in [0..length
[ do
423 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
429 res
.append
('_'.ascii
.to_s
)
432 if c
>= '0' and c
<= '9' then
435 else if c
== '_' then
440 res
.append
(c
.ascii
.to_s
)
448 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
450 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
451 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
452 fun escape_to_c
: String
454 var b
= new FlatBuffer
455 for i
in [0..length
[ do
459 else if c
== '\0' then
461 else if c
== '"' then
463 else if c == '\'' then
465 else if c == '\\
' then
467 else if c.ascii < 32 then
468 b.append("\\{c.ascii.to_base(8, false)}")
476 # Escape additionnal characters
477 # The result might no be legal in C but be used in other languages
479 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
480 fun escape_more_to_c(chars: String): String
482 var b = new FlatBuffer
483 for c in escape_to_c.chars do
484 if chars.chars.has(c) then
492 # Escape to C plus braces
494 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
495 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
497 # Return a string where Nit escape sequences are transformed.
500 # assert s.length == 2
501 # var u = s.unescape_nit
502 # assert u.length == 1
503 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
504 fun unescape_nit
: String
506 var res
= new FlatBuffer.with_capacity
(self.length
)
507 var was_slash
= false
508 for i
in [0..length
[ do
510 if not was_slash
then
521 else if c
== 'r' then
523 else if c
== 't' then
525 else if c
== '0' then
534 # Encode `self` to percent (or URL) encoding
536 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
537 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
538 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
539 fun to_percent_encoding
: String
541 var buf
= new FlatBuffer
543 for i
in [0..length
[ do
545 if (c
>= '0' and c
<= '9') or
546 (c
>= 'a' and c
<= 'z') or
547 (c
>= 'A' and c
<= 'Z') or
548 c
== '-' or c
== '.' or
552 else buf
.append
"%{c.ascii.to_hex}"
558 # Decode `self` from percent (or URL) encoding to a clear string
560 # Replace invalid use of '%' with '?'.
562 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
563 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
564 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
565 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
566 # assert "incomplete %".from_percent_encoding == "incomplete ?"
567 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
568 fun from_percent_encoding
: String
570 var buf
= new FlatBuffer
576 if i
+ 2 >= length
then
577 # What follows % has been cut off
581 var hex_s
= substring
(i
, 2)
583 var hex_i
= hex_s
.to_hex
587 # What follows a % is not Hex
600 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
602 # assert "a&b->\"x\"".html_escape == "a&b->"x""
603 fun html_escape
: SELFTYPE
605 var buf
= new FlatBuffer
607 for i
in [0..length
[ do
611 else if c
== '<' then
613 else if c
== '>' then
615 else if c
== '"' then
624 # Two pieces of text are equals if thez have the same characters in the same order.
626 # assert "hello" == "hello"
627 # assert "hello" != "HELLO"
628 # assert "hello" == "hel"+"lo"
630 # Things that are not Text are not equal.
633 # assert "9" != ['9']
636 # assert "9".chars.first == '9' # equality of Char
637 # assert "9".chars == ['9'] # equality of Sequence
638 # assert "9".to_i == 9 # equality of Int
641 if o
== null then return false
642 if not o
isa Text then return false
643 if self.is_same_instance
(o
) then return true
644 if self.length
!= o
.length
then return false
645 return self.chars
== o
.chars
648 # Lexicographical comparaison
650 # assert "abc" < "xy"
651 # assert "ABC" < "abc"
654 var self_chars
= self.chars
.iterator
655 var other_chars
= other
.chars
.iterator
657 while self_chars
.is_ok
and other_chars
.is_ok
do
658 if self_chars
.item
< other_chars
.item
then return true
659 if self_chars
.item
> other_chars
.item
then return false
664 if self_chars
.is_ok
then
671 # Escape string used in labels for graphviz
673 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
674 fun escape_to_dot
: String
676 return escape_more_to_c
("|\{\}<>")
679 # Flat representation of self
680 fun flatten
: FlatText is abstract
682 private var hash_cache
: nullable Int = null
686 if hash_cache
== null then
687 # djb2 hash algorithm
690 for i
in [0..length
[ do
692 h
= h
.lshift
(5) + h
+ char
.ascii
697 return hash_cache
.as(not null)
702 # All kinds of array-based text representations.
703 abstract class FlatText
706 # Underlying C-String (`char*`)
708 # Warning : Might be void in some subclasses, be sure to check
709 # if set before using it.
710 private var items
: NativeString is noinit
712 # Real items, used as cache for to_cstring is called
713 private var real_items
: nullable NativeString = null
715 redef var length
: Int = 0
728 redef fun flatten
do return self
731 # Abstract class for the SequenceRead compatible
732 # views on String and Buffer objects
733 private abstract class StringCharView
734 super SequenceRead[Char]
738 private var target
: SELFTYPE
740 redef fun is_empty
do return target
.is_empty
742 redef fun length
do return target
.length
744 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
746 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
749 # View on Buffer objects, extends Sequence
750 # for mutation operations
751 private abstract class BufferCharView
755 redef type SELFTYPE: Buffer
759 abstract class String
762 redef type SELFTYPE: String
764 redef fun to_s
do return self
766 # Concatenates `o` to `self`
768 # assert "hello" + "world" == "helloworld"
769 # assert "" + "hello" + "" == "hello"
770 fun +(o
: Text): SELFTYPE is abstract
772 # Concatenates self `i` times
774 # assert "abc" * 4 == "abcabcabcabc"
775 # assert "abc" * 1 == "abc"
776 # assert "abc" * 0 == ""
777 fun *(i
: Int): SELFTYPE is abstract
779 fun insert_at
(s
: String, pos
: Int): SELFTYPE is abstract
781 # Returns a reversed version of self
783 # assert "hello".reversed == "olleh"
784 # assert "bob".reversed == "bob"
785 # assert "".reversed == ""
786 fun reversed
: SELFTYPE is abstract
788 # A upper case version of `self`
790 # assert "Hello World!".to_upper == "HELLO WORLD!"
791 fun to_upper
: SELFTYPE is abstract
793 # A lower case version of `self`
795 # assert "Hello World!".to_lower == "hello world!"
796 fun to_lower
: SELFTYPE is abstract
798 # Takes a camel case `self` and converts it to snake case
800 # assert "randomMethodId".to_snake_case == "random_method_id"
802 # If `self` is upper, it is returned unchanged
804 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
806 # If the identifier is prefixed by an underscore, the underscore is ignored
808 # assert "_privateField".to_snake_case == "_private_field"
809 fun to_snake_case
: SELFTYPE
811 if self.is_upper
then return self
813 var new_str
= new FlatBuffer.with_capacity
(self.length
)
814 var is_first_char
= true
816 for i
in [0..length
[ do
818 if is_first_char
then
819 new_str
.add
(char
.to_lower
)
820 is_first_char
= false
821 else if char
.is_upper
then
823 new_str
.add
(char
.to_lower
)
832 # Takes a snake case `self` and converts it to camel case
834 # assert "random_method_id".to_camel_case == "randomMethodId"
836 # If the identifier is prefixed by an underscore, the underscore is ignored
838 # assert "_private_field".to_camel_case == "_privateField"
840 # If `self` is upper, it is returned unchanged
842 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
844 # If there are several consecutive underscores, they are considered as a single one
846 # assert "random__method_id".to_camel_case == "randomMethodId"
847 fun to_camel_case
: SELFTYPE
849 if self.is_upper
then return self
851 var new_str
= new FlatBuffer
852 var is_first_char
= true
853 var follows_us
= false
855 for i
in [0..length
[ do
857 if is_first_char
then
859 is_first_char
= false
860 else if char
== '_' then
862 else if follows_us
then
863 new_str
.add
(char
.to_upper
)
873 # Returns a capitalized `self`
875 # Letters that follow a letter are lowercased
876 # Letters that follow a non-letter are upcased.
878 # SEE : `Char::is_letter` for the definition of letter.
880 # assert "jAVASCRIPT".capitalized == "Javascript"
881 # assert "i am root".capitalized == "I Am Root"
882 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
883 fun capitalized
: SELFTYPE do
884 if length
== 0 then return self
886 var buf
= new FlatBuffer.with_capacity
(length
)
888 var curr
= chars
[0].to_upper
892 for i
in [1 .. length
[ do
895 if prev
.is_letter
then
896 buf
[i
] = curr
.to_lower
898 buf
[i
] = curr
.to_upper
906 private class FlatSubstringsIter
907 super Iterator[FlatText]
909 var tgt
: nullable FlatText
913 return tgt
.as(not null)
916 redef fun is_ok
do return tgt
!= null
918 redef fun next
do tgt
= null
921 # Immutable strings of characters.
926 # Index in _items of the start of the string
927 private var index_from
: Int is noinit
929 # Indes in _items of the last item of the string
930 private var index_to
: Int is noinit
932 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
936 # Check that the index (+ index_from) is not larger than indexTo
937 # In other terms, if the index is valid
939 assert (index
+ index_from
) <= index_to
940 return items
[index
+ index_from
]
943 ################################################
944 # AbstractString specific methods #
945 ################################################
949 var native
= calloc_string
(self.length
+ 1)
950 var length
= self.length
951 var items
= self.items
954 while pos
< length
do
955 native
[pos
] = items
[ipos
]
959 return native
.to_s_with_length
(self.length
)
962 redef fun substring
(from
, count
)
968 if count
< 0 then count
= 0
972 var realFrom
= index_from
+ from
974 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
976 if count
== 0 then return empty
978 var to
= realFrom
+ count
- 1
980 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
983 redef fun empty
do return "".as(FlatString)
987 var outstr
= calloc_string
(self.length
+ 1)
990 var myitems
= self.items
991 var index_from
= self.index_from
992 var max
= self.index_to
994 while index_from
<= max
do
995 outstr
[out_index
] = myitems
[index_from
].to_upper
1000 outstr
[self.length
] = '\0'
1002 return outstr
.to_s_with_length
(self.length
)
1007 var outstr
= calloc_string
(self.length
+ 1)
1010 var myitems
= self.items
1011 var index_from
= self.index_from
1012 var max
= self.index_to
1014 while index_from
<= max
do
1015 outstr
[out_index
] = myitems
[index_from
].to_lower
1020 outstr
[self.length
] = '\0'
1022 return outstr
.to_s_with_length
(self.length
)
1027 var i
= self.index_from
1028 var imax
= self.index_to
1035 ##################################################
1036 # String Specific Methods #
1037 ##################################################
1039 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
1047 redef fun to_cstring
: NativeString
1049 if real_items
!= null then
1050 return real_items
.as(not null)
1052 var newItems
= calloc_string
(length
+ 1)
1053 self.items
.copy_to
(newItems
, length
, index_from
, 0)
1054 newItems
[length
] = '\0'
1055 self.real_items
= newItems
1062 if not other
isa FlatString then return super
1064 if self.object_id
== other
.object_id
then return true
1066 var my_length
= length
1068 if other
.length
!= my_length
then return false
1070 var my_index
= index_from
1071 var its_index
= other
.index_from
1073 var last_iteration
= my_index
+ my_length
1075 var itsitems
= other
.items
1076 var myitems
= self.items
1078 while my_index
< last_iteration
do
1079 if myitems
[my_index
] != itsitems
[its_index
] then return false
1089 if not other
isa FlatString then return super
1091 if self.object_id
== other
.object_id
then return false
1093 var my_curr_char
: Char
1094 var its_curr_char
: Char
1096 var curr_id_self
= self.index_from
1097 var curr_id_other
= other
.index_from
1099 var my_items
= self.items
1100 var its_items
= other
.items
1102 var my_length
= self.length
1103 var its_length
= other
.length
1105 var max_iterations
= curr_id_self
+ my_length
1107 while curr_id_self
< max_iterations
do
1108 my_curr_char
= my_items
[curr_id_self
]
1109 its_curr_char
= its_items
[curr_id_other
]
1111 if my_curr_char
!= its_curr_char
then
1112 if my_curr_char
< its_curr_char
then return true
1120 return my_length
< its_length
1125 var my_length
= self.length
1126 var its_length
= s
.length
1128 var total_length
= my_length
+ its_length
1130 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
1132 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
1133 if s
isa FlatString then
1134 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
1135 else if s
isa FlatBuffer then
1136 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
1138 var curr_pos
= my_length
1139 for i
in [0..s
.length
[ do
1141 target_string
[curr_pos
] = c
1146 target_string
[total_length
] = '\0'
1148 return target_string
.to_s_with_length
(total_length
)
1155 var my_length
= self.length
1157 var final_length
= my_length
* i
1159 var my_items
= self.items
1161 var target_string
= calloc_string
((final_length
) + 1)
1163 target_string
[final_length
] = '\0'
1165 var current_last
= 0
1167 for iteration
in [1 .. i
] do
1168 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
1169 current_last
+= my_length
1172 return target_string
.to_s_with_length
(final_length
)
1177 if hash_cache
== null then
1178 # djb2 hash algorithm
1184 while i
<= index_to
do
1185 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
1192 return hash_cache
.as(not null)
1195 redef fun substrings
do return new FlatSubstringsIter(self)
1198 private class FlatStringReverseIterator
1199 super IndexedIterator[Char]
1201 var target
: FlatString
1203 var target_items
: NativeString
1207 init with_pos
(tgt
: FlatString, pos
: Int)
1210 target_items
= tgt
.items
1211 curr_pos
= pos
+ tgt
.index_from
1214 redef fun is_ok
do return curr_pos
>= target
.index_from
1216 redef fun item
do return target_items
[curr_pos
]
1218 redef fun next
do curr_pos
-= 1
1220 redef fun index
do return curr_pos
- target
.index_from
1224 private class FlatStringIterator
1225 super IndexedIterator[Char]
1227 var target
: FlatString
1229 var target_items
: NativeString
1233 init with_pos
(tgt
: FlatString, pos
: Int)
1236 target_items
= tgt
.items
1237 curr_pos
= pos
+ target
.index_from
1240 redef fun is_ok
do return curr_pos
<= target
.index_to
1242 redef fun item
do return target_items
[curr_pos
]
1244 redef fun next
do curr_pos
+= 1
1246 redef fun index
do return curr_pos
- target
.index_from
1250 private class FlatStringCharView
1251 super StringCharView
1253 redef type SELFTYPE: FlatString
1257 # Check that the index (+ index_from) is not larger than indexTo
1258 # In other terms, if the index is valid
1260 var target
= self.target
1261 assert (index
+ target
.index_from
) <= target
.index_to
1262 return target
.items
[index
+ target
.index_from
]
1265 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
1267 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
1271 abstract class Buffer
1274 redef type SELFTYPE: Buffer
1276 # Specific implementations MUST set this to `true` in order to invalidate caches
1277 protected var is_dirty
= true
1279 # Copy-On-Write flag
1281 # If the `Buffer` was to_s'd, the next in-place altering
1282 # operation will cause the current `Buffer` to be re-allocated.
1284 # The flag will then be set at `false`.
1285 protected var written
= false
1287 # Modifies the char contained at pos `index`
1289 # DEPRECATED : Use self.chars.[]= instead
1290 fun []=(index
: Int, item
: Char) is abstract
1292 # Adds a char `c` at the end of self
1294 # DEPRECATED : Use self.chars.add instead
1295 fun add
(c
: Char) is abstract
1299 # var b = new FlatBuffer
1301 # assert not b.is_empty
1304 fun clear
is abstract
1306 # Enlarges the subsequent array containing the chars of self
1307 fun enlarge
(cap
: Int) is abstract
1309 # Adds the content of text `s` at the end of self
1311 # var b = new FlatBuffer
1314 # assert b == "helloworld"
1315 fun append
(s
: Text) is abstract
1317 # `self` is appended in such a way that `self` is repeated `r` times
1319 # var b = new FlatBuffer
1322 # assert b == "hellohellohello"
1323 fun times
(r
: Int) is abstract
1325 # Reverses itself in-place
1327 # var b = new FlatBuffer
1330 # assert b == "olleh"
1331 fun reverse
is abstract
1333 # Changes each lower-case char in `self` by its upper-case variant
1335 # var b = new FlatBuffer
1336 # b.append("Hello World!")
1338 # assert b == "HELLO WORLD!"
1339 fun upper
is abstract
1341 # Changes each upper-case char in `self` by its lower-case variant
1343 # var b = new FlatBuffer
1344 # b.append("Hello World!")
1346 # assert b == "hello world!"
1347 fun lower
is abstract
1349 # Capitalizes each word in `self`
1351 # Letters that follow a letter are lowercased
1352 # Letters that follow a non-letter are upcased.
1354 # SEE: `Char::is_letter` for the definition of a letter.
1356 # var b = new FlatBuffer.from("jAVAsCriPt")"
1358 # assert b == "Javascript"
1359 # b = new FlatBuffer.from("i am root")
1361 # assert b == "I Am Root"
1362 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1364 # assert b == "Ab_C -Ab0C Ab\nC"
1366 if length
== 0 then return
1367 var c
= self[0].to_upper
1370 for i
in [1 .. length
[ do
1373 if prev
.is_letter
then
1374 self[i
] = c
.to_lower
1376 self[i
] = c
.to_upper
1383 if is_dirty
then hash_cache
= null
1387 # In Buffers, the internal sequence of character is mutable
1388 # Thus, `chars` can be used to modify the buffer.
1389 redef fun chars
: Sequence[Char] is abstract
1392 # Mutable strings of characters.
1397 redef type SELFTYPE: FlatBuffer
1399 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1401 private var capacity
: Int = 0
1403 redef fun substrings
do return new FlatSubstringsIter(self)
1405 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1407 # This happens when an operation modifies the current `Buffer` and
1408 # the Copy-On-Write flag `written` is set at true.
1409 private fun reset
do
1410 var nns
= new NativeString(capacity
)
1411 items
.copy_to
(nns
, length
, 0, 0)
1419 assert index
< length
1423 redef fun []=(index
, item
)
1426 if index
== length
then
1430 if written
then reset
1431 assert index
>= 0 and index
< length
1438 if capacity
<= length
then enlarge
(length
+ 5)
1445 if written
then reset
1449 redef fun empty
do return new FlatBuffer
1451 redef fun enlarge
(cap
)
1454 if cap
<= c
then return
1455 while c
<= cap
do c
= c
* 2 + 2
1456 # The COW flag can be set at false here, since
1457 # it does a copy of the current `Buffer`
1459 var a
= calloc_string
(c
+1)
1460 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1465 redef fun to_s
: String
1468 if length
== 0 then items
= new NativeString(1)
1469 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1472 redef fun to_cstring
1475 var new_native
= calloc_string
(length
+ 1)
1476 new_native
[length
] = '\0'
1477 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1478 real_items
= new_native
1481 return real_items
.as(not null)
1484 # Create a new empty string.
1489 capacity
= s
.length
+ 1
1491 items
= calloc_string
(capacity
)
1492 if s
isa FlatString then
1493 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1494 else if s
isa FlatBuffer then
1495 s
.items
.copy_to
(items
, length
, 0, 0)
1498 for i
in [0..s
.length
[ do
1506 # Create a new empty string with a given capacity.
1507 init with_capacity
(cap
: Int)
1510 # _items = new NativeString.calloc(cap)
1511 items
= calloc_string
(cap
+1)
1518 if s
.is_empty
then return
1521 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1522 if s
isa FlatString then
1523 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1524 else if s
isa FlatBuffer then
1525 s
.items
.copy_to
(items
, sl
, 0, length
)
1527 var curr_pos
= self.length
1528 for i
in [0..s
.length
[ do
1537 # Copies the content of self in `dest`
1538 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1540 var self_chars
= self.chars
1541 var dest_chars
= dest
.chars
1542 for i
in [0..len-1
] do
1543 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1547 redef fun substring
(from
, count
)
1551 if from
< 0 then from
= 0
1552 if count
> length
then count
= length
1553 if from
< count
then
1554 var r
= new FlatBuffer.with_capacity
(count
- from
)
1555 while from
< count
do
1556 r
.chars
.push
(items
[from
])
1561 return new FlatBuffer
1568 var ns
= calloc_string
(capacity
)
1580 redef fun times
(repeats
)
1582 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1583 for i
in [1..repeats
[ do
1590 if written
then reset
1594 it
[id
] = it
[id
].to_upper
1601 if written
then reset
1605 it
[id
] = it
[id
].to_lower
1611 private class FlatBufferReverseIterator
1612 super IndexedIterator[Char]
1614 var target
: FlatBuffer
1616 var target_items
: NativeString
1620 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1623 if tgt
.length
> 0 then target_items
= tgt
.items
1627 redef fun index
do return curr_pos
1629 redef fun is_ok
do return curr_pos
>= 0
1631 redef fun item
do return target_items
[curr_pos
]
1633 redef fun next
do curr_pos
-= 1
1637 private class FlatBufferCharView
1638 super BufferCharView
1641 redef type SELFTYPE: FlatBuffer
1643 redef fun [](index
) do return target
.items
[index
]
1645 redef fun []=(index
, item
)
1647 assert index
>= 0 and index
<= length
1648 if index
== length
then
1652 target
.items
[index
] = item
1665 fun enlarge
(cap
: Int)
1672 var my_items
= target
.items
1673 var s_length
= s
.length
1674 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1677 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1679 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1683 private class FlatBufferIterator
1684 super IndexedIterator[Char]
1686 var target
: FlatBuffer
1688 var target_items
: NativeString
1692 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1695 if tgt
.length
> 0 then target_items
= tgt
.items
1699 redef fun index
do return curr_pos
1701 redef fun is_ok
do return curr_pos
< target
.length
1703 redef fun item
do return target_items
[curr_pos
]
1705 redef fun next
do curr_pos
+= 1
1709 ###############################################################################
1711 ###############################################################################
1714 # User readable representation of `self`.
1715 fun to_s
: String do return inspect
1717 # The class name of the object in NativeString format.
1718 private fun native_class_name
: NativeString is intern
1720 # The class name of the object.
1722 # assert 5.class_name == "Int"
1723 fun class_name
: String do return native_class_name
.to_s
1725 # Developer readable representation of `self`.
1726 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1729 return "<{inspect_head}>"
1732 # Return "CLASSNAME:#OBJECTID".
1733 # This function is mainly used with the redefinition of the inspect method
1734 protected fun inspect_head
: String
1736 return "{class_name}:#{object_id.to_hex}"
1741 # assert true.to_s == "true"
1742 # assert false.to_s == "false"
1755 # Wrapper of strerror C function
1756 private fun strerror_ext
: NativeString is extern `{
1757 return strerror(recv);
1760 # Returns a string describing error number
1761 fun strerror
: String do return strerror_ext
.to_s
1763 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1764 # assume < to_c max const of char
1765 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1772 else if self == 0 then
1779 var pos
= digit_count
(base
) - 1
1780 while pos
>= 0 and n
> 0 do
1781 s
.chars
[pos
] = (n
% base
).to_c
1787 # C function to convert an nit Int to a NativeString (char*)
1788 private fun native_int_to_s
: NativeString is extern "native_int_to_s"
1790 # return displayable int in base 10 and signed
1792 # assert 1.to_s == "1"
1793 # assert (-123).to_s == "-123"
1795 return native_int_to_s
.to_s
1798 # return displayable int in hexadecimal
1800 # assert 1.to_hex == "1"
1801 # assert (-255).to_hex == "-ff"
1802 fun to_hex
: String do return to_base
(16,false)
1804 # return displayable int in base base and signed
1805 fun to_base
(base
: Int, signed
: Bool): String
1807 var l
= digit_count
(base
)
1808 var s
= new FlatBuffer.from
(" " * l
)
1809 fill_buffer
(s
, base
, signed
)
1815 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1817 # assert 12.34.to_s == "12.34"
1818 # assert (-0120.030).to_s == "-120.03"
1820 # see `to_precision` for a custom precision.
1822 var str
= to_precision
( 3 )
1823 if is_inf
!= 0 or is_nan
then return str
1824 var len
= str
.length
1825 for i
in [0..len-1
] do
1827 var c
= str
.chars
[j
]
1830 else if c
== '.' then
1831 return str
.substring
( 0, j
+2 )
1833 return str
.substring
( 0, j
+1 )
1839 # `String` representation of `self` with the given number of `decimals`
1841 # assert 12.345.to_precision(0) == "12"
1842 # assert 12.345.to_precision(3) == "12.345"
1843 # assert (-12.345).to_precision(3) == "-12.345"
1844 # assert (-0.123).to_precision(3) == "-0.123"
1845 # assert 0.999.to_precision(2) == "1.00"
1846 # assert 0.999.to_precision(4) == "0.9990"
1847 fun to_precision
(decimals
: Int): String
1849 if is_nan
then return "nan"
1851 var isinf
= self.is_inf
1854 else if isinf
== -1 then
1858 if decimals
== 0 then return self.to_i
.to_s
1860 for i
in [0..decimals
[ do f
= f
* 10.0
1867 if i
== 0 then return "0." + "0"*decimals
1869 # Prepare both parts of the float, before and after the "."
1874 if sl
> decimals
then
1875 # Has something before the "."
1876 p1
= s
.substring
(0, sl-decimals
)
1877 p2
= s
.substring
(sl-decimals
, decimals
)
1880 p2
= "0"*(decimals-sl
) + s
1883 if i
< 0 then p1
= "-" + p1
1885 return p1
+ "." + p2
1888 # `self` representation with `nb` digits after the '.'.
1890 # assert 12.345.to_precision_native(1) == "12.3"
1891 # assert 12.345.to_precision_native(2) == "12.35"
1892 # assert 12.345.to_precision_native(3) == "12.345"
1893 # assert 12.345.to_precision_native(4) == "12.3450"
1894 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1898 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1899 str = malloc(size + 1);
1900 sprintf(str, "%.*f", (int)nb, recv );
1902 return NativeString_to_s( str );
1907 # assert 'x'.to_s == "x"
1910 var s
= new FlatBuffer.with_capacity
(1)
1915 # Returns true if the char is a numerical digit
1917 # assert '0'.is_numeric
1918 # assert '9'.is_numeric
1919 # assert not 'a'.is_numeric
1920 # assert not '?'.is_numeric
1921 fun is_numeric
: Bool
1923 return self >= '0' and self <= '9'
1926 # Returns true if the char is an alpha digit
1928 # assert 'a'.is_alpha
1929 # assert 'Z'.is_alpha
1930 # assert not '0'.is_alpha
1931 # assert not '?'.is_alpha
1934 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1937 # Returns true if the char is an alpha or a numeric digit
1939 # assert 'a'.is_alphanumeric
1940 # assert 'Z'.is_alphanumeric
1941 # assert '0'.is_alphanumeric
1942 # assert '9'.is_alphanumeric
1943 # assert not '?'.is_alphanumeric
1944 fun is_alphanumeric
: Bool
1946 return self.is_numeric
or self.is_alpha
1950 redef class Collection[E
]
1951 # Concatenate elements.
1954 var s
= new FlatBuffer
1955 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1959 # Concatenate and separate each elements with `sep`.
1961 # assert [1, 2, 3].join(":") == "1:2:3"
1962 # assert [1..3].join(":") == "1:2:3"
1963 fun join
(sep
: Text): String
1965 if is_empty
then return ""
1967 var s
= new FlatBuffer # Result
1972 if e
!= null then s
.append
(e
.to_s
)
1974 # Concat other items
1979 if e
!= null then s
.append
(e
.to_s
)
1986 redef class Array[E
]
1988 # Fast implementation
1992 if l
== 0 then return ""
1993 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
1995 var na
= new NativeArray[String](l
)
2001 if itsi
== null then
2011 var ns
= new NativeString(sl
+ 1)
2017 var tpl
= tmp
.length
2018 if tmp
isa FlatString then
2019 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2022 for j
in tmp
.substrings
do
2023 var s
= j
.as(FlatString)
2025 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2031 return ns
.to_s_with_length
(sl
)
2035 redef class Map[K
,V
]
2036 # Concatenate couple of 'key value'.
2037 # key and value are separated by `couple_sep`.
2038 # each couple is separated each couple with `sep`.
2040 # var m = new ArrayMap[Int, String]
2043 # assert m.join("; ", "=") == "1=one; 10=ten"
2044 fun join
(sep
: String, couple_sep
: String): String
2046 if is_empty
then return ""
2048 var s
= new FlatBuffer # Result
2054 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2056 # Concat other items
2062 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2069 ###############################################################################
2071 ###############################################################################
2073 # Native strings are simple C char *
2074 extern class NativeString `{ char* `}
2076 # Creates a new NativeString with a capacity of `length
`
2077 new(length: Int) is intern
2078 fun [](index: Int): Char is intern
2079 fun []=(index: Int, item: Char) is intern
2080 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2082 # Position of the first nul character.
2083 fun cstring_length: Int
2086 while self[l] != '\0' do l += 1
2089 fun atoi: Int is intern
2090 fun atof: Float is extern "atof"
2094 return to_s_with_length(cstring_length)
2097 fun to_s_with_length(length: Int): FlatString
2100 var str = new FlatString.with_infos(self, length, 0, length - 1)
2101 str.real_items = self
2105 fun to_s_with_copy: FlatString
2107 var length = cstring_length
2108 var new_self = calloc_string(length + 1)
2109 copy_to(new_self, length, 0, 0)
2110 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2111 str.real_items = self
2116 # StringCapable objects can create native strings
2117 interface StringCapable
2118 protected fun calloc_string(size: Int): NativeString is intern
2122 private var args_cache: nullable Sequence[String]
2124 # The arguments of the program as given by the OS
2125 fun program_args: Sequence[String]
2127 if _args_cache == null then init_args
2128 return _args_cache.as(not null)
2131 # The name of the program as given by the OS
2132 fun program_name: String
2134 return native_argv(0).to_s
2137 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2138 private fun init_args
2140 var argc = native_argc
2141 var args = new Array[String].with_capacity(0)
2144 args[i-1] = native_argv(i).to_s
2150 # First argument of the main C function.
2151 private fun native_argc: Int is intern
2153 # Second argument of the main C function.
2154 private fun native_argv(i: Int): NativeString is intern
2157 # Comparator that efficienlty use `to_s
` to compare things
2159 # The comparaison call `to_s
` on object and use the result to order things.
2161 # var a = [1, 2, 3, 10, 20]
2162 # (new CachedAlphaComparator).sort(a)
2163 # assert a == [1, 10, 2, 20, 3]
2165 # Internally the result of `to_s
` is cached in a HashMap to counter
2166 # uneficient implementation of `to_s
`.
2168 # Note: it caching is not usefull, see `alpha_comparator
`
2169 class CachedAlphaComparator
2171 redef type COMPARED: Object
2173 private var cache = new HashMap[Object, String]
2175 private fun do_to_s(a: Object): String do
2176 if cache.has_key(a) then return cache[a]
2182 redef fun compare(a, b) do
2183 return do_to_s(a) <=> do_to_s(b)
2187 # see `alpha_comparator
`
2188 private class AlphaComparator
2190 redef fun compare(a, b) do return a.to_s <=> b.to_s
2193 # Stateless comparator that naively use `to_s
` to compare things.
2195 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2196 # on a single instace. See `CachedAlphaComparator` as an alternative.
2198 # var a = [1, 2, 3, 10, 20]
2199 # alpha_comparator.sort(a)
2200 # assert a == [1, 10, 2, 20, 3]
2201 fun alpha_comparator: Comparator do return once new AlphaComparator
2203 # The arguments of the program as given by the OS
2204 fun args: Sequence[String]
2206 return sys.program_args