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
34 redef type OTHER: Text
36 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
39 # Gets a view on the chars of the Text object
41 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
42 fun chars
: SequenceRead[Char] is abstract
44 # Number of characters contained in self.
46 # assert "12345".length == 5
47 # assert "".length == 0
48 fun length
: Int is abstract
52 # assert "abcd".substring(1, 2) == "bc"
53 # assert "abcd".substring(-1, 2) == "a"
54 # assert "abcd".substring(1, 0) == ""
55 # assert "abcd".substring(2, 5) == "cd"
57 # A `from` index < 0 will be replaced by 0.
58 # Unless a `count` value is > 0 at the same time.
59 # In this case, `from += count` and `count -= from`.
60 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
62 # Iterates on the substrings of self if any
63 fun substrings
: Iterator[Text] is abstract
65 # Is the current Text empty (== "")
68 # assert not "foo".is_empty
69 fun is_empty
: Bool do return self.length
== 0
71 # Returns an empty Text of the right type
73 # This method is used internally to get the right
74 # implementation of an empty string.
75 protected fun empty
: SELFTYPE is abstract
77 # Gets the first char of the Text
79 # DEPRECATED : Use self.chars.first instead
80 fun first
: Char do return self.chars
[0]
82 # Access a character at `index` in the string.
84 # assert "abcd"[2] == 'c'
86 # DEPRECATED : Use self.chars.[] instead
87 fun [](index
: Int): Char do return self.chars
[index
]
89 # Gets the index of the first occurence of 'c'
91 # Returns -1 if not found
93 # DEPRECATED : Use self.chars.index_of instead
94 fun index_of
(c
: Char): Int
96 return index_of_from
(c
, 0)
99 # Gets the last char of self
101 # DEPRECATED : Use self.chars.last instead
102 fun last
: Char do return self.chars
[length-1
]
104 # Gets the index of the first occurence of ´c´ starting from ´pos´
106 # Returns -1 if not found
108 # DEPRECATED : Use self.chars.index_of_from instead
109 fun index_of_from
(c
: Char, pos
: Int): Int
111 var iter
= self.chars
.iterator_from
(pos
)
113 if iter
.item
== c
then return iter
.index
119 # Gets the last index of char ´c´
121 # Returns -1 if not found
123 # DEPRECATED : Use self.chars.last_index_of instead
124 fun last_index_of
(c
: Char): Int
126 return last_index_of_from
(c
, length
- 1)
129 # Return a null terminated char *
130 fun to_cstring
: NativeString do return flatten
.to_cstring
132 # The index of the last occurrence of an element starting from pos (in reverse order).
134 # var s = "/etc/bin/test/test.nit"
135 # assert s.last_index_of_from('/', s.length-1) == 13
136 # assert s.last_index_of_from('/', 12) == 8
138 # Returns -1 if not found
140 # DEPRECATED : Use self.chars.last_index_of_from instead
141 fun last_index_of_from
(item
: Char, pos
: Int): Int
143 var iter
= self.chars
.reverse_iterator_from
(pos
)
145 if iter
.item
== item
then return iter
.index
151 # Gets an iterator on the chars of self
153 # DEPRECATED : Use self.chars.iterator instead
154 fun iterator
: Iterator[Char]
156 return self.chars
.iterator
160 # Gets an Array containing the chars of self
162 # DEPRECATED : Use self.chars.to_a instead
163 fun to_a
: Array[Char] do return chars
.to_a
165 # Create a substring from `self` beginning at the `from` position
167 # assert "abcd".substring_from(1) == "bcd"
168 # assert "abcd".substring_from(-1) == "abcd"
169 # assert "abcd".substring_from(2) == "cd"
171 # As with substring, a `from` index < 0 will be replaced by 0
172 fun substring_from
(from
: Int): SELFTYPE
174 if from
>= self.length
then return empty
175 if from
< 0 then from
= 0
176 return substring
(from
, length
- from
)
179 # Does self have a substring `str` starting from position `pos`?
181 # assert "abcd".has_substring("bc",1) == true
182 # assert "abcd".has_substring("bc",2) == false
184 # Returns true iff all characters of `str` are presents
185 # at the expected index in `self.`
186 # The first character of `str` being at `pos`, the second
187 # character being at `pos+1` and so on...
189 # This means that all characters of `str` need to be inside `self`.
191 # assert "abcd".has_substring("xab", -1) == false
192 # assert "abcd".has_substring("cdx", 2) == false
194 # And that the empty string is always a valid substring.
196 # assert "abcd".has_substring("", 2) == true
197 # assert "abcd".has_substring("", 200) == true
198 fun has_substring
(str
: String, pos
: Int): Bool
200 if str
.is_empty
then return true
201 if pos
< 0 or pos
+ str
.length
> length
then return false
202 var myiter
= self.chars
.iterator_from
(pos
)
203 var itsiter
= str
.chars
.iterator
204 while myiter
.is_ok
and itsiter
.is_ok
do
205 if myiter
.item
!= itsiter
.item
then return false
209 if itsiter
.is_ok
then return false
213 # Is this string prefixed by `prefix`?
215 # assert "abcd".has_prefix("ab") == true
216 # assert "abcbc".has_prefix("bc") == false
217 # assert "ab".has_prefix("abcd") == false
218 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
220 # Is this string suffixed by `suffix`?
222 # assert "abcd".has_suffix("abc") == false
223 # assert "abcd".has_suffix("bcd") == true
224 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
226 # If `self` contains only digits, return the corresponding integer
228 # assert "123".to_i == 123
229 # assert "-1".to_i == -1
233 return to_s
.to_cstring
.atoi
236 # If `self` contains a float, return the corresponding float
238 # assert "123".to_f == 123.0
239 # assert "-1".to_f == -1.0
240 # assert "-1.2e-3".to_f == -0.0012
244 return to_s
.to_cstring
.atof
247 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
249 # assert "ff".to_hex == 255
250 fun to_hex
: Int do return a_to
(16)
252 # If `self` contains only digits and letters, return the corresponding integer in a given base
254 # assert "120".a_to(3) == 15
255 fun a_to
(base
: Int) : Int
260 for j
in [0..length
[ do
282 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
284 # assert "123".is_numeric == true
285 # assert "1.2".is_numeric == true
286 # assert "1,2".is_numeric == true
287 # assert "1..2".is_numeric == false
290 var has_point_or_comma
= false
291 for i
in [0..length
[ do
293 if not c
.is_numeric
then
294 if (c
== '.' or c
== ',') and not has_point_or_comma
then
295 has_point_or_comma
= true
304 # Returns `true` if the string contains only Hex chars
306 # assert "048bf".is_hex == true
307 # assert "ABCDEF".is_hex == true
308 # assert "0G".is_hex == false
311 for i
in [0..length
[ do
313 if not (c
>= 'a' and c
<= 'f') and
314 not (c
>= 'A' and c
<= 'F') and
315 not (c
>= '0' and c
<= '9') then return false
320 # Are all letters in `self` upper-case ?
322 # assert "HELLO WORLD".is_upper == true
323 # assert "%$&%!".is_upper == true
324 # assert "hello world".is_upper == false
325 # assert "Hello World".is_upper == false
328 for i
in [0..length
[ do
330 if char
.is_lower
then return false
335 # Are all letters in `self` lower-case ?
337 # assert "hello world".is_lower == true
338 # assert "%$&%!".is_lower == true
339 # assert "Hello World".is_lower == false
342 for i
in [0..length
[ do
344 if char
.is_upper
then return false
349 # Removes the whitespaces at the beginning of self
351 # assert " \n\thello \n\t".l_trim == "hello \n\t"
353 # A whitespace is defined as any character which ascii value is less than or equal to 32
356 var iter
= self.chars
.iterator
358 if iter
.item
.ascii
> 32 then break
361 if iter
.index
== length
then return self.empty
362 return self.substring_from
(iter
.index
)
365 # Removes the whitespaces at the end of self
367 # assert " \n\thello \n\t".r_trim == " \n\thello"
369 # A whitespace is defined as any character which ascii value is less than or equal to 32
372 var iter
= self.chars
.reverse_iterator
374 if iter
.item
.ascii
> 32 then break
377 if iter
.index
< 0 then return self.empty
378 return self.substring
(0, iter
.index
+ 1)
381 # Trims trailing and preceding white spaces
382 # A whitespace is defined as any character which ascii value is less than or equal to 32
384 # assert " Hello World ! ".trim == "Hello World !"
385 # assert "\na\nb\tc\t".trim == "a\nb\tc"
386 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
388 # Justify a self in a space of `length`
390 # `left` is the space ratio on the left side.
391 # * 0.0 for left-justified (no space at the left)
392 # * 1.0 for right-justified (all spaces at the left)
393 # * 0.5 for centered (half the spaces at the left)
395 # assert "hello".justify(10, 0.0) == "hello "
396 # assert "hello".justify(10, 1.0) == " hello"
397 # assert "hello".justify(10, 0.5) == " hello "
399 # If `length` is not enough, `self` is returned as is.
401 # assert "hello".justify(2, 0.0) == "hello"
403 # REQUIRE: left >= 0.0 and left <= 1.0
404 # ENSURE: `self.length <= length implies result.length == length`
405 # ENSURE: `self.length >= length implies result == self
406 fun justify
(length
: Int, left
: Float): SELFTYPE
408 var diff
= length
- self.length
409 if diff
<= 0 then return self
410 assert left
>= 0.0 and left
<= 1.0
411 var before
= (diff
.to_f
* left
).to_i
412 return " " * before
+ self + " " * (diff-before
)
415 # Mangle a string to be a unique string only made of alphanumeric characters
416 fun to_cmangle
: String
418 var res
= new FlatBuffer
419 var underscore
= false
420 for i
in [0..length
[ do
422 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
428 res
.append
('_'.ascii
.to_s
)
431 if c
>= '0' and c
<= '9' then
434 else if c
== '_' then
439 res
.append
(c
.ascii
.to_s
)
447 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
449 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
450 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
451 fun escape_to_c
: String
453 var b
= new FlatBuffer
454 for i
in [0..length
[ do
458 else if c
== '\0' then
460 else if c
== '"' then
462 else if c == '\'' then
464 else if c == '\\
' then
466 else if c.ascii < 32 then
467 b.append("\\{c.ascii.to_base(8, false)}")
475 # Escape additionnal characters
476 # The result might no be legal in C but be used in other languages
478 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
479 fun escape_more_to_c(chars: String): String
481 var b = new FlatBuffer
482 for c in escape_to_c.chars do
483 if chars.chars.has(c) then
491 # Escape to C plus braces
493 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
494 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
496 # Escape to POSIX Shell (sh).
498 # Abort if the text contains a null byte.
500 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
501 fun escape_to_sh
: String do
502 var b
= new FlatBuffer
504 for i in [0..length[ do
509 assert without_null_byte
: c
!= '\0'
517 # Escape to include in a Makefile
519 # Unfortunately, some characters are not escapable in Makefile.
520 # These characters are `;`, `|`, `\`, and the non-printable ones.
521 # They will be rendered as `"?{hex}"`.
522 fun escape_to_mk: String do
523 var b = new FlatBuffer
524 for i in [0..length[ do
528 else if c == ':' or c == ' ' or c == '#' then
531 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
532 b
.append
("?{c.ascii.to_base(16, false)}")
540 # Return a string where Nit escape sequences are transformed.
543 # assert s.length == 2
544 # var u = s.unescape_nit
545 # assert u.length == 1
546 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
547 fun unescape_nit
: String
549 var res
= new FlatBuffer.with_capacity
(self.length
)
550 var was_slash
= false
551 for i
in [0..length
[ do
553 if not was_slash
then
564 else if c
== 'r' then
566 else if c
== 't' then
568 else if c
== '0' then
577 # Encode `self` to percent (or URL) encoding
579 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
580 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
581 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
582 fun to_percent_encoding
: String
584 var buf
= new FlatBuffer
586 for i
in [0..length
[ do
588 if (c
>= '0' and c
<= '9') or
589 (c
>= 'a' and c
<= 'z') or
590 (c
>= 'A' and c
<= 'Z') or
591 c
== '-' or c
== '.' or
595 else buf
.append
"%{c.ascii.to_hex}"
601 # Decode `self` from percent (or URL) encoding to a clear string
603 # Replace invalid use of '%' with '?'.
605 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
606 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
607 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
608 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
609 # assert "incomplete %".from_percent_encoding == "incomplete ?"
610 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
611 fun from_percent_encoding
: String
613 var buf
= new FlatBuffer
619 if i
+ 2 >= length
then
620 # What follows % has been cut off
624 var hex_s
= substring
(i
, 2)
626 var hex_i
= hex_s
.to_hex
630 # What follows a % is not Hex
643 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
645 # assert "a&b->\"x\"".html_escape == "a&b->"x""
646 fun html_escape
: SELFTYPE
648 var buf
= new FlatBuffer
650 for i
in [0..length
[ do
654 else if c
== '<' then
656 else if c
== '>' then
658 else if c
== '"' then
667 # Two pieces of text are equals if thez have the same characters in the same order.
669 # assert "hello" == "hello"
670 # assert "hello" != "HELLO"
671 # assert "hello" == "hel"+"lo"
673 # Things that are not Text are not equal.
676 # assert "9" != ['9']
679 # assert "9".chars.first == '9' # equality of Char
680 # assert "9".chars == ['9'] # equality of Sequence
681 # assert "9".to_i == 9 # equality of Int
684 if o
== null then return false
685 if not o
isa Text then return false
686 if self.is_same_instance
(o
) then return true
687 if self.length
!= o
.length
then return false
688 return self.chars
== o
.chars
691 # Lexicographical comparaison
693 # assert "abc" < "xy"
694 # assert "ABC" < "abc"
697 var self_chars
= self.chars
.iterator
698 var other_chars
= other
.chars
.iterator
700 while self_chars
.is_ok
and other_chars
.is_ok
do
701 if self_chars
.item
< other_chars
.item
then return true
702 if self_chars
.item
> other_chars
.item
then return false
707 if self_chars
.is_ok
then
714 # Escape string used in labels for graphviz
716 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
717 fun escape_to_dot
: String
719 return escape_more_to_c
("|\{\}<>")
722 # Flat representation of self
723 fun flatten
: FlatText is abstract
725 private var hash_cache
: nullable Int = null
729 if hash_cache
== null then
730 # djb2 hash algorithm
733 for i
in [0..length
[ do
735 h
= h
.lshift
(5) + h
+ char
.ascii
740 return hash_cache
.as(not null)
745 # All kinds of array-based text representations.
746 abstract class FlatText
749 # Underlying C-String (`char*`)
751 # Warning : Might be void in some subclasses, be sure to check
752 # if set before using it.
753 private var items
: NativeString is noinit
755 # Real items, used as cache for to_cstring is called
756 private var real_items
: nullable NativeString = null
758 redef var length
: Int = 0
771 redef fun flatten
do return self
774 # Abstract class for the SequenceRead compatible
775 # views on String and Buffer objects
776 private abstract class StringCharView
777 super SequenceRead[Char]
781 private var target
: SELFTYPE
783 redef fun is_empty
do return target
.is_empty
785 redef fun length
do return target
.length
787 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
789 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
792 # View on Buffer objects, extends Sequence
793 # for mutation operations
794 private abstract class BufferCharView
798 redef type SELFTYPE: Buffer
802 abstract class String
805 redef type SELFTYPE: String
807 redef fun to_s
do return self
809 # Concatenates `o` to `self`
811 # assert "hello" + "world" == "helloworld"
812 # assert "" + "hello" + "" == "hello"
813 fun +(o
: Text): SELFTYPE is abstract
815 # Concatenates self `i` times
817 # assert "abc" * 4 == "abcabcabcabc"
818 # assert "abc" * 1 == "abc"
819 # assert "abc" * 0 == ""
820 fun *(i
: Int): SELFTYPE is abstract
822 fun insert_at
(s
: String, pos
: Int): SELFTYPE is abstract
824 redef fun substrings
: Iterator[String] is abstract
826 # Returns a reversed version of self
828 # assert "hello".reversed == "olleh"
829 # assert "bob".reversed == "bob"
830 # assert "".reversed == ""
831 fun reversed
: SELFTYPE is abstract
833 # A upper case version of `self`
835 # assert "Hello World!".to_upper == "HELLO WORLD!"
836 fun to_upper
: SELFTYPE is abstract
838 # A lower case version of `self`
840 # assert "Hello World!".to_lower == "hello world!"
841 fun to_lower
: SELFTYPE is abstract
843 # Takes a camel case `self` and converts it to snake case
845 # assert "randomMethodId".to_snake_case == "random_method_id"
847 # If `self` is upper, it is returned unchanged
849 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
851 # If the identifier is prefixed by an underscore, the underscore is ignored
853 # assert "_privateField".to_snake_case == "_private_field"
854 fun to_snake_case
: SELFTYPE
856 if self.is_upper
then return self
858 var new_str
= new FlatBuffer.with_capacity
(self.length
)
859 var is_first_char
= true
861 for i
in [0..length
[ do
863 if is_first_char
then
864 new_str
.add
(char
.to_lower
)
865 is_first_char
= false
866 else if char
.is_upper
then
868 new_str
.add
(char
.to_lower
)
877 # Takes a snake case `self` and converts it to camel case
879 # assert "random_method_id".to_camel_case == "randomMethodId"
881 # If the identifier is prefixed by an underscore, the underscore is ignored
883 # assert "_private_field".to_camel_case == "_privateField"
885 # If `self` is upper, it is returned unchanged
887 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
889 # If there are several consecutive underscores, they are considered as a single one
891 # assert "random__method_id".to_camel_case == "randomMethodId"
892 fun to_camel_case
: SELFTYPE
894 if self.is_upper
then return self
896 var new_str
= new FlatBuffer
897 var is_first_char
= true
898 var follows_us
= false
900 for i
in [0..length
[ do
902 if is_first_char
then
904 is_first_char
= false
905 else if char
== '_' then
907 else if follows_us
then
908 new_str
.add
(char
.to_upper
)
918 # Returns a capitalized `self`
920 # Letters that follow a letter are lowercased
921 # Letters that follow a non-letter are upcased.
923 # SEE : `Char::is_letter` for the definition of letter.
925 # assert "jAVASCRIPT".capitalized == "Javascript"
926 # assert "i am root".capitalized == "I Am Root"
927 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
928 fun capitalized
: SELFTYPE do
929 if length
== 0 then return self
931 var buf
= new FlatBuffer.with_capacity
(length
)
933 var curr
= chars
[0].to_upper
937 for i
in [1 .. length
[ do
940 if prev
.is_letter
then
941 buf
[i
] = curr
.to_lower
943 buf
[i
] = curr
.to_upper
951 private class FlatSubstringsIter
952 super Iterator[FlatText]
954 var tgt
: nullable FlatText
958 return tgt
.as(not null)
961 redef fun is_ok
do return tgt
!= null
963 redef fun next
do tgt
= null
966 # Immutable strings of characters.
971 # Index in _items of the start of the string
972 private var index_from
: Int is noinit
974 # Indes in _items of the last item of the string
975 private var index_to
: Int is noinit
977 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
981 # Check that the index (+ index_from) is not larger than indexTo
982 # In other terms, if the index is valid
984 assert (index
+ index_from
) <= index_to
985 return items
[index
+ index_from
]
988 ################################################
989 # AbstractString specific methods #
990 ################################################
994 var native
= new NativeString(self.length
+ 1)
995 var length
= self.length
996 var items
= self.items
999 while pos
< length
do
1000 native
[pos
] = items
[ipos
]
1004 return native
.to_s_with_length
(self.length
)
1007 redef fun substring
(from
, count
)
1013 if count
< 0 then count
= 0
1017 var realFrom
= index_from
+ from
1019 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
1021 if count
== 0 then return empty
1023 var to
= realFrom
+ count
- 1
1025 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
1028 redef fun empty
do return "".as(FlatString)
1032 var outstr
= new NativeString(self.length
+ 1)
1035 var myitems
= self.items
1036 var index_from
= self.index_from
1037 var max
= self.index_to
1039 while index_from
<= max
do
1040 outstr
[out_index
] = myitems
[index_from
].to_upper
1045 outstr
[self.length
] = '\0'
1047 return outstr
.to_s_with_length
(self.length
)
1052 var outstr
= new NativeString(self.length
+ 1)
1055 var myitems
= self.items
1056 var index_from
= self.index_from
1057 var max
= self.index_to
1059 while index_from
<= max
do
1060 outstr
[out_index
] = myitems
[index_from
].to_lower
1065 outstr
[self.length
] = '\0'
1067 return outstr
.to_s_with_length
(self.length
)
1072 var i
= self.index_from
1073 var imax
= self.index_to
1080 ##################################################
1081 # String Specific Methods #
1082 ##################################################
1084 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
1092 redef fun to_cstring
: NativeString
1094 if real_items
!= null then
1095 return real_items
.as(not null)
1097 var newItems
= new NativeString(length
+ 1)
1098 self.items
.copy_to
(newItems
, length
, index_from
, 0)
1099 newItems
[length
] = '\0'
1100 self.real_items
= newItems
1107 if not other
isa FlatString then return super
1109 if self.object_id
== other
.object_id
then return true
1111 var my_length
= length
1113 if other
.length
!= my_length
then return false
1115 var my_index
= index_from
1116 var its_index
= other
.index_from
1118 var last_iteration
= my_index
+ my_length
1120 var itsitems
= other
.items
1121 var myitems
= self.items
1123 while my_index
< last_iteration
do
1124 if myitems
[my_index
] != itsitems
[its_index
] then return false
1134 if not other
isa FlatString then return super
1136 if self.object_id
== other
.object_id
then return false
1138 var my_curr_char
: Char
1139 var its_curr_char
: Char
1141 var curr_id_self
= self.index_from
1142 var curr_id_other
= other
.index_from
1144 var my_items
= self.items
1145 var its_items
= other
.items
1147 var my_length
= self.length
1148 var its_length
= other
.length
1150 var max_iterations
= curr_id_self
+ my_length
1152 while curr_id_self
< max_iterations
do
1153 my_curr_char
= my_items
[curr_id_self
]
1154 its_curr_char
= its_items
[curr_id_other
]
1156 if my_curr_char
!= its_curr_char
then
1157 if my_curr_char
< its_curr_char
then return true
1165 return my_length
< its_length
1170 var my_length
= self.length
1171 var its_length
= s
.length
1173 var total_length
= my_length
+ its_length
1175 var target_string
= new NativeString(my_length
+ its_length
+ 1)
1177 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
1178 if s
isa FlatString then
1179 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
1180 else if s
isa FlatBuffer then
1181 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
1183 var curr_pos
= my_length
1184 for i
in [0..s
.length
[ do
1186 target_string
[curr_pos
] = c
1191 target_string
[total_length
] = '\0'
1193 return target_string
.to_s_with_length
(total_length
)
1200 var my_length
= self.length
1202 var final_length
= my_length
* i
1204 var my_items
= self.items
1206 var target_string
= new NativeString(final_length
+ 1)
1208 target_string
[final_length
] = '\0'
1210 var current_last
= 0
1212 for iteration
in [1 .. i
] do
1213 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
1214 current_last
+= my_length
1217 return target_string
.to_s_with_length
(final_length
)
1222 if hash_cache
== null then
1223 # djb2 hash algorithm
1229 while i
<= index_to
do
1230 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
1237 return hash_cache
.as(not null)
1240 redef fun substrings
do return new FlatSubstringsIter(self)
1243 private class FlatStringReverseIterator
1244 super IndexedIterator[Char]
1246 var target
: FlatString
1248 var target_items
: NativeString
1252 init with_pos
(tgt
: FlatString, pos
: Int)
1255 target_items
= tgt
.items
1256 curr_pos
= pos
+ tgt
.index_from
1259 redef fun is_ok
do return curr_pos
>= target
.index_from
1261 redef fun item
do return target_items
[curr_pos
]
1263 redef fun next
do curr_pos
-= 1
1265 redef fun index
do return curr_pos
- target
.index_from
1269 private class FlatStringIterator
1270 super IndexedIterator[Char]
1272 var target
: FlatString
1274 var target_items
: NativeString
1278 init with_pos
(tgt
: FlatString, pos
: Int)
1281 target_items
= tgt
.items
1282 curr_pos
= pos
+ target
.index_from
1285 redef fun is_ok
do return curr_pos
<= target
.index_to
1287 redef fun item
do return target_items
[curr_pos
]
1289 redef fun next
do curr_pos
+= 1
1291 redef fun index
do return curr_pos
- target
.index_from
1295 private class FlatStringCharView
1296 super StringCharView
1298 redef type SELFTYPE: FlatString
1302 # Check that the index (+ index_from) is not larger than indexTo
1303 # In other terms, if the index is valid
1305 var target
= self.target
1306 assert (index
+ target
.index_from
) <= target
.index_to
1307 return target
.items
[index
+ target
.index_from
]
1310 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
1312 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
1316 abstract class Buffer
1319 redef type SELFTYPE: Buffer
1321 # Specific implementations MUST set this to `true` in order to invalidate caches
1322 protected var is_dirty
= true
1324 # Copy-On-Write flag
1326 # If the `Buffer` was to_s'd, the next in-place altering
1327 # operation will cause the current `Buffer` to be re-allocated.
1329 # The flag will then be set at `false`.
1330 protected var written
= false
1332 # Modifies the char contained at pos `index`
1334 # DEPRECATED : Use self.chars.[]= instead
1335 fun []=(index
: Int, item
: Char) is abstract
1337 # Adds a char `c` at the end of self
1339 # DEPRECATED : Use self.chars.add instead
1340 fun add
(c
: Char) is abstract
1344 # var b = new FlatBuffer
1346 # assert not b.is_empty
1349 fun clear
is abstract
1351 # Enlarges the subsequent array containing the chars of self
1352 fun enlarge
(cap
: Int) is abstract
1354 # Adds the content of text `s` at the end of self
1356 # var b = new FlatBuffer
1359 # assert b == "helloworld"
1360 fun append
(s
: Text) is abstract
1362 # `self` is appended in such a way that `self` is repeated `r` times
1364 # var b = new FlatBuffer
1367 # assert b == "hellohellohello"
1368 fun times
(r
: Int) is abstract
1370 # Reverses itself in-place
1372 # var b = new FlatBuffer
1375 # assert b == "olleh"
1376 fun reverse
is abstract
1378 # Changes each lower-case char in `self` by its upper-case variant
1380 # var b = new FlatBuffer
1381 # b.append("Hello World!")
1383 # assert b == "HELLO WORLD!"
1384 fun upper
is abstract
1386 # Changes each upper-case char in `self` by its lower-case variant
1388 # var b = new FlatBuffer
1389 # b.append("Hello World!")
1391 # assert b == "hello world!"
1392 fun lower
is abstract
1394 # Capitalizes each word in `self`
1396 # Letters that follow a letter are lowercased
1397 # Letters that follow a non-letter are upcased.
1399 # SEE: `Char::is_letter` for the definition of a letter.
1401 # var b = new FlatBuffer.from("jAVAsCriPt")"
1403 # assert b == "Javascript"
1404 # b = new FlatBuffer.from("i am root")
1406 # assert b == "I Am Root"
1407 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1409 # assert b == "Ab_C -Ab0C Ab\nC"
1411 if length
== 0 then return
1412 var c
= self[0].to_upper
1415 for i
in [1 .. length
[ do
1418 if prev
.is_letter
then
1419 self[i
] = c
.to_lower
1421 self[i
] = c
.to_upper
1428 if is_dirty
then hash_cache
= null
1432 # In Buffers, the internal sequence of character is mutable
1433 # Thus, `chars` can be used to modify the buffer.
1434 redef fun chars
: Sequence[Char] is abstract
1437 # Mutable strings of characters.
1442 redef type SELFTYPE: FlatBuffer
1444 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1446 private var capacity
: Int = 0
1448 redef fun substrings
do return new FlatSubstringsIter(self)
1450 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1452 # This happens when an operation modifies the current `Buffer` and
1453 # the Copy-On-Write flag `written` is set at true.
1454 private fun reset
do
1455 var nns
= new NativeString(capacity
)
1456 items
.copy_to
(nns
, length
, 0, 0)
1464 assert index
< length
1468 redef fun []=(index
, item
)
1471 if index
== length
then
1475 if written
then reset
1476 assert index
>= 0 and index
< length
1483 if capacity
<= length
then enlarge
(length
+ 5)
1490 if written
then reset
1494 redef fun empty
do return new FlatBuffer
1496 redef fun enlarge
(cap
)
1499 if cap
<= c
then return
1500 while c
<= cap
do c
= c
* 2 + 2
1501 # The COW flag can be set at false here, since
1502 # it does a copy of the current `Buffer`
1504 var a
= new NativeString(c
+1)
1505 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1510 redef fun to_s
: String
1513 if length
== 0 then items
= new NativeString(1)
1514 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1517 redef fun to_cstring
1520 var new_native
= new NativeString(length
+ 1)
1521 new_native
[length
] = '\0'
1522 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1523 real_items
= new_native
1526 return real_items
.as(not null)
1529 # Create a new empty string.
1534 capacity
= s
.length
+ 1
1536 items
= new NativeString(capacity
)
1537 if s
isa FlatString then
1538 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1539 else if s
isa FlatBuffer then
1540 s
.items
.copy_to
(items
, length
, 0, 0)
1543 for i
in [0..s
.length
[ do
1551 # Create a new empty string with a given capacity.
1552 init with_capacity
(cap
: Int)
1555 # _items = new NativeString.calloc(cap)
1556 items
= new NativeString(cap
+1)
1563 if s
.is_empty
then return
1566 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1567 if s
isa FlatString then
1568 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1569 else if s
isa FlatBuffer then
1570 s
.items
.copy_to
(items
, sl
, 0, length
)
1572 var curr_pos
= self.length
1573 for i
in [0..s
.length
[ do
1582 # Copies the content of self in `dest`
1583 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1585 var self_chars
= self.chars
1586 var dest_chars
= dest
.chars
1587 for i
in [0..len-1
] do
1588 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1592 redef fun substring
(from
, count
)
1596 if from
< 0 then from
= 0
1597 if count
> length
then count
= length
1598 if from
< count
then
1599 var r
= new FlatBuffer.with_capacity
(count
- from
)
1600 while from
< count
do
1601 r
.chars
.push
(items
[from
])
1606 return new FlatBuffer
1613 var ns
= new NativeString(capacity
)
1625 redef fun times
(repeats
)
1627 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1628 for i
in [1..repeats
[ do
1635 if written
then reset
1639 it
[id
] = it
[id
].to_upper
1646 if written
then reset
1650 it
[id
] = it
[id
].to_lower
1656 private class FlatBufferReverseIterator
1657 super IndexedIterator[Char]
1659 var target
: FlatBuffer
1661 var target_items
: NativeString
1665 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1668 if tgt
.length
> 0 then target_items
= tgt
.items
1672 redef fun index
do return curr_pos
1674 redef fun is_ok
do return curr_pos
>= 0
1676 redef fun item
do return target_items
[curr_pos
]
1678 redef fun next
do curr_pos
-= 1
1682 private class FlatBufferCharView
1683 super BufferCharView
1685 redef type SELFTYPE: FlatBuffer
1687 redef fun [](index
) do return target
.items
[index
]
1689 redef fun []=(index
, item
)
1691 assert index
>= 0 and index
<= length
1692 if index
== length
then
1696 target
.items
[index
] = item
1709 fun enlarge
(cap
: Int)
1716 var my_items
= target
.items
1717 var s_length
= s
.length
1718 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1721 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1723 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1727 private class FlatBufferIterator
1728 super IndexedIterator[Char]
1730 var target
: FlatBuffer
1732 var target_items
: NativeString
1736 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1739 if tgt
.length
> 0 then target_items
= tgt
.items
1743 redef fun index
do return curr_pos
1745 redef fun is_ok
do return curr_pos
< target
.length
1747 redef fun item
do return target_items
[curr_pos
]
1749 redef fun next
do curr_pos
+= 1
1753 ###############################################################################
1755 ###############################################################################
1758 # User readable representation of `self`.
1759 fun to_s
: String do return inspect
1761 # The class name of the object in NativeString format.
1762 private fun native_class_name
: NativeString is intern
1764 # The class name of the object.
1766 # assert 5.class_name == "Int"
1767 fun class_name
: String do return native_class_name
.to_s
1769 # Developer readable representation of `self`.
1770 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1773 return "<{inspect_head}>"
1776 # Return "CLASSNAME:#OBJECTID".
1777 # This function is mainly used with the redefinition of the inspect method
1778 protected fun inspect_head
: String
1780 return "{class_name}:#{object_id.to_hex}"
1785 # assert true.to_s == "true"
1786 # assert false.to_s == "false"
1799 # Wrapper of strerror C function
1800 private fun strerror_ext
: NativeString is extern `{
1801 return strerror(recv);
1804 # Returns a string describing error number
1805 fun strerror
: String do return strerror_ext
.to_s
1807 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1808 # assume < to_c max const of char
1809 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1816 else if self == 0 then
1823 var pos
= digit_count
(base
) - 1
1824 while pos
>= 0 and n
> 0 do
1825 s
.chars
[pos
] = (n
% base
).to_c
1831 # C function to convert an nit Int to a NativeString (char*)
1832 private fun native_int_to_s
: NativeString is extern "native_int_to_s"
1834 # return displayable int in base 10 and signed
1836 # assert 1.to_s == "1"
1837 # assert (-123).to_s == "-123"
1839 return native_int_to_s
.to_s
1842 # return displayable int in hexadecimal
1844 # assert 1.to_hex == "1"
1845 # assert (-255).to_hex == "-ff"
1846 fun to_hex
: String do return to_base
(16,false)
1848 # return displayable int in base base and signed
1849 fun to_base
(base
: Int, signed
: Bool): String
1851 var l
= digit_count
(base
)
1852 var s
= new FlatBuffer.from
(" " * l
)
1853 fill_buffer
(s
, base
, signed
)
1859 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1861 # assert 12.34.to_s == "12.34"
1862 # assert (-0120.030).to_s == "-120.03"
1864 # see `to_precision` for a custom precision.
1866 var str
= to_precision
( 3 )
1867 if is_inf
!= 0 or is_nan
then return str
1868 var len
= str
.length
1869 for i
in [0..len-1
] do
1871 var c
= str
.chars
[j
]
1874 else if c
== '.' then
1875 return str
.substring
( 0, j
+2 )
1877 return str
.substring
( 0, j
+1 )
1883 # `String` representation of `self` with the given number of `decimals`
1885 # assert 12.345.to_precision(0) == "12"
1886 # assert 12.345.to_precision(3) == "12.345"
1887 # assert (-12.345).to_precision(3) == "-12.345"
1888 # assert (-0.123).to_precision(3) == "-0.123"
1889 # assert 0.999.to_precision(2) == "1.00"
1890 # assert 0.999.to_precision(4) == "0.9990"
1891 fun to_precision
(decimals
: Int): String
1893 if is_nan
then return "nan"
1895 var isinf
= self.is_inf
1898 else if isinf
== -1 then
1902 if decimals
== 0 then return self.to_i
.to_s
1904 for i
in [0..decimals
[ do f
= f
* 10.0
1911 if i
== 0 then return "0." + "0"*decimals
1913 # Prepare both parts of the float, before and after the "."
1918 if sl
> decimals
then
1919 # Has something before the "."
1920 p1
= s
.substring
(0, sl-decimals
)
1921 p2
= s
.substring
(sl-decimals
, decimals
)
1924 p2
= "0"*(decimals-sl
) + s
1927 if i
< 0 then p1
= "-" + p1
1929 return p1
+ "." + p2
1932 # `self` representation with `nb` digits after the '.'.
1934 # assert 12.345.to_precision_native(1) == "12.3"
1935 # assert 12.345.to_precision_native(2) == "12.35"
1936 # assert 12.345.to_precision_native(3) == "12.345"
1937 # assert 12.345.to_precision_native(4) == "12.3450"
1938 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1942 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1943 str = malloc(size + 1);
1944 sprintf(str, "%.*f", (int)nb, recv );
1946 return NativeString_to_s( str );
1951 # assert 'x'.to_s == "x"
1954 var s
= new FlatBuffer.with_capacity
(1)
1959 # Returns true if the char is a numerical digit
1961 # assert '0'.is_numeric
1962 # assert '9'.is_numeric
1963 # assert not 'a'.is_numeric
1964 # assert not '?'.is_numeric
1965 fun is_numeric
: Bool
1967 return self >= '0' and self <= '9'
1970 # Returns true if the char is an alpha digit
1972 # assert 'a'.is_alpha
1973 # assert 'Z'.is_alpha
1974 # assert not '0'.is_alpha
1975 # assert not '?'.is_alpha
1978 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1981 # Returns true if the char is an alpha or a numeric digit
1983 # assert 'a'.is_alphanumeric
1984 # assert 'Z'.is_alphanumeric
1985 # assert '0'.is_alphanumeric
1986 # assert '9'.is_alphanumeric
1987 # assert not '?'.is_alphanumeric
1988 fun is_alphanumeric
: Bool
1990 return self.is_numeric
or self.is_alpha
1994 redef class Collection[E
]
1995 # Concatenate elements.
1998 var s
= new FlatBuffer
1999 for e
in self do if e
!= null then s
.append
(e
.to_s
)
2003 # Concatenate and separate each elements with `sep`.
2005 # assert [1, 2, 3].join(":") == "1:2:3"
2006 # assert [1..3].join(":") == "1:2:3"
2007 fun join
(sep
: Text): String
2009 if is_empty
then return ""
2011 var s
= new FlatBuffer # Result
2016 if e
!= null then s
.append
(e
.to_s
)
2018 # Concat other items
2023 if e
!= null then s
.append
(e
.to_s
)
2030 redef class Array[E
]
2032 # Fast implementation
2036 if l
== 0 then return ""
2037 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
2039 var na
= new NativeArray[String](l
)
2045 if itsi
== null then
2055 var ns
= new NativeString(sl
+ 1)
2061 var tpl
= tmp
.length
2062 if tmp
isa FlatString then
2063 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2066 for j
in tmp
.substrings
do
2067 var s
= j
.as(FlatString)
2069 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2075 return ns
.to_s_with_length
(sl
)
2079 redef class Map[K
,V
]
2080 # Concatenate couple of 'key value'.
2081 # key and value are separated by `couple_sep`.
2082 # each couple is separated each couple with `sep`.
2084 # var m = new ArrayMap[Int, String]
2087 # assert m.join("; ", "=") == "1=one; 10=ten"
2088 fun join
(sep
: String, couple_sep
: String): String
2090 if is_empty
then return ""
2092 var s
= new FlatBuffer # Result
2098 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2100 # Concat other items
2106 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2113 ###############################################################################
2115 ###############################################################################
2117 # Native strings are simple C char *
2118 extern class NativeString `{ char* `}
2119 # Creates a new NativeString with a capacity of `length
`
2120 new(length: Int) is intern
2121 fun [](index: Int): Char is intern
2122 fun []=(index: Int, item: Char) is intern
2123 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2125 # Position of the first nul character.
2126 fun cstring_length: Int
2129 while self[l] != '\0' do l += 1
2132 fun atoi: Int is intern
2133 fun atof: Float is extern "atof"
2137 return to_s_with_length(cstring_length)
2140 fun to_s_with_length(length: Int): FlatString
2143 var str = new FlatString.with_infos(self, length, 0, length - 1)
2147 fun to_s_with_copy: FlatString
2149 var length = cstring_length
2150 var new_self = new NativeString(length + 1)
2151 copy_to(new_self, length, 0, 0)
2152 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2153 new_self[length] = '\0'
2154 str.real_items = new_self
2160 private var args_cache: nullable Sequence[String]
2162 # The arguments of the program as given by the OS
2163 fun program_args: Sequence[String]
2165 if _args_cache == null then init_args
2166 return _args_cache.as(not null)
2169 # The name of the program as given by the OS
2170 fun program_name: String
2172 return native_argv(0).to_s
2175 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2176 private fun init_args
2178 var argc = native_argc
2179 var args = new Array[String].with_capacity(0)
2182 args[i-1] = native_argv(i).to_s
2188 # First argument of the main C function.
2189 private fun native_argc: Int is intern
2191 # Second argument of the main C function.
2192 private fun native_argv(i: Int): NativeString is intern
2195 # Comparator that efficienlty use `to_s
` to compare things
2197 # The comparaison call `to_s
` on object and use the result to order things.
2199 # var a = [1, 2, 3, 10, 20]
2200 # (new CachedAlphaComparator).sort(a)
2201 # assert a == [1, 10, 2, 20, 3]
2203 # Internally the result of `to_s
` is cached in a HashMap to counter
2204 # uneficient implementation of `to_s
`.
2206 # Note: it caching is not usefull, see `alpha_comparator
`
2207 class CachedAlphaComparator
2209 redef type COMPARED: Object
2211 private var cache = new HashMap[Object, String]
2213 private fun do_to_s(a: Object): String do
2214 if cache.has_key(a) then return cache[a]
2220 redef fun compare(a, b) do
2221 return do_to_s(a) <=> do_to_s(b)
2225 # see `alpha_comparator
`
2226 private class AlphaComparator
2228 redef fun compare(a, b) do return a.to_s <=> b.to_s
2231 # Stateless comparator that naively use `to_s
` to compare things.
2233 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2234 # on a single instace. See `CachedAlphaComparator` as an alternative.
2236 # var a = [1, 2, 3, 10, 20]
2237 # alpha_comparator.sort(a)
2238 # assert a == [1, 10, 2, 20, 3]
2239 fun alpha_comparator: Comparator do return once new AlphaComparator
2241 # The arguments of the program as given by the OS
2242 fun args: Sequence[String]
2244 return sys.program_args