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 # `Char::is_whitespace` determines what is a whitespace.
356 var iter
= self.chars
.iterator
358 if not iter
.item
.is_whitespace
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 # `Char::is_whitespace` determines what is a whitespace.
372 var iter
= self.chars
.reverse_iterator
374 if not iter
.item
.is_whitespace
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
383 # assert " Hello World ! ".trim == "Hello World !"
384 # assert "\na\nb\tc\t".trim == "a\nb\tc"
386 # `Char::is_whitespace` determines what is a whitespace.
387 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
389 # Is the string non-empty but only made of whitespaces?
391 # assert " \n\t ".is_whitespace == true
392 # assert " hello ".is_whitespace == false
393 # assert "".is_whitespace == false
395 # `Char::is_whitespace` determines what is a whitespace.
396 fun is_whitespace
: Bool
398 if is_empty
then return false
399 for c
in self.chars
do
400 if not c
.is_whitespace
then return false
405 # Returns `self` removed from its last line terminator (if any).
407 # assert "Hello\n".chomp == "Hello"
408 # assert "Hello".chomp == "Hello"
410 # assert "\n".chomp == ""
411 # assert "".chomp == ""
413 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
414 # A single line terminator, the last one, is removed.
416 # assert "\r\n".chomp == ""
417 # assert "\r\n\n".chomp == "\r\n"
418 # assert "\r\n\r\n".chomp == "\r\n"
419 # assert "\r\n\r".chomp == "\r\n"
421 # Note: unlike with most IO methods like `Reader::read_line`,
422 # a single `\r` is considered here to be a line terminator and will be removed.
426 if len
== 0 then return self
427 var l
= self.chars
.last
429 return substring
(0, len-1
)
430 else if l
!= '\n' then
432 else if len
> 1 and self.chars
[len-2
] == '\r' then
433 return substring
(0, len-2
)
435 return substring
(0, len-1
)
439 # Justify a self in a space of `length`
441 # `left` is the space ratio on the left side.
442 # * 0.0 for left-justified (no space at the left)
443 # * 1.0 for right-justified (all spaces at the left)
444 # * 0.5 for centered (half the spaces at the left)
448 # assert "hello".justify(10, 0.0) == "hello "
449 # assert "hello".justify(10, 1.0) == " hello"
450 # assert "hello".justify(10, 0.5) == " hello "
452 # If `length` is not enough, `self` is returned as is.
454 # assert "hello".justify(2, 0.0) == "hello"
456 # REQUIRE: `left >= 0.0 and left <= 1.0`
457 # ENSURE: `self.length <= length implies result.length == length`
458 # ENSURE: `self.length >= length implies result == self`
459 fun justify
(length
: Int, left
: Float): String
461 var diff
= length
- self.length
462 if diff
<= 0 then return to_s
463 assert left
>= 0.0 and left
<= 1.0
464 var before
= (diff
.to_f
* left
).to_i
465 return " " * before
+ self + " " * (diff-before
)
468 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
470 # This method is injective (two different inputs never produce the same
471 # output) and the returned string always respect the following rules:
473 # * Contains only US-ASCII letters, digits and underscores.
474 # * Never starts with a digit.
475 # * Never ends with an underscore.
476 # * Never contains two contiguous underscores.
478 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
479 # assert "__".to_cmangle == "_95d_95d"
480 # assert "__d".to_cmangle == "_95d_d"
481 # assert "_d_".to_cmangle == "_d_95d"
482 # assert "_42".to_cmangle == "_95d42"
483 # assert "foo".to_cmangle == "foo"
484 # assert "".to_cmangle == ""
485 fun to_cmangle
: String
487 if is_empty
then return ""
488 var res
= new FlatBuffer
489 var underscore
= false
493 if c
>= '0' and c
<= '9' then
495 res
.append
(c
.ascii
.to_s
)
499 for i
in [start
..length
[ do
501 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
507 res
.append
('_'.ascii
.to_s
)
510 if c
>= '0' and c
<= '9' then
513 else if c
== '_' then
518 res
.append
(c
.ascii
.to_s
)
524 res
.append
('_'.ascii
.to_s
)
530 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
532 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
533 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
535 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
536 # Three digits are always used to avoid following digits to be interpreted as an element
537 # of the octal sequence.
539 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
541 # The exceptions are the common `\t` and `\n`.
542 fun escape_to_c
: String
544 var b
= new FlatBuffer
545 for i
in [0..length
[ do
549 else if c
== '\t' then
551 else if c
== '\0' then
553 else if c
== '"' then
555 else if c == '\'' then
557 else if c == '\\
' then
559 else if c.ascii < 32 then
561 var oct = c.ascii.to_base(8, false)
562 # Force 3 octal digits since it is the
563 # maximum allowed in the C specification
564 if oct.length == 1 then
567 else if oct.length == 2 then
578 # Escape additionnal characters
579 # The result might no be legal in C but be used in other languages
581 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
582 fun escape_more_to_c(chars: String): String
584 var b = new FlatBuffer
585 for c in escape_to_c.chars do
586 if chars.chars.has(c) then
594 # Escape to C plus braces
596 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
597 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
599 # Escape to POSIX Shell (sh).
601 # Abort if the text contains a null byte.
603 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
604 fun escape_to_sh
: String do
605 var b
= new FlatBuffer
607 for i in [0..length[ do
612 assert without_null_byte
: c
!= '\0'
620 # Escape to include in a Makefile
622 # Unfortunately, some characters are not escapable in Makefile.
623 # These characters are `;`, `|`, `\`, and the non-printable ones.
624 # They will be rendered as `"?{hex}"`.
625 fun escape_to_mk: String do
626 var b = new FlatBuffer
627 for i in [0..length[ do
631 else if c == ':' or c == ' ' or c == '#' then
634 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
635 b
.append
("?{c.ascii.to_base(16, false)}")
643 # Return a string where Nit escape sequences are transformed.
646 # assert s.length == 2
647 # var u = s.unescape_nit
648 # assert u.length == 1
649 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
650 fun unescape_nit
: String
652 var res
= new FlatBuffer.with_capacity
(self.length
)
653 var was_slash
= false
654 for i
in [0..length
[ do
656 if not was_slash
then
667 else if c
== 'r' then
669 else if c
== 't' then
671 else if c
== '0' then
680 # Encode `self` to percent (or URL) encoding
682 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
683 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
684 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
685 fun to_percent_encoding
: String
687 var buf
= new FlatBuffer
689 for i
in [0..length
[ do
691 if (c
>= '0' and c
<= '9') or
692 (c
>= 'a' and c
<= 'z') or
693 (c
>= 'A' and c
<= 'Z') or
694 c
== '-' or c
== '.' or
698 else buf
.append
"%{c.ascii.to_hex}"
704 # Decode `self` from percent (or URL) encoding to a clear string
706 # Replace invalid use of '%' with '?'.
708 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
709 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
710 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
711 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
712 # assert "incomplete %".from_percent_encoding == "incomplete ?"
713 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
714 fun from_percent_encoding
: String
716 var buf
= new FlatBuffer
722 if i
+ 2 >= length
then
723 # What follows % has been cut off
727 var hex_s
= substring
(i
, 2)
729 var hex_i
= hex_s
.to_hex
733 # What follows a % is not Hex
746 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
748 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
750 # SEE: <https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.231_-_HTML_Escape_Before_Inserting_Untrusted_Data_into_HTML_Element_Content>
751 fun html_escape
: String
753 var buf
= new FlatBuffer
755 for i
in [0..length
[ do
759 else if c
== '<' then
761 else if c
== '>' then
763 else if c
== '"' then
765 else if c
== '\'' then
767 else if c == '/' then
776 # Two pieces of text are equals if thez have the same characters in the same order.
778 # assert "hello" == "hello"
779 # assert "hello" != "HELLO"
780 # assert "hello" == "hel"+"lo"
782 # Things that are not Text are not equal.
785 # assert "9" != ['9']
788 # assert "9".chars.first == '9' # equality of Char
789 # assert "9".chars == ['9'] # equality of Sequence
790 # assert "9".to_i == 9 # equality of Int
793 if o == null then return false
794 if not o isa Text then return false
795 if self.is_same_instance(o) then return true
796 if self.length != o.length then return false
797 return self.chars == o.chars
800 # Lexicographical comparaison
802 # assert "abc" < "xy"
803 # assert "ABC" < "abc"
806 var self_chars = self.chars.iterator
807 var other_chars = other.chars.iterator
809 while self_chars.is_ok and other_chars.is_ok do
810 if self_chars.item < other_chars.item then return true
811 if self_chars.item > other_chars.item then return false
816 if self_chars.is_ok then
823 # Escape string used in labels for graphviz
825 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
826 fun escape_to_dot: String
828 return escape_more_to_c("|\{\}<>")
831 # Flat representation of self
832 fun flatten: FlatText is abstract
834 private var hash_cache: nullable Int = null
838 if hash_cache == null then
839 # djb2 hash algorithm
842 for i in [0..length[ do
844 h = h.lshift(5) + h + char.ascii
849 return hash_cache.as(not null)
854 # All kinds of array-based text representations.
855 abstract class FlatText
858 # Underlying C-String (`char*`)
860 # Warning : Might be void in some subclasses, be sure to check
861 # if set before using it.
862 private var items: NativeString is noinit
864 # Real items, used as cache for to_cstring is called
865 private var real_items: nullable NativeString = null
867 # Returns a char* starting at position `index_from`
869 # WARNING: If you choose to use this service, be careful of the following.
871 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
872 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
873 # deallocated at any moment, rendering the pointer returned by this function invalid.
874 # Any access to freed memory may very likely cause undefined behaviour or a crash.
875 # (Failure to do so will most certainly result in long and painful debugging hours)
877 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
878 # then immediately return).
880 # As always, do not modify the content of the String in C code, if this is what you want
881 # copy locally the char* as Nit Strings are immutable.
882 private fun fast_cstring: NativeString is abstract
884 redef var length: Int = 0
895 redef fun flatten do return self
898 # Abstract class for the SequenceRead compatible
899 # views on String and Buffer objects
900 private abstract class StringCharView
901 super SequenceRead[Char]
907 redef fun is_empty do return target.is_empty
909 redef fun length do return target.length
911 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
913 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
916 # View on Buffer objects, extends Sequence
917 # for mutation operations
918 private abstract class BufferCharView
922 redef type SELFTYPE: Buffer
926 # A `String` holds and manipulates an arbitrary sequence of characters.
928 # String objects may be created using literals.
930 # assert "Hello World!" isa String
931 abstract class String
934 redef type SELFTYPE: String is fixed
936 redef fun to_s do return self
938 # Concatenates `o` to `self`
940 # assert "hello" + "world" == "helloworld"
941 # assert "" + "hello" + "" == "hello"
942 fun +(o: Text): SELFTYPE is abstract
944 # Concatenates self `i` times
946 # assert "abc" * 4 == "abcabcabcabc"
947 # assert "abc" * 1 == "abc"
948 # assert "abc" * 0 == ""
949 fun *(i: Int): SELFTYPE is abstract
951 # Insert `s` at `pos`.
953 # assert "helloworld".insert_at(" ", 5) == "hello world"
954 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
956 redef fun substrings: Iterator[String] is abstract
958 # Returns a reversed version of self
960 # assert "hello".reversed == "olleh"
961 # assert "bob".reversed == "bob"
962 # assert "".reversed == ""
963 fun reversed: SELFTYPE is abstract
965 # A upper case version of `self`
967 # assert "Hello World!".to_upper == "HELLO WORLD!"
968 fun to_upper: SELFTYPE is abstract
970 # A lower case version of `self`
972 # assert "Hello World!".to_lower == "hello world!"
973 fun to_lower : SELFTYPE is abstract
975 # Takes a camel case `self` and converts it to snake case
977 # assert "randomMethodId".to_snake_case == "random_method_id"
979 # The rules are the following:
981 # An uppercase is always converted to a lowercase
983 # assert "HELLO_WORLD".to_snake_case == "hello_world"
985 # An uppercase that follows a lowercase is prefixed with an underscore
987 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
989 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
991 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
993 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
995 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
996 fun to_snake_case: SELFTYPE
998 if self.is_lower then return self
1000 var new_str = new FlatBuffer.with_capacity(self.length)
1001 var prev_is_lower = false
1002 var prev_is_upper = false
1004 for i in [0..length[ do
1006 if char.is_lower then
1008 prev_is_lower = true
1009 prev_is_upper = false
1010 else if char.is_upper then
1011 if prev_is_lower then
1013 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1016 new_str.add(char.to_lower)
1017 prev_is_lower = false
1018 prev_is_upper = true
1021 prev_is_lower = false
1022 prev_is_upper = false
1029 # Takes a snake case `self` and converts it to camel case
1031 # assert "random_method_id".to_camel_case == "randomMethodId"
1033 # If the identifier is prefixed by an underscore, the underscore is ignored
1035 # assert "_private_field".to_camel_case == "_privateField"
1037 # If `self` is upper, it is returned unchanged
1039 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1041 # If there are several consecutive underscores, they are considered as a single one
1043 # assert "random__method_id".to_camel_case == "randomMethodId"
1044 fun to_camel_case: SELFTYPE
1046 if self.is_upper then return self
1048 var new_str = new FlatBuffer
1049 var is_first_char = true
1050 var follows_us = false
1052 for i in [0..length[ do
1054 if is_first_char then
1056 is_first_char = false
1057 else if char == '_
' then
1059 else if follows_us then
1060 new_str.add(char.to_upper)
1070 # Returns a capitalized `self`
1072 # Letters that follow a letter are lowercased
1073 # Letters that follow a non-letter are upcased.
1075 # SEE : `Char::is_letter` for the definition of letter.
1077 # assert "jAVASCRIPT".capitalized == "Javascript"
1078 # assert "i am root".capitalized == "I Am Root"
1079 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1080 fun capitalized: SELFTYPE do
1081 if length == 0 then return self
1083 var buf = new FlatBuffer.with_capacity(length)
1085 var curr = chars[0].to_upper
1089 for i in [1 .. length[ do
1092 if prev.is_letter then
1093 buf[i] = curr.to_lower
1095 buf[i] = curr.to_upper
1103 private class FlatSubstringsIter
1104 super Iterator[FlatText]
1106 var tgt: nullable FlatText
1110 return tgt.as(not null)
1113 redef fun is_ok do return tgt != null
1115 redef fun next do tgt = null
1118 # Immutable strings of characters.
1123 # Index in _items of the start of the string
1124 private var index_from: Int is noinit
1126 # Indes in _items of the last item of the string
1127 private var index_to: Int is noinit
1129 redef var chars: SequenceRead[Char] = new FlatStringCharView(self) is lazy
1133 # Check that the index (+ index_from) is not larger than indexTo
1134 # In other terms, if the index is valid
1136 assert (index + index_from) <= index_to
1137 return items[index + index_from]
1140 ################################################
1141 # AbstractString specific methods #
1142 ################################################
1146 var native = new NativeString(self.length + 1)
1147 var length = self.length
1148 var items = self.items
1151 while pos < length do
1152 native[pos] = items[ipos]
1156 return native.to_s_with_length(self.length)
1159 redef fun fast_cstring do return items.fast_cstring(index_from)
1161 redef fun substring(from, count)
1167 if count < 0 then count = 0
1171 var new_from = index_from + from
1173 if (new_from + count) > index_to then
1174 var new_len = index_to - new_from + 1
1175 if new_len <= 0 then return empty
1176 return new FlatString.with_infos(items, new_len, new_from, index_to)
1179 if count <= 0 then return empty
1181 var to = new_from + count - 1
1183 return new FlatString.with_infos(items, to - new_from + 1, new_from, to)
1186 redef fun empty do return "".as(FlatString)
1190 var outstr = new NativeString(self.length + 1)
1193 var myitems = self.items
1194 var index_from = self.index_from
1195 var max = self.index_to
1197 while index_from <= max do
1198 outstr[out_index] = myitems[index_from].to_upper
1203 outstr[self.length] = '\
0'
1205 return outstr.to_s_with_length(self.length)
1210 var outstr = new NativeString(self.length + 1)
1213 var myitems = self.items
1214 var index_from = self.index_from
1215 var max = self.index_to
1217 while index_from <= max do
1218 outstr[out_index] = myitems[index_from].to_lower
1223 outstr[self.length] = '\
0'
1225 return outstr.to_s_with_length(self.length)
1230 var i = self.index_from
1231 var imax = self.index_to
1238 ##################################################
1239 # String Specific Methods #
1240 ##################################################
1242 # Low-level creation of a new string with given data.
1244 # `items` will be used as is, without copy, to retrieve the characters of the string.
1245 # Aliasing issues is the responsibility of the caller.
1246 private init with_infos(items: NativeString, length: Int, from: Int, to: Int)
1249 self.length = length
1254 redef fun to_cstring: NativeString
1256 if real_items != null then
1257 return real_items.as(not null)
1259 var newItems = new NativeString(length + 1)
1260 self.items.copy_to(newItems, length, index_from, 0)
1261 newItems[length] = '\
0'
1262 self.real_items = newItems
1269 if not other isa FlatString then return super
1271 if self.object_id == other.object_id then return true
1273 var my_length = length
1275 if other.length != my_length then return false
1277 var my_index = index_from
1278 var its_index = other.index_from
1280 var last_iteration = my_index + my_length
1282 var itsitems = other.items
1283 var myitems = self.items
1285 while my_index < last_iteration do
1286 if myitems[my_index] != itsitems[its_index] then return false
1296 if not other isa FlatString then return super
1298 if self.object_id == other.object_id then return false
1300 var my_curr_char : Char
1301 var its_curr_char : Char
1303 var curr_id_self = self.index_from
1304 var curr_id_other = other.index_from
1306 var my_items = self.items
1307 var its_items = other.items
1309 var my_length = self.length
1310 var its_length = other.length
1312 var max_iterations = curr_id_self + my_length
1314 while curr_id_self < max_iterations do
1315 my_curr_char = my_items[curr_id_self]
1316 its_curr_char = its_items[curr_id_other]
1318 if my_curr_char != its_curr_char then
1319 if my_curr_char < its_curr_char then return true
1327 return my_length < its_length
1332 var my_length = self.length
1333 var its_length = s.length
1335 var total_length = my_length + its_length
1337 var target_string = new NativeString(my_length + its_length + 1)
1339 self.items.copy_to(target_string, my_length, index_from, 0)
1340 if s isa FlatString then
1341 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1342 else if s isa FlatBuffer then
1343 s.items.copy_to(target_string, its_length, 0, my_length)
1345 var curr_pos = my_length
1346 for i in [0..s.length[ do
1348 target_string[curr_pos] = c
1353 target_string[total_length] = '\
0'
1355 return target_string.to_s_with_length(total_length)
1362 var my_length = self.length
1364 var final_length = my_length * i
1366 var my_items = self.items
1368 var target_string = new NativeString(final_length + 1)
1370 target_string[final_length] = '\
0'
1372 var current_last = 0
1374 for iteration in [1 .. i] do
1375 my_items.copy_to(target_string, my_length, 0, current_last)
1376 current_last += my_length
1379 return target_string.to_s_with_length(final_length)
1384 if hash_cache == null then
1385 # djb2 hash algorithm
1391 while i <= index_to do
1392 h = h.lshift(5) + h + myitems[i].ascii
1399 return hash_cache.as(not null)
1402 redef fun substrings do return new FlatSubstringsIter(self)
1405 private class FlatStringReverseIterator
1406 super IndexedIterator[Char]
1408 var target: FlatString
1410 var target_items: NativeString
1414 init with_pos(tgt: FlatString, pos: Int)
1417 target_items = tgt.items
1418 curr_pos = pos + tgt.index_from
1421 redef fun is_ok do return curr_pos >= target.index_from
1423 redef fun item do return target_items[curr_pos]
1425 redef fun next do curr_pos -= 1
1427 redef fun index do return curr_pos - target.index_from
1431 private class FlatStringIterator
1432 super IndexedIterator[Char]
1434 var target: FlatString
1436 var target_items: NativeString
1440 init with_pos(tgt: FlatString, pos: Int)
1443 target_items = tgt.items
1444 curr_pos = pos + target.index_from
1447 redef fun is_ok do return curr_pos <= target.index_to
1449 redef fun item do return target_items[curr_pos]
1451 redef fun next do curr_pos += 1
1453 redef fun index do return curr_pos - target.index_from
1457 private class FlatStringCharView
1458 super StringCharView
1460 redef type SELFTYPE: FlatString
1464 # Check that the index (+ index_from) is not larger than indexTo
1465 # In other terms, if the index is valid
1467 var target = self.target
1468 assert (index + target.index_from) <= target.index_to
1469 return target.items[index + target.index_from]
1472 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1474 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1478 # A mutable sequence of characters.
1479 abstract class Buffer
1482 redef type SELFTYPE: Buffer is fixed
1484 # Specific implementations MUST set this to `true` in order to invalidate caches
1485 protected var is_dirty = true
1487 # Copy-On-Write flag
1489 # If the `Buffer` was to_s'd
, the next in-place altering
1490 # operation will cause the current `Buffer` to be re-allocated.
1492 # The flag will then be set at `false`.
1493 protected var written
= false
1495 # Modifies the char contained at pos `index`
1497 # DEPRECATED : Use self.chars.[]= instead
1498 fun []=(index
: Int, item
: Char) is abstract
1500 # Adds a char `c` at the end of self
1502 # DEPRECATED : Use self.chars.add instead
1503 fun add
(c
: Char) is abstract
1507 # var b = new FlatBuffer
1509 # assert not b.is_empty
1512 fun clear
is abstract
1514 # Enlarges the subsequent array containing the chars of self
1515 fun enlarge
(cap
: Int) is abstract
1517 # Adds the content of text `s` at the end of self
1519 # var b = new FlatBuffer
1522 # assert b == "helloworld"
1523 fun append
(s
: Text) is abstract
1525 # `self` is appended in such a way that `self` is repeated `r` times
1527 # var b = new FlatBuffer
1530 # assert b == "hellohellohello"
1531 fun times
(r
: Int) is abstract
1533 # Reverses itself in-place
1535 # var b = new FlatBuffer
1538 # assert b == "olleh"
1539 fun reverse
is abstract
1541 # Changes each lower-case char in `self` by its upper-case variant
1543 # var b = new FlatBuffer
1544 # b.append("Hello World!")
1546 # assert b == "HELLO WORLD!"
1547 fun upper
is abstract
1549 # Changes each upper-case char in `self` by its lower-case variant
1551 # var b = new FlatBuffer
1552 # b.append("Hello World!")
1554 # assert b == "hello world!"
1555 fun lower
is abstract
1557 # Capitalizes each word in `self`
1559 # Letters that follow a letter are lowercased
1560 # Letters that follow a non-letter are upcased.
1562 # SEE: `Char::is_letter` for the definition of a letter.
1564 # var b = new FlatBuffer.from("jAVAsCriPt")
1566 # assert b == "Javascript"
1567 # b = new FlatBuffer.from("i am root")
1569 # assert b == "I Am Root"
1570 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1572 # assert b == "Ab_C -Ab0C Ab\nC"
1574 if length
== 0 then return
1575 var c
= self[0].to_upper
1578 for i
in [1 .. length
[ do
1581 if prev
.is_letter
then
1582 self[i
] = c
.to_lower
1584 self[i
] = c
.to_upper
1591 if is_dirty
then hash_cache
= null
1595 # In Buffers, the internal sequence of character is mutable
1596 # Thus, `chars` can be used to modify the buffer.
1597 redef fun chars
: Sequence[Char] is abstract
1600 # Mutable strings of characters.
1605 redef var chars
: Sequence[Char] = new FlatBufferCharView(self) is lazy
1607 private var capacity
: Int = 0
1609 redef fun fast_cstring
do return items
.fast_cstring
(0)
1611 redef fun substrings
do return new FlatSubstringsIter(self)
1613 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1615 # This happens when an operation modifies the current `Buffer` and
1616 # the Copy-On-Write flag `written` is set at true.
1617 private fun reset
do
1618 var nns
= new NativeString(capacity
)
1619 items
.copy_to
(nns
, length
, 0, 0)
1627 assert index
< length
1631 redef fun []=(index
, item
)
1634 if index
== length
then
1638 if written
then reset
1639 assert index
>= 0 and index
< length
1646 if capacity
<= length
then enlarge
(length
+ 5)
1653 if written
then reset
1657 redef fun empty
do return new FlatBuffer
1659 redef fun enlarge
(cap
)
1662 if cap
<= c
then return
1663 while c
<= cap
do c
= c
* 2 + 2
1664 # The COW flag can be set at false here, since
1665 # it does a copy of the current `Buffer`
1667 var a
= new NativeString(c
+1)
1668 if length
> 0 then items
.copy_to
(a
, length
, 0, 0)
1673 redef fun to_s
: String
1676 if length
== 0 then items
= new NativeString(1)
1677 return new FlatString.with_infos
(items
, length
, 0, length
- 1)
1680 redef fun to_cstring
1683 var new_native
= new NativeString(length
+ 1)
1684 new_native
[length
] = '\0'
1685 if length
> 0 then items
.copy_to
(new_native
, length
, 0, 0)
1686 real_items
= new_native
1689 return real_items
.as(not null)
1692 # Create a new empty string.
1695 # Low-level creation a new buffer with given data.
1697 # `items` will be used as is, without copy, to store the characters of the buffer.
1698 # Aliasing issues is the responsibility of the caller.
1700 # If `items` is shared, `written` should be set to true after the creation
1701 # so that a modification will do a copy-on-write.
1702 private init with_infos
(items
: NativeString, capacity
, length
: Int)
1705 self.length
= length
1706 self.capacity
= capacity
1709 # Create a new string copied from `s`.
1712 capacity
= s
.length
+ 1
1714 items
= new NativeString(capacity
)
1715 if s
isa FlatString then
1716 s
.items
.copy_to
(items
, length
, s
.index_from
, 0)
1717 else if s
isa FlatBuffer then
1718 s
.items
.copy_to
(items
, length
, 0, 0)
1721 for i
in [0..s
.length
[ do
1729 # Create a new empty string with a given capacity.
1730 init with_capacity
(cap
: Int)
1733 items
= new NativeString(cap
+1)
1740 if s
.is_empty
then return
1743 if capacity
< length
+ sl
then enlarge
(length
+ sl
)
1744 if s
isa FlatString then
1745 s
.items
.copy_to
(items
, sl
, s
.index_from
, length
)
1746 else if s
isa FlatBuffer then
1747 s
.items
.copy_to
(items
, sl
, 0, length
)
1749 var curr_pos
= self.length
1750 for i
in [0..s
.length
[ do
1759 # Copies the content of self in `dest`
1760 fun copy
(start
: Int, len
: Int, dest
: Buffer, new_start
: Int)
1762 var self_chars
= self.chars
1763 var dest_chars
= dest
.chars
1764 for i
in [0..len-1
] do
1765 dest_chars
[new_start
+i
] = self_chars
[start
+i
]
1769 redef fun substring
(from
, count
)
1773 if from
< 0 then from
= 0
1774 if count
> length
then count
= length
1775 if from
< count
then
1776 var len
= count
- from
1777 var r_items
= new NativeString(len
)
1778 items
.copy_to
(r_items
, len
, from
, 0)
1779 var r
= new FlatBuffer.with_infos
(r_items
, len
, len
)
1782 return new FlatBuffer
1789 var ns
= new NativeString(capacity
)
1801 redef fun times
(repeats
)
1803 var x
= new FlatString.with_infos
(items
, length
, 0, length
- 1)
1804 for i
in [1..repeats
[ do
1811 if written
then reset
1815 it
[id
] = it
[id
].to_upper
1822 if written
then reset
1826 it
[id
] = it
[id
].to_lower
1832 private class FlatBufferReverseIterator
1833 super IndexedIterator[Char]
1835 var target
: FlatBuffer
1837 var target_items
: NativeString
1841 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1844 if tgt
.length
> 0 then target_items
= tgt
.items
1848 redef fun index
do return curr_pos
1850 redef fun is_ok
do return curr_pos
>= 0
1852 redef fun item
do return target_items
[curr_pos
]
1854 redef fun next
do curr_pos
-= 1
1858 private class FlatBufferCharView
1859 super BufferCharView
1861 redef type SELFTYPE: FlatBuffer
1863 redef fun [](index
) do return target
.items
[index
]
1865 redef fun []=(index
, item
)
1867 assert index
>= 0 and index
<= length
1868 if index
== length
then
1872 target
.items
[index
] = item
1885 fun enlarge
(cap
: Int)
1892 var s_length
= s
.length
1893 if target
.capacity
< s
.length
then enlarge
(s_length
+ target
.length
)
1896 redef fun iterator_from
(pos
) do return new FlatBufferIterator.with_pos
(target
, pos
)
1898 redef fun reverse_iterator_from
(pos
) do return new FlatBufferReverseIterator.with_pos
(target
, pos
)
1902 private class FlatBufferIterator
1903 super IndexedIterator[Char]
1905 var target
: FlatBuffer
1907 var target_items
: NativeString
1911 init with_pos
(tgt
: FlatBuffer, pos
: Int)
1914 if tgt
.length
> 0 then target_items
= tgt
.items
1918 redef fun index
do return curr_pos
1920 redef fun is_ok
do return curr_pos
< target
.length
1922 redef fun item
do return target_items
[curr_pos
]
1924 redef fun next
do curr_pos
+= 1
1928 ###############################################################################
1930 ###############################################################################
1933 # User readable representation of `self`.
1934 fun to_s
: String do return inspect
1936 # The class name of the object in NativeString format.
1937 private fun native_class_name
: NativeString is intern
1939 # The class name of the object.
1941 # assert 5.class_name == "Int"
1942 fun class_name
: String do return native_class_name
.to_s
1944 # Developer readable representation of `self`.
1945 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1948 return "<{inspect_head}>"
1951 # Return "CLASSNAME:#OBJECTID".
1952 # This function is mainly used with the redefinition of the inspect method
1953 protected fun inspect_head
: String
1955 return "{class_name}:#{object_id.to_hex}"
1960 # assert true.to_s == "true"
1961 # assert false.to_s == "false"
1974 # Wrapper of strerror C function
1975 private fun strerror_ext
: NativeString is extern "strerror"
1977 # Returns a string describing error number
1978 fun strerror
: String do return strerror_ext
.to_s
1980 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1981 # assume < to_c max const of char
1982 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1989 else if self == 0 then
1996 var pos
= digit_count
(base
) - 1
1997 while pos
>= 0 and n
> 0 do
1998 s
.chars
[pos
] = (n
% base
).to_c
2004 # C function to calculate the length of the `NativeString` to receive `self`
2005 private fun int_to_s_len
: Int is extern "native_int_length_str"
2007 # C function to convert an nit Int to a NativeString (char*)
2008 private fun native_int_to_s
(nstr
: NativeString, strlen
: Int) is extern "native_int_to_s"
2010 # return displayable int in base 10 and signed
2012 # assert 1.to_s == "1"
2013 # assert (-123).to_s == "-123"
2015 # Fast case for common numbers
2016 if self == 0 then return "0"
2017 if self == 1 then return "1"
2019 var nslen
= int_to_s_len
2020 var ns
= new NativeString(nslen
+ 1)
2022 native_int_to_s
(ns
, nslen
+ 1)
2023 return ns
.to_s_with_length
(nslen
)
2026 # return displayable int in hexadecimal
2028 # assert 1.to_hex == "1"
2029 # assert (-255).to_hex == "-ff"
2030 fun to_hex
: String do return to_base
(16,false)
2032 # return displayable int in base base and signed
2033 fun to_base
(base
: Int, signed
: Bool): String
2035 var l
= digit_count
(base
)
2036 var s
= new FlatBuffer.from
(" " * l
)
2037 fill_buffer
(s
, base
, signed
)
2043 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
2045 # assert 12.34.to_s == "12.34"
2046 # assert (-0120.030).to_s == "-120.03"
2048 # see `to_precision` for a custom precision.
2050 var str
= to_precision
( 3 )
2051 if is_inf
!= 0 or is_nan
then return str
2052 var len
= str
.length
2053 for i
in [0..len-1
] do
2055 var c
= str
.chars
[j
]
2058 else if c
== '.' then
2059 return str
.substring
( 0, j
+2 )
2061 return str
.substring
( 0, j
+1 )
2067 # `String` representation of `self` with the given number of `decimals`
2069 # assert 12.345.to_precision(0) == "12"
2070 # assert 12.345.to_precision(3) == "12.345"
2071 # assert (-12.345).to_precision(3) == "-12.345"
2072 # assert (-0.123).to_precision(3) == "-0.123"
2073 # assert 0.999.to_precision(2) == "1.00"
2074 # assert 0.999.to_precision(4) == "0.9990"
2075 fun to_precision
(decimals
: Int): String
2077 if is_nan
then return "nan"
2079 var isinf
= self.is_inf
2082 else if isinf
== -1 then
2086 if decimals
== 0 then return self.to_i
.to_s
2088 for i
in [0..decimals
[ do f
= f
* 10.0
2095 if i
== 0 then return "0." + "0"*decimals
2097 # Prepare both parts of the float, before and after the "."
2102 if sl
> decimals
then
2103 # Has something before the "."
2104 p1
= s
.substring
(0, sl-decimals
)
2105 p2
= s
.substring
(sl-decimals
, decimals
)
2108 p2
= "0"*(decimals-sl
) + s
2111 if i
< 0 then p1
= "-" + p1
2113 return p1
+ "." + p2
2118 # assert 'x'.to_s == "x"
2121 var s
= new FlatBuffer.with_capacity
(1)
2126 # Returns true if the char is a numerical digit
2128 # assert '0'.is_numeric
2129 # assert '9'.is_numeric
2130 # assert not 'a'.is_numeric
2131 # assert not '?'.is_numeric
2132 fun is_numeric
: Bool
2134 return self >= '0' and self <= '9'
2137 # Returns true if the char is an alpha digit
2139 # assert 'a'.is_alpha
2140 # assert 'Z'.is_alpha
2141 # assert not '0'.is_alpha
2142 # assert not '?'.is_alpha
2145 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
2148 # Returns true if the char is an alpha or a numeric digit
2150 # assert 'a'.is_alphanumeric
2151 # assert 'Z'.is_alphanumeric
2152 # assert '0'.is_alphanumeric
2153 # assert '9'.is_alphanumeric
2154 # assert not '?'.is_alphanumeric
2155 fun is_alphanumeric
: Bool
2157 return self.is_numeric
or self.is_alpha
2161 redef class Collection[E
]
2162 # Concatenate elements.
2165 var s
= new FlatBuffer
2166 for e
in self do if e
!= null then s
.append
(e
.to_s
)
2170 # Concatenate and separate each elements with `sep`.
2172 # assert [1, 2, 3].join(":") == "1:2:3"
2173 # assert [1..3].join(":") == "1:2:3"
2174 fun join
(sep
: Text): String
2176 if is_empty
then return ""
2178 var s
= new FlatBuffer # Result
2183 if e
!= null then s
.append
(e
.to_s
)
2185 # Concat other items
2190 if e
!= null then s
.append
(e
.to_s
)
2197 redef class Array[E
]
2199 # Fast implementation
2203 if l
== 0 then return ""
2204 if l
== 1 then if self[0] == null then return "" else return self[0].to_s
2206 var na
= new NativeArray[String](l
)
2212 if itsi
== null then
2222 var ns
= new NativeString(sl
+ 1)
2228 var tpl
= tmp
.length
2229 if tmp
isa FlatString then
2230 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2233 for j
in tmp
.substrings
do
2234 var s
= j
.as(FlatString)
2236 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2242 return ns
.to_s_with_length
(sl
)
2246 redef class NativeArray[E
]
2247 # Join all the elements using `to_s`
2249 # REQUIRE: `self isa NativeArray[String]`
2250 # REQUIRE: all elements are initialized
2251 fun native_to_s
: String
2253 assert self isa NativeArray[String]
2264 var ns
= new NativeString(sl
+ 1)
2270 var tpl
= tmp
.length
2271 if tmp
isa FlatString then
2272 tmp
.items
.copy_to
(ns
, tpl
, tmp
.index_from
, off
)
2275 for j
in tmp
.substrings
do
2276 var s
= j
.as(FlatString)
2278 s
.items
.copy_to
(ns
, slen
, s
.index_from
, off
)
2284 return ns
.to_s_with_length
(sl
)
2288 redef class Map[K
,V
]
2289 # Concatenate couple of 'key value'.
2290 # key and value are separated by `couple_sep`.
2291 # each couple is separated each couple with `sep`.
2293 # var m = new ArrayMap[Int, String]
2296 # assert m.join("; ", "=") == "1=one; 10=ten"
2297 fun join
(sep
: String, couple_sep
: String): String
2299 if is_empty
then return ""
2301 var s
= new FlatBuffer # Result
2307 s
.append
("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2309 # Concat other items
2315 s
.append
("{k or else "<null>"}{couple_sep}{e or else "<null>"}")
2322 ###############################################################################
2324 ###############################################################################
2326 # Native strings are simple C char *
2327 extern class NativeString `{ char* `}
2328 # Creates a new NativeString with a capacity of `length
`
2329 new(length: Int) is intern
2331 # Returns a char* starting at `index
`.
2333 # WARNING: Unsafe for extern code, use only for temporary
2334 # pointer manipulation purposes (e.g. write to file or such)
2335 fun fast_cstring(index: Int): NativeString is intern
2337 # Get char at `index
`.
2338 fun [](index: Int): Char is intern
2340 # Set char `item
` at index.
2341 fun []=(index: Int, item: Char) is intern
2343 # Copy `self` to `dest
`.
2344 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2346 # Position of the first nul character.
2347 fun cstring_length: Int
2350 while self[l] != '\0' do l += 1
2354 # Parse `self` as an Int.
2355 fun atoi: Int is intern
2357 # Parse `self` as a Float.
2358 fun atof: Float is extern "atof"
2362 return to_s_with_length(cstring_length)
2365 # Returns `self` as a String of `length
`.
2366 fun to_s_with_length(length: Int): FlatString
2369 var str = new FlatString.with_infos(self, length, 0, length - 1)
2373 # Returns `self` as a new String.
2374 fun to_s_with_copy: FlatString
2376 var length = cstring_length
2377 var new_self = new NativeString(length + 1)
2378 copy_to(new_self, length, 0, 0)
2379 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2380 new_self[length] = '\0'
2381 str.real_items = new_self
2387 private var args_cache: nullable Sequence[String]
2389 # The arguments of the program as given by the OS
2390 fun program_args: Sequence[String]
2392 if _args_cache == null then init_args
2393 return _args_cache.as(not null)
2396 # The name of the program as given by the OS
2397 fun program_name: String
2399 return native_argv(0).to_s
2402 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
2403 private fun init_args
2405 var argc = native_argc
2406 var args = new Array[String].with_capacity(0)
2409 args[i-1] = native_argv(i).to_s
2415 # First argument of the main C function.
2416 private fun native_argc: Int is intern
2418 # Second argument of the main C function.
2419 private fun native_argv(i: Int): NativeString is intern
2422 # Comparator that efficienlty use `to_s
` to compare things
2424 # The comparaison call `to_s
` on object and use the result to order things.
2426 # var a = [1, 2, 3, 10, 20]
2427 # (new CachedAlphaComparator).sort(a)
2428 # assert a == [1, 10, 2, 20, 3]
2430 # Internally the result of `to_s
` is cached in a HashMap to counter
2431 # uneficient implementation of `to_s
`.
2433 # Note: it caching is not usefull, see `alpha_comparator
`
2434 class CachedAlphaComparator
2436 redef type COMPARED: Object
2438 private var cache = new HashMap[Object, String]
2440 private fun do_to_s(a: Object): String do
2441 if cache.has_key(a) then return cache[a]
2447 redef fun compare(a, b) do
2448 return do_to_s(a) <=> do_to_s(b)
2452 # see `alpha_comparator
`
2453 private class AlphaComparator
2455 redef fun compare(a, b) do return a.to_s <=> b.to_s
2458 # Stateless comparator that naively use `to_s
` to compare things.
2460 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
2461 # on a single instace. See `CachedAlphaComparator` as an alternative.
2463 # var a = [1, 2, 3, 10, 20]
2464 # alpha_comparator.sort(a)
2465 # assert a == [1, 10, 2, 20, 3]
2466 fun alpha_comparator: Comparator do return once new AlphaComparator
2468 # The arguments of the program as given by the OS
2469 fun args: Sequence[String]
2471 return sys.program_args