664ecbcb0652892b7659a98e5fb24c995211563c
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 # Returns `self` removed from its last `\n` (if any).
390 # assert "Hello\n".chomp == "Hello"
391 # assert "Hello".chomp == "Hello"
392 # assert "\n\n\n".chomp == "\n\n"
394 # This method is mainly used to remove the LINE_FEED character from lines of text.
397 if self.chars
.last
!= '\n' then return self
398 return substring
(0, length-1
)
401 # Justify a self in a space of `length`
403 # `left` is the space ratio on the left side.
404 # * 0.0 for left-justified (no space at the left)
405 # * 1.0 for right-justified (all spaces at the left)
406 # * 0.5 for centered (half the spaces at the left)
408 # assert "hello".justify(10, 0.0) == "hello "
409 # assert "hello".justify(10, 1.0) == " hello"
410 # assert "hello".justify(10, 0.5) == " hello "
412 # If `length` is not enough, `self` is returned as is.
414 # assert "hello".justify(2, 0.0) == "hello"
416 # REQUIRE: left >= 0.0 and left <= 1.0
417 # ENSURE: `self.length <= length implies result.length == length`
418 # ENSURE: `self.length >= length implies result == self
419 fun justify
(length
: Int, left
: Float): SELFTYPE
421 var diff
= length
- self.length
422 if diff
<= 0 then return self
423 assert left
>= 0.0 and left
<= 1.0
424 var before
= (diff
.to_f
* left
).to_i
425 return " " * before
+ self + " " * (diff-before
)
428 # Mangle a string to be a unique string only made of alphanumeric characters
429 fun to_cmangle
: String
431 var res
= new FlatBuffer
432 var underscore
= false
433 for i
in [0..length
[ do
435 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
441 res
.append
('_'.ascii
.to_s
)
444 if c
>= '0' and c
<= '9' then
447 else if c
== '_' then
452 res
.append
(c
.ascii
.to_s
)
460 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
462 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
463 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
464 fun escape_to_c
: String
466 var b
= new FlatBuffer
467 for i
in [0..length
[ do
471 else if c
== '\0' then
473 else if c
== '"' then
475 else if c == '\'' then
477 else if c == '\\
' then
479 else if c.ascii < 32 then
480 b.append("\\{c.ascii.to_base(8, false)}")
488 # Escape additionnal characters
489 # The result might no be legal in C but be used in other languages
491 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
492 fun escape_more_to_c(chars: String): String
494 var b = new FlatBuffer
495 for c in escape_to_c.chars do
496 if chars.chars.has(c) then
504 # Escape to C plus braces
506 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
507 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
509 # Escape to POSIX Shell (sh).
511 # Abort if the text contains a null byte.
513 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
514 fun escape_to_sh
: String do
515 var b
= new FlatBuffer
517 for i in [0..length[ do
522 assert without_null_byte
: c
!= '\0'
530 # Escape to include in a Makefile
532 # Unfortunately, some characters are not escapable in Makefile.
533 # These characters are `;`, `|`, `\`, and the non-printable ones.
534 # They will be rendered as `"?{hex}"`.
535 fun escape_to_mk: String do
536 var b = new FlatBuffer
537 for i in [0..length[ do
541 else if c == ':' or c == ' ' or c == '#' then
544 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
545 b
.append
("?{c.ascii.to_base(16, false)}")
553 # Return a string where Nit escape sequences are transformed.
556 # assert s.length == 2
557 # var u = s.unescape_nit
558 # assert u.length == 1
559 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
560 fun unescape_nit
: String
562 var res
= new FlatBuffer.with_capacity
(self.length
)
563 var was_slash
= false
564 for i
in [0..length
[ do
566 if not was_slash
then
577 else if c
== 'r' then
579 else if c
== 't' then
581 else if c
== '0' then
590 # Encode `self` to percent (or URL) encoding
592 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
593 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
594 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
595 fun to_percent_encoding
: String
597 var buf
= new FlatBuffer
599 for i
in [0..length
[ do
601 if (c
>= '0' and c
<= '9') or
602 (c
>= 'a' and c
<= 'z') or
603 (c
>= 'A' and c
<= 'Z') or
604 c
== '-' or c
== '.' or
608 else buf
.append
"%{c.ascii.to_hex}"
614 # Decode `self` from percent (or URL) encoding to a clear string
616 # Replace invalid use of '%' with '?'.
618 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
619 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
620 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
621 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
622 # assert "incomplete %".from_percent_encoding == "incomplete ?"
623 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
624 fun from_percent_encoding
: String
626 var buf
= new FlatBuffer
632 if i
+ 2 >= length
then
633 # What follows % has been cut off
637 var hex_s
= substring
(i
, 2)
639 var hex_i
= hex_s
.to_hex
643 # What follows a % is not Hex
656 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
658 # assert "a&b->\"x\"".html_escape == "a&b->"x""
659 fun html_escape
: SELFTYPE
661 var buf
= new FlatBuffer
663 for i
in [0..length
[ do
667 else if c
== '<' then
669 else if c
== '>' then
671 else if c
== '"' then
680 # Two pieces of text are equals if thez have the same characters in the same order.
682 # assert "hello" == "hello"
683 # assert "hello" != "HELLO"
684 # assert "hello" == "hel"+"lo"
686 # Things that are not Text are not equal.
689 # assert "9" != ['9']
692 # assert "9".chars.first == '9' # equality of Char
693 # assert "9".chars == ['9'] # equality of Sequence
694 # assert "9".to_i == 9 # equality of Int
697 if o
== null then return false
698 if not o
isa Text then return false
699 if self.is_same_instance
(o
) then return true
700 if self.length
!= o
.length
then return false
701 return self.chars
== o
.chars
704 # Lexicographical comparaison
706 # assert "abc" < "xy"
707 # assert "ABC" < "abc"
710 var self_chars
= self.chars
.iterator
711 var other_chars
= other
.chars
.iterator
713 while self_chars
.is_ok
and other_chars
.is_ok
do
714 if self_chars
.item
< other_chars
.item
then return true
715 if self_chars
.item
> other_chars
.item
then return false
720 if self_chars
.is_ok
then
727 # Escape string used in labels for graphviz
729 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
730 fun escape_to_dot
: String
732 return escape_more_to_c
("|\{\}<>")
735 # Flat representation of self
736 fun flatten
: FlatText is abstract
738 private var hash_cache
: nullable Int = null
742 if hash_cache
== null then
743 # djb2 hash algorithm
746 for i
in [0..length
[ do
748 h
= h
.lshift
(5) + h
+ char
.ascii
753 return hash_cache
.as(not null)
758 # All kinds of array-based text representations.
759 abstract class FlatText
762 # Underlying C-String (`char*`)
764 # Warning : Might be void in some subclasses, be sure to check
765 # if set before using it.
766 private var items
: NativeString is noinit
768 # Real items, used as cache for to_cstring is called
769 private var real_items
: nullable NativeString = null
771 redef var length
: Int = 0
782 redef fun flatten
do return self
785 # Abstract class for the SequenceRead compatible
786 # views on String and Buffer objects
787 private abstract class StringCharView
788 super SequenceRead[Char]
794 redef fun is_empty
do return target
.is_empty
796 redef fun length
do return target
.length
798 redef fun iterator
: IndexedIterator[Char] do return self.iterator_from
(0)
800 redef fun reverse_iterator
do return self.reverse_iterator_from
(self.length
- 1)
803 # View on Buffer objects, extends Sequence
804 # for mutation operations
805 private abstract class BufferCharView
809 redef type SELFTYPE: Buffer
813 # A `String` holds and manipulates an arbitrary sequence of characters.
815 # String objects may be created using literals.
817 # assert "Hello World!" isa String
818 abstract class String
821 redef type SELFTYPE: String
823 redef fun to_s
do return self
825 # Concatenates `o` to `self`
827 # assert "hello" + "world" == "helloworld"
828 # assert "" + "hello" + "" == "hello"
829 fun +(o
: Text): SELFTYPE is abstract
831 # Concatenates self `i` times
833 # assert "abc" * 4 == "abcabcabcabc"
834 # assert "abc" * 1 == "abc"
835 # assert "abc" * 0 == ""
836 fun *(i
: Int): SELFTYPE is abstract
838 # Insert `s` at `pos`.
840 # assert "helloworld".insert_at(" ", 5) == "hello world"
841 fun insert_at
(s
: String, pos
: Int): SELFTYPE is abstract
843 redef fun substrings
: Iterator[String] is abstract
845 # Returns a reversed version of self
847 # assert "hello".reversed == "olleh"
848 # assert "bob".reversed == "bob"
849 # assert "".reversed == ""
850 fun reversed
: SELFTYPE is abstract
852 # A upper case version of `self`
854 # assert "Hello World!".to_upper == "HELLO WORLD!"
855 fun to_upper
: SELFTYPE is abstract
857 # A lower case version of `self`
859 # assert "Hello World!".to_lower == "hello world!"
860 fun to_lower
: SELFTYPE is abstract
862 # Takes a camel case `self` and converts it to snake case
864 # assert "randomMethodId".to_snake_case == "random_method_id"
866 # If `self` is upper, it is returned unchanged
868 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
870 # If the identifier is prefixed by an underscore, the underscore is ignored
872 # assert "_privateField".to_snake_case == "_private_field"
873 fun to_snake_case
: SELFTYPE
875 if self.is_upper
then return self
877 var new_str
= new FlatBuffer.with_capacity
(self.length
)
878 var is_first_char
= true
880 for i
in [0..length
[ do
882 if is_first_char
then
883 new_str
.add
(char
.to_lower
)
884 is_first_char
= false
885 else if char
.is_upper
then
887 new_str
.add
(char
.to_lower
)
896 # Takes a snake case `self` and converts it to camel case
898 # assert "random_method_id".to_camel_case == "randomMethodId"
900 # If the identifier is prefixed by an underscore, the underscore is ignored
902 # assert "_private_field".to_camel_case == "_privateField"
904 # If `self` is upper, it is returned unchanged
906 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
908 # If there are several consecutive underscores, they are considered as a single one
910 # assert "random__method_id".to_camel_case == "randomMethodId"
911 fun to_camel_case
: SELFTYPE
913 if self.is_upper
then return self
915 var new_str
= new FlatBuffer
916 var is_first_char
= true
917 var follows_us
= false
919 for i
in [0..length
[ do
921 if is_first_char
then
923 is_first_char
= false
924 else if char
== '_' then
926 else if follows_us
then
927 new_str
.add
(char
.to_upper
)
937 # Returns a capitalized `self`
939 # Letters that follow a letter are lowercased
940 # Letters that follow a non-letter are upcased.
942 # SEE : `Char::is_letter` for the definition of letter.
944 # assert "jAVASCRIPT".capitalized == "Javascript"
945 # assert "i am root".capitalized == "I Am Root"
946 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
947 fun capitalized
: SELFTYPE do
948 if length
== 0 then return self
950 var buf
= new FlatBuffer.with_capacity
(length
)
952 var curr
= chars
[0].to_upper
956 for i
in [1 .. length
[ do
959 if prev
.is_letter
then
960 buf
[i
] = curr
.to_lower
962 buf
[i
] = curr
.to_upper
970 private class FlatSubstringsIter
971 super Iterator[FlatText]
973 var tgt
: nullable FlatText
977 return tgt
.as(not null)
980 redef fun is_ok
do return tgt
!= null
982 redef fun next
do tgt
= null
985 # Immutable strings of characters.
990 # Index in _items of the start of the string
991 private var index_from
: Int is noinit
993 # Indes in _items of the last item of the string
994 private var index_to
: Int is noinit
996 redef var chars
: SequenceRead[Char] = new FlatStringCharView(self)
1000 # Check that the index (+ index_from) is not larger than indexTo
1001 # In other terms, if the index is valid
1003 assert (index
+ index_from
) <= index_to
1004 return items
[index
+ index_from
]
1007 ################################################
1008 # AbstractString specific methods #
1009 ################################################
1013 var native
= new NativeString(self.length
+ 1)
1014 var length
= self.length
1015 var items
= self.items
1018 while pos
< length
do
1019 native
[pos
] = items
[ipos
]
1023 return native
.to_s_with_length
(self.length
)
1026 redef fun substring
(from
, count
)
1032 if count
< 0 then count
= 0
1036 var realFrom
= index_from
+ from
1038 if (realFrom
+ count
) > index_to
then return new FlatString.with_infos
(items
, index_to
- realFrom
+ 1, realFrom
, index_to
)
1040 if count
== 0 then return empty
1042 var to
= realFrom
+ count
- 1
1044 return new FlatString.with_infos
(items
, to
- realFrom
+ 1, realFrom
, to
)
1047 redef fun empty
do return "".as(FlatString)
1051 var outstr
= new NativeString(self.length
+ 1)
1054 var myitems
= self.items
1055 var index_from
= self.index_from
1056 var max
= self.index_to
1058 while index_from
<= max
do
1059 outstr
[out_index
] = myitems
[index_from
].to_upper
1064 outstr
[self.length
] = '\0'
1066 return outstr
.to_s_with_length
(self.length
)
1071 var outstr
= new NativeString(self.length
+ 1)
1074 var myitems
= self.items
1075 var index_from
= self.index_from
1076 var max
= self.index_to
1078 while index_from
<= max
do
1079 outstr
[out_index
] = myitems
[index_from
].to_lower
1084 outstr
[self.length
] = '\0'
1086 return outstr
.to_s_with_length
(self.length
)
1091 var i
= self.index_from
1092 var imax
= self.index_to
1099 ##################################################
1100 # String Specific Methods #
1101 ##################################################
1103 private init with_infos
(items
: NativeString, len
: Int, from
: Int, to
: Int)
1111 redef fun to_cstring
: NativeString
1113 if real_items
!= null then
1114 return real_items
.as(not null)
1116 var newItems
= new NativeString(length
+ 1)
1117 self.items
.copy_to
(newItems
, length
, index_from
, 0)
1118 newItems
[length
] = '\0'
1119 self.real_items
= newItems
1126 if not other
isa FlatString then return super
1128 if self.object_id
== other
.object_id
then return true
1130 var my_length
= length
1132 if other
.length
!= my_length
then return false
1134 var my_index
= index_from
1135 var its_index
= other
.index_from
1137 var last_iteration
= my_index
+ my_length
1139 var itsitems
= other
.items
1140 var myitems
= self.items
1142 while my_index
< last_iteration
do
1143 if myitems
[my_index
] != itsitems
[its_index
] then return false
1153 if not other
isa FlatString then return super
1155 if self.object_id
== other
.object_id
then return false
1157 var my_curr_char
: Char
1158 var its_curr_char
: Char
1160 var curr_id_self
= self.index_from
1161 var curr_id_other
= other
.index_from
1163 var my_items
= self.items
1164 var its_items
= other
.items
1166 var my_length
= self.length
1167 var its_length
= other
.length
1169 var max_iterations
= curr_id_self
+ my_length
1171 while curr_id_self
< max_iterations
do
1172 my_curr_char
= my_items
[curr_id_self
]
1173 its_curr_char
= its_items
[curr_id_other
]
1175 if my_curr_char
!= its_curr_char
then
1176 if my_curr_char
< its_curr_char
then return true
1184 return my_length
< its_length
1189 var my_length
= self.length
1190 var its_length
= s
.length
1192 var total_length
= my_length
+ its_length
1194 var target_string
= new NativeString(my_length
+ its_length
+ 1)
1196 self.items
.copy_to
(target_string
, my_length
, index_from
, 0)
1197 if s
isa FlatString then
1198 s
.items
.copy_to
(target_string
, its_length
, s
.index_from
, my_length
)
1199 else if s
isa FlatBuffer then
1200 s
.items
.copy_to
(target_string
, its_length
, 0, my_length
)
1202 var curr_pos
= my_length
1203 for i
in [0..s
.length
[ do
1205 target_string
[curr_pos
] = c
1210 target_string
[total_length
] = '\0'
1212 return target_string
.to_s_with_length
(total_length
)
1219 var my_length
= self.length
1221 var final_length
= my_length
* i
1223 var my_items
= self.items
1225 var target_string
= new NativeString(final_length
+ 1)
1227 target_string
[final_length
] = '\0'
1229 var current_last
= 0
1231 for iteration
in [1 .. i
] do
1232 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
1233 current_last
+= my_length
1236 return target_string
.to_s_with_length
(final_length
)
1241 if hash_cache
== null then
1242 # djb2 hash algorithm
1248 while i
<= index_to
do
1249 h
= h
.lshift
(5) + h
+ myitems
[i
].ascii
1256 return hash_cache
.as(not null)
1259 redef fun substrings
do return new FlatSubstringsIter(self)
1262 private class FlatStringReverseIterator
1263 super IndexedIterator[Char]
1265 var target
: FlatString
1267 var target_items
: NativeString
1271 init with_pos
(tgt
: FlatString, pos
: Int)
1274 target_items
= tgt
.items
1275 curr_pos
= pos
+ tgt
.index_from
1278 redef fun is_ok
do return curr_pos
>= target
.index_from
1280 redef fun item
do return target_items
[curr_pos
]
1282 redef fun next
do curr_pos
-= 1
1284 redef fun index
do return curr_pos
- target
.index_from
1288 private class FlatStringIterator
1289 super IndexedIterator[Char]
1291 var target
: FlatString
1293 var target_items
: NativeString
1297 init with_pos
(tgt
: FlatString, pos
: Int)
1300 target_items
= tgt
.items
1301 curr_pos
= pos
+ target
.index_from
1304 redef fun is_ok
do return curr_pos
<= target
.index_to
1306 redef fun item
do return target_items
[curr_pos
]
1308 redef fun next
do curr_pos
+= 1
1310 redef fun index
do return curr_pos
- target
.index_from
1314 private class FlatStringCharView
1315 super StringCharView
1317 redef type SELFTYPE: FlatString
1321 # Check that the index (+ index_from) is not larger than indexTo
1322 # In other terms, if the index is valid
1324 var target
= self.target
1325 assert (index
+ target
.index_from
) <= target
.index_to
1326 return target
.items
[index
+ target
.index_from
]
1329 redef fun iterator_from
(start
) do return new FlatStringIterator.with_pos
(target
, start
)
1331 redef fun reverse_iterator_from
(start
) do return new FlatStringReverseIterator.with_pos
(target
, start
)
1335 # A mutable sequence of characters.
1336 abstract class Buffer
1339 redef type SELFTYPE: Buffer
1341 # Specific implementations MUST set this to `true` in order to invalidate caches
1342 protected var is_dirty
= true
1344 # Copy-On-Write flag
1346 # If the `Buffer` was to_s'd, the next in-place altering
1347 # operation will cause the current `Buffer` to be re-allocated.
1349 # The flag will then be set at `false`.
1350 protected var written
= false
1352 # Modifies the char contained at pos `index`
1354 # DEPRECATED : Use self.chars.[]= instead
1355 fun []=(index
: Int, item
: Char) is abstract
1357 # Adds a char `c` at the end of self
1359 # DEPRECATED : Use self.chars.add instead
1360 fun add
(c
: Char) is abstract
1364 # var b = new FlatBuffer
1366 # assert not b.is_empty
1369 fun clear
is abstract
1371 # Enlarges the subsequent array containing the chars of self
1372 fun enlarge
(cap
: Int) is abstract
1374 # Adds the content of text `s` at the end of self
1376 # var b = new FlatBuffer
1379 # assert b == "helloworld"
1380 fun append
(s
: Text) is abstract
1382 # `self` is appended in such a way that `self` is repeated `r` times
1384 # var b = new FlatBuffer
1387 # assert b == "hellohellohello"
1388 fun times
(r
: Int) is abstract
1390 # Reverses itself in-place
1392 # var b = new FlatBuffer
1395 # assert b == "olleh"
1396 fun reverse
is abstract
1398 # Changes each lower-case char in `self` by its upper-case variant
1400 # var b = new FlatBuffer
1401 # b.append("Hello World!")
1403 # assert b == "HELLO WORLD!"
1404 fun upper
is abstract
1406 # Changes each upper-case char in `self` by its lower-case variant
1408 # var b = new FlatBuffer
1409 # b.append("Hello World!")
1411 # assert b == "hello world!"
1412 fun lower
is abstract
1414 # Capitalizes each word in `self`
1416 # Letters that follow a letter are lowercased
1417 # Letters that follow a non-letter are upcased.
1419 # SEE: `Char::is_letter` for the definition of a letter.
1421 # var b = new FlatBuffer.from("jAVAsCriPt")
1423 # assert b == "Javascript"
1424 # b = new FlatBuffer.from("i am root")
1426 # assert b == "I Am Root"
1427 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1429 # assert b == "Ab_C -Ab0C Ab\nC"
1431 if length
== 0 then return
1432 var c
= self[0].to_upper
1435 for i
in [1 .. length
[ do
1438 if prev
.is_letter
then
1439 self[i
] = c
.to_lower
1441 self[i
] = c
.to_upper
1448 if is_dirty
then hash_cache
= null
1452 # In Buffers, the internal sequence of character is mutable
1453 # Thus, `chars` can be used to modify the buffer.
1454 redef fun chars
: Sequence[Char] is abstract
1457 # Mutable strings of characters.
1462 redef type SELFTYPE: FlatBuffer
1464 redef var chars
: Sequence[Char] = new FlatBufferCharView(self)
1466 private var capacity
: Int = 0
1468 redef fun substrings
do return new FlatSubstringsIter(self)
1470 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1472 # This happens when an operation modifies the current `Buffer` and
1473 # the Copy-On-Write flag `written` is set at true.
1474 private fun reset
do
1475 var nns
= new NativeString(capacity
)
1476 items
.copy_to
(nns
, length
, 0, 0)
1484 assert index
< length
1488 redef fun []=(index
, item
)
1491 if index
== length
then
1495 if written
then reset
1496 assert index
>= 0 and index
< length
1503 if capacity
<= length
then enlarge
(length
+ 5)
1510 if written
then reset
1514 redef fun empty
do return new FlatBuffer
1516 redef fun enlarge
(cap
)
1519 if cap
<= c
then return
1520 while c
<= cap
do c
= c
* 2 + 2
1521 # The COW flag can be set at false here, since
1522 # it does a copy of the current `Buffer`
1524 var a
= new NativeString(c
+1)
1525 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1530 redef fun to_s
: String
1533 if length
== 0 then items
= new NativeString(1)
1534 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1537 redef fun to_cstring
1540 var new_native
= new NativeString(length
+ 1)
1541 new_native
[length
] = '\0'
1542 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1543 real_items
= new_native
1546 return real_items
.as(not null)
1549 # Create a new empty string.
1552 # Create a new string copied from `s`.
1555 capacity
= s
.length
+ 1
1557 items
= new NativeString(capacity
)
1558 if s
isa FlatString then
1559 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1560 else if s
isa FlatBuffer then
1561 s
.items
.copy_to
(items
, length
, 0, 0)
1564 for i
in [0..s
.length
[ do
1572 # Create a new empty string with a given capacity.
1573 init with_capacity
(cap
: Int)
1576 # _items = new NativeString.calloc(cap)
1577 items
= new NativeString(cap
+1)
1584 if s
.is_empty
then return
1587 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1588 if s
isa FlatString then
1589 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1590 else if s
isa FlatBuffer then
1591 s
.items
.copy_to
(items
, sl
, 0, length
)
1593 var curr_pos
= self.length
1594 for i
in [0..s
.length
[ do
1603 # Copies the content of self in `dest`
1604 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1606 var self_chars
= self.chars
1607 var dest_chars
= dest
.chars
1608 for i
in [0..len-1
] do
1609 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1613 redef fun substring
(from
, count
)
1617 if from
< 0 then from
= 0
1618 if count
> length
then count
= length
1619 if from
< count
then
1620 var r
= new FlatBuffer.with_capacity
(count
- from
)
1621 while from
< count
do
1622 r
.chars
.push
(items
[from
])
1627 return new FlatBuffer
1634 var ns
= new NativeString(capacity
)
1646 redef fun times
(repeats
)
1648 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1649 for i
in [1..repeats
[ do
1656 if written
then reset
1660 it
[id
] = it
[id
].to_upper
1667 if written
then reset
1671 it
[id
] = it
[id
].to_lower
1677 private class FlatBufferReverseIterator
1678 super IndexedIterator[Char]
1680 var target
: FlatBuffer
1682 var target_items
: NativeString
1686 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1689 if tgt
.length
> 0 then target_items
= tgt
.items
1693 redef fun index
do return curr_pos
1695 redef fun is_ok
do return curr_pos
>= 0
1697 redef fun item
do return target_items
[curr_pos
]
1699 redef fun next
do curr_pos
-= 1
1703 private class FlatBufferCharView
1704 super BufferCharView
1706 redef type SELFTYPE: FlatBuffer
1708 redef fun [](index
) do return target
.items
[index
]
1710 redef fun []=(index
, item
)
1712 assert index
>= 0 and index
<= length
1713 if index
== length
then
1717 target
.items
[index
] = item
1730 fun enlarge
(cap
: Int)
1737 var s_length
= s
.length
1738 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1741 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1743 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1747 private class FlatBufferIterator
1748 super IndexedIterator[Char]
1750 var target
: FlatBuffer
1752 var target_items
: NativeString
1756 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1759 if tgt
.length
> 0 then target_items
= tgt
.items
1763 redef fun index
do return curr_pos
1765 redef fun is_ok
do return curr_pos
< target
.length
1767 redef fun item
do return target_items
[curr_pos
]
1769 redef fun next
do curr_pos
+= 1
1773 ###############################################################################
1775 ###############################################################################
1778 # User readable representation of `self`.
1779 fun to_s
: String do return inspect
1781 # The class name of the object in NativeString format.
1782 private fun native_class_name
: NativeString is intern
1784 # The class name of the object.
1786 # assert 5.class_name == "Int"
1787 fun class_name
: String do return native_class_name
.to_s
1789 # Developer readable representation of `self`.
1790 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1793 return "<{inspect_head}>"
1796 # Return "CLASSNAME:#OBJECTID".
1797 # This function is mainly used with the redefinition of the inspect method
1798 protected fun inspect_head
: String
1800 return "{class_name}:#{object_id.to_hex}"
1805 # assert true.to_s == "true"
1806 # assert false.to_s == "false"
1819 # Wrapper of strerror C function
1820 private fun strerror_ext
: NativeString is extern `{
1821 return strerror(recv);
1824 # Returns a string describing error number
1825 fun strerror
: String do return strerror_ext
.to_s
1827 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1828 # assume < to_c max const of char
1829 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1836 else if self == 0 then
1843 var pos
= digit_count
(base
) - 1
1844 while pos
>= 0 and n
> 0 do
1845 s
.chars
[pos
] = (n
% base
).to_c
1851 # C function to convert an nit Int to a NativeString (char*)
1852 private fun native_int_to_s
: NativeString is extern "native_int_to_s"
1854 # return displayable int in base 10 and signed
1856 # assert 1.to_s == "1"
1857 # assert (-123).to_s == "-123"
1859 return native_int_to_s
.to_s
1862 # return displayable int in hexadecimal
1864 # assert 1.to_hex == "1"
1865 # assert (-255).to_hex == "-ff"
1866 fun to_hex
: String do return to_base
(16,false)
1868 # return displayable int in base base and signed
1869 fun to_base
(base
: Int, signed
: Bool): String
1871 var l
= digit_count
(base
)
1872 var s
= new FlatBuffer.from
(" " * l
)
1873 fill_buffer
(s
, base
, signed
)
1879 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1881 # assert 12.34.to_s == "12.34"
1882 # assert (-0120.030).to_s == "-120.03"
1884 # see `to_precision` for a custom precision.
1886 var str
= to_precision
( 3 )
1887 if is_inf
!= 0 or is_nan
then return str
1888 var len
= str
.length
1889 for i
in [0..len-1
] do
1891 var c
= str
.chars
[j
]
1894 else if c
== '.' then
1895 return str
.substring
( 0, j
+2 )
1897 return str
.substring
( 0, j
+1 )
1903 # `String` representation of `self` with the given number of `decimals`
1905 # assert 12.345.to_precision(0) == "12"
1906 # assert 12.345.to_precision(3) == "12.345"
1907 # assert (-12.345).to_precision(3) == "-12.345"
1908 # assert (-0.123).to_precision(3) == "-0.123"
1909 # assert 0.999.to_precision(2) == "1.00"
1910 # assert 0.999.to_precision(4) == "0.9990"
1911 fun to_precision
(decimals
: Int): String
1913 if is_nan
then return "nan"
1915 var isinf
= self.is_inf
1918 else if isinf
== -1 then
1922 if decimals
== 0 then return self.to_i
.to_s
1924 for i
in [0..decimals
[ do f
= f
* 10.0
1931 if i
== 0 then return "0." + "0"*decimals
1933 # Prepare both parts of the float, before and after the "."
1938 if sl
> decimals
then
1939 # Has something before the "."
1940 p1
= s
.substring
(0, sl-decimals
)
1941 p2
= s
.substring
(sl-decimals
, decimals
)
1944 p2
= "0"*(decimals-sl
) + s
1947 if i
< 0 then p1
= "-" + p1
1949 return p1
+ "." + p2
1952 # `self` representation with `nb` digits after the '.'.
1954 # assert 12.345.to_precision_native(1) == "12.3"
1955 # assert 12.345.to_precision_native(2) == "12.35"
1956 # assert 12.345.to_precision_native(3) == "12.345"
1957 # assert 12.345.to_precision_native(4) == "12.3450"
1958 fun to_precision_native
(nb
: Int): String import NativeString.to_s
`{
1962 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1963 str = malloc(size + 1);
1964 sprintf(str, "%.*f", (int)nb, recv );
1966 return NativeString_to_s( str );
1971 # assert 'x'.to_s == "x"
1974 var s
= new FlatBuffer.with_capacity
(1)
1979 # Returns true if the char is a numerical digit
1981 # assert '0'.is_numeric
1982 # assert '9'.is_numeric
1983 # assert not 'a'.is_numeric
1984 # assert not '?'.is_numeric
1985 fun is_numeric
: Bool
1987 return self >= '0' and self <= '9'
1990 # Returns true if the char is an alpha digit
1992 # assert 'a'.is_alpha
1993 # assert 'Z'.is_alpha
1994 # assert not '0'.is_alpha
1995 # assert not '?'.is_alpha
1998 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2001 # Returns true if the char is an alpha or a numeric digit
2003 # assert 'a'.is_alphanumeric
2004 # assert 'Z'.is_alphanumeric
2005 # assert '0'.is_alphanumeric
2006 # assert '9'.is_alphanumeric
2007 # assert not '?'.is_alphanumeric
2008 fun is_alphanumeric
: Bool
2010 return self.is_numeric
or self.is_alpha
2014 redef class Collection[E
]
2015 # Concatenate elements.
2018 var s
= new FlatBuffer
2019 for e
in self do if e
!= null then s
.append
(e
.to_s
)
2023 # Concatenate and separate each elements with `sep`.
2025 # assert [1, 2, 3].join(":") == "1:2:3"
2026 # assert [1..3].join(":") == "1:2:3"
2027 fun join
(sep
: Text): String
2029 if is_empty
then return ""
2031 var s
= new FlatBuffer # Result
2036 if e
!= null then s
.append
(e
.to_s
)
2038 # Concat other items
2043 if e
!= null then s
.append
(e
.to_s
)
2050 redef class Array[E
]
2052 # Fast implementation
2056 if l
== 0 then return ""
2057 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
2059 var na
= new NativeArray[String](l
)
2065 if itsi
== null then
2075 var ns
= new NativeString(sl
+ 1)
2081 var tpl
= tmp
.length
2082 if tmp
isa FlatString then
2083 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2086 for j
in tmp
.substrings
do
2087 var s
= j
.as(FlatString)
2089 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2095 return ns
.to_s_with_length
(sl
)
2099 redef class Map[K
,V
]
2100 # Concatenate couple of 'key value'.
2101 # key and value are separated by `couple_sep`.
2102 # each couple is separated each couple with `sep`.
2104 # var m = new ArrayMap[Int, String]
2107 # assert m.join("; ", "=") == "1=one; 10=ten"
2108 fun join
(sep
: String, couple_sep
: String): String
2110 if is_empty
then return ""
2112 var s
= new FlatBuffer # Result
2118 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2120 # Concat other items
2126 s
.append
("{k}{couple_sep}{e or else "<null>"}")
2133 ###############################################################################
2135 ###############################################################################
2137 # Native strings are simple C char *
2138 extern class NativeString `{ char* `}
2139 # Creates a new NativeString with a capacity of `length
`
2140 new(length: Int) is intern
2142 # Get char at `index
`.
2143 fun [](index: Int): Char is intern
2145 # Set char `item
` at index.
2146 fun []=(index: Int, item: Char) is intern
2148 # Copy `self` to `dest
`.
2149 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2151 # Position of the first nul character.
2152 fun cstring_length: Int
2155 while self[l] != '\0' do l += 1
2159 # Parse `self` as an Int.
2160 fun atoi: Int is intern
2162 # Parse `self` as a Float.
2163 fun atof: Float is extern "atof"
2167 return to_s_with_length(cstring_length)
2170 # Returns `self` as a String of `length
`.
2171 fun to_s_with_length(length: Int): FlatString
2174 var str = new FlatString.with_infos(self, length, 0, length - 1)
2178 # Returns `self` as a new String.
2179 fun to_s_with_copy: FlatString
2181 var length = cstring_length
2182 var new_self = new NativeString(length + 1)
2183 copy_to(new_self, length, 0, 0)
2184 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2185 new_self[length] = '\0'
2186 str.real_items = new_self
2192 private var args_cache: nullable Sequence[String]
2194 # The arguments of the program as given by the OS
2195 fun program_args: Sequence[String]
2197 if _args_cache == null then init_args
2198 return _args_cache.as(not null)
2201 # The name of the program as given by the OS
2202 fun program_name: String
2204 return native_argv(0).to_s
2207 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2208 private fun init_args
2210 var argc = native_argc
2211 var args = new Array[String].with_capacity(0)
2214 args[i-1] = native_argv(i).to_s
2220 # First argument of the main C function.
2221 private fun native_argc: Int is intern
2223 # Second argument of the main C function.
2224 private fun native_argv(i: Int): NativeString is intern
2227 # Comparator that efficienlty use `to_s
` to compare things
2229 # The comparaison call `to_s
` on object and use the result to order things.
2231 # var a = [1, 2, 3, 10, 20]
2232 # (new CachedAlphaComparator).sort(a)
2233 # assert a == [1, 10, 2, 20, 3]
2235 # Internally the result of `to_s
` is cached in a HashMap to counter
2236 # uneficient implementation of `to_s
`.
2238 # Note: it caching is not usefull, see `alpha_comparator
`
2239 class CachedAlphaComparator
2241 redef type COMPARED: Object
2243 private var cache = new HashMap[Object, String]
2245 private fun do_to_s(a: Object): String do
2246 if cache.has_key(a) then return cache[a]
2252 redef fun compare(a, b) do
2253 return do_to_s(a) <=> do_to_s(b)
2257 # see `alpha_comparator
`
2258 private class AlphaComparator
2260 redef fun compare(a, b) do return a.to_s <=> b.to_s
2263 # Stateless comparator that naively use `to_s
` to compare things.
2265 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2266 # on a single instace. See `CachedAlphaComparator` as an alternative.
2268 # var a = [1, 2, 3, 10, 20]
2269 # alpha_comparator.sort(a)
2270 # assert a == [1, 10, 2, 20, 3]
2271 fun alpha_comparator: Comparator do return once new AlphaComparator
2273 # The arguments of the program as given by the OS
2274 fun args: Sequence[String]
2276 return sys.program_args