1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # This file is free software, which comes along with NIT. This software is
4 # distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
5 # without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
6 # PARTICULAR PURPOSE. You can modify it is you want, provided this header
7 # is kept unaltered, and a notification of the changes is added.
8 # You are allowed to redistribute it and sell it, alone or is a part of
11 # Abstract class for manipulation of sequences of characters
17 intrude import collection
::array
19 # High-level abstraction for all text representations
23 redef type OTHER: Text
25 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
28 # Gets a view on the chars of the Text object
30 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
31 fun chars
: SequenceRead[Char] is abstract
33 # Number of characters contained in self.
35 # assert "12345".length == 5
36 # assert "".length == 0
37 fun length
: Int is abstract
41 # assert "abcd".substring(1, 2) == "bc"
42 # assert "abcd".substring(-1, 2) == "a"
43 # assert "abcd".substring(1, 0) == ""
44 # assert "abcd".substring(2, 5) == "cd"
46 # A `from` index < 0 will be replaced by 0.
47 # Unless a `count` value is > 0 at the same time.
48 # In this case, `from += count` and `count -= from`.
49 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
51 # Iterates on the substrings of self if any
52 fun substrings
: Iterator[FlatText] is abstract
54 # Is the current Text empty (== "")
57 # assert not "foo".is_empty
58 fun is_empty
: Bool do return self.length
== 0
60 # Returns an empty Text of the right type
62 # This method is used internally to get the right
63 # implementation of an empty string.
64 protected fun empty
: SELFTYPE is abstract
66 # Gets the first char of the Text
68 # DEPRECATED : Use self.chars.first instead
69 fun first
: Char do return self.chars
[0]
71 # Access a character at `index` in the string.
73 # assert "abcd"[2] == 'c'
75 # DEPRECATED : Use self.chars.[] instead
76 fun [](index
: Int): Char do return self.chars
[index
]
78 # Gets the index of the first occurence of 'c'
80 # Returns -1 if not found
82 # DEPRECATED : Use self.chars.index_of instead
83 fun index_of
(c
: Char): Int
85 return index_of_from
(c
, 0)
88 # Gets the last char of self
90 # DEPRECATED : Use self.chars.last instead
91 fun last
: Char do return self.chars
[length-1
]
93 # Gets the index of the first occurence of ´c´ starting from ´pos´
95 # Returns -1 if not found
97 # DEPRECATED : Use self.chars.index_of_from instead
98 fun index_of_from
(c
: Char, pos
: Int): Int
100 var iter
= self.chars
.iterator_from
(pos
)
102 if iter
.item
== c
then return iter
.index
108 # Gets the last index of char ´c´
110 # Returns -1 if not found
112 # DEPRECATED : Use self.chars.last_index_of instead
113 fun last_index_of
(c
: Char): Int
115 return last_index_of_from
(c
, length
- 1)
118 # Return a null terminated char *
119 fun to_cstring
: NativeString is abstract
121 # The index of the last occurrence of an element starting from pos (in reverse order).
123 # var s = "/etc/bin/test/test.nit"
124 # assert s.last_index_of_from('/', s.length-1) == 13
125 # assert s.last_index_of_from('/', 12) == 8
127 # Returns -1 if not found
129 # DEPRECATED : Use self.chars.last_index_of_from instead
130 fun last_index_of_from
(item
: Char, pos
: Int): Int
132 var iter
= self.chars
.reverse_iterator_from
(pos
)
134 if iter
.item
== item
then return iter
.index
140 # Gets an iterator on the chars of self
142 # DEPRECATED : Use self.chars.iterator instead
143 fun iterator
: Iterator[Char]
145 return self.chars
.iterator
149 # Gets an Array containing the chars of self
151 # DEPRECATED : Use self.chars.to_a instead
152 fun to_a
: Array[Char] do return chars
.to_a
154 # Create a substring from `self` beginning at the `from` position
156 # assert "abcd".substring_from(1) == "bcd"
157 # assert "abcd".substring_from(-1) == "abcd"
158 # assert "abcd".substring_from(2) == "cd"
160 # As with substring, a `from` index < 0 will be replaced by 0
161 fun substring_from
(from
: Int): SELFTYPE
163 if from
>= self.length
then return empty
164 if from
< 0 then from
= 0
165 return substring
(from
, length
- from
)
168 # Does self have a substring `str` starting from position `pos`?
170 # assert "abcd".has_substring("bc",1) == true
171 # assert "abcd".has_substring("bc",2) == false
173 # Returns true iff all characters of `str` are presents
174 # at the expected index in `self.`
175 # The first character of `str` being at `pos`, the second
176 # character being at `pos+1` and so on...
178 # This means that all characters of `str` need to be inside `self`.
180 # assert "abcd".has_substring("xab", -1) == false
181 # assert "abcd".has_substring("cdx", 2) == false
183 # And that the empty string is always a valid substring.
185 # assert "abcd".has_substring("", 2) == true
186 # assert "abcd".has_substring("", 200) == true
187 fun has_substring
(str
: String, pos
: Int): Bool
189 if str
.is_empty
then return true
190 if pos
< 0 or pos
+ str
.length
> length
then return false
191 var myiter
= self.chars
.iterator_from
(pos
)
192 var itsiter
= str
.chars
.iterator
193 while myiter
.is_ok
and itsiter
.is_ok
do
194 if myiter
.item
!= itsiter
.item
then return false
198 if itsiter
.is_ok
then return false
202 # Is this string prefixed by `prefix`?
204 # assert "abcd".has_prefix("ab") == true
205 # assert "abcbc".has_prefix("bc") == false
206 # assert "ab".has_prefix("abcd") == false
207 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
209 # Is this string suffixed by `suffix`?
211 # assert "abcd".has_suffix("abc") == false
212 # assert "abcd".has_suffix("bcd") == true
213 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
215 # If `self` contains only digits, return the corresponding integer
217 # assert "123".to_i == 123
218 # assert "-1".to_i == -1
222 return to_s
.to_cstring
.atoi
225 # If `self` contains a float, return the corresponding float
227 # assert "123".to_f == 123.0
228 # assert "-1".to_f == -1.0
229 # assert "-1.2e-3".to_f == -0.0012
233 return to_s
.to_cstring
.atof
236 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
238 # assert "ff".to_hex == 255
239 fun to_hex
: Int do return a_to
(16)
241 # If `self` contains only digits <= '7', return the corresponding integer.
243 # assert "714".to_oct == 460
244 fun to_oct
: Int do return a_to
(8)
246 # If `self` contains only '0' et '1', return the corresponding integer.
248 # assert "101101".to_bin == 45
249 fun to_bin
: Int do return a_to
(2)
251 # If `self` contains only digits and letters, return the corresponding integer in a given base
253 # assert "120".a_to(3) == 15
254 fun a_to
(base
: Int) : Int
259 for j
in [0..length
[ do
281 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
283 # assert "123".is_numeric == true
284 # assert "1.2".is_numeric == true
285 # assert "1,2".is_numeric == true
286 # assert "1..2".is_numeric == false
289 var has_point_or_comma
= false
290 for i
in [0..length
[ do
292 if not c
.is_numeric
then
293 if (c
== '.' or c
== ',') and not has_point_or_comma
then
294 has_point_or_comma
= true
303 # Returns `true` if the string contains only Hex chars
305 # assert "048bf".is_hex == true
306 # assert "ABCDEF".is_hex == true
307 # assert "0G".is_hex == false
310 for i
in [0..length
[ do
312 if not (c
>= 'a' and c
<= 'f') and
313 not (c
>= 'A' and c
<= 'F') and
314 not (c
>= '0' and c
<= '9') then return false
319 # Are all letters in `self` upper-case ?
321 # assert "HELLO WORLD".is_upper == true
322 # assert "%$&%!".is_upper == true
323 # assert "hello world".is_upper == false
324 # assert "Hello World".is_upper == false
327 for i
in [0..length
[ do
329 if char
.is_lower
then return false
334 # Are all letters in `self` lower-case ?
336 # assert "hello world".is_lower == true
337 # assert "%$&%!".is_lower == true
338 # assert "Hello World".is_lower == false
341 for i
in [0..length
[ do
343 if char
.is_upper
then return false
348 # Removes the whitespaces at the beginning of self
350 # assert " \n\thello \n\t".l_trim == "hello \n\t"
352 # `Char::is_whitespace` determines what is a whitespace.
355 var iter
= self.chars
.iterator
357 if not iter
.item
.is_whitespace
then break
360 if iter
.index
== length
then return self.empty
361 return self.substring_from
(iter
.index
)
364 # Removes the whitespaces at the end of self
366 # assert " \n\thello \n\t".r_trim == " \n\thello"
368 # `Char::is_whitespace` determines what is a whitespace.
371 var iter
= self.chars
.reverse_iterator
373 if not iter
.item
.is_whitespace
then break
376 if iter
.index
< 0 then return self.empty
377 return self.substring
(0, iter
.index
+ 1)
380 # Trims trailing and preceding white spaces
382 # assert " Hello World ! ".trim == "Hello World !"
383 # assert "\na\nb\tc\t".trim == "a\nb\tc"
385 # `Char::is_whitespace` determines what is a whitespace.
386 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
388 # Is the string non-empty but only made of whitespaces?
390 # assert " \n\t ".is_whitespace == true
391 # assert " hello ".is_whitespace == false
392 # assert "".is_whitespace == false
394 # `Char::is_whitespace` determines what is a whitespace.
395 fun is_whitespace
: Bool
397 if is_empty
then return false
398 for c
in self.chars
do
399 if not c
.is_whitespace
then return false
404 # Returns `self` removed from its last line terminator (if any).
406 # assert "Hello\n".chomp == "Hello"
407 # assert "Hello".chomp == "Hello"
409 # assert "\n".chomp == ""
410 # assert "".chomp == ""
412 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
413 # A single line terminator, the last one, is removed.
415 # assert "\r\n".chomp == ""
416 # assert "\r\n\n".chomp == "\r\n"
417 # assert "\r\n\r\n".chomp == "\r\n"
418 # assert "\r\n\r".chomp == "\r\n"
420 # Note: unlike with most IO methods like `Reader::read_line`,
421 # a single `\r` is considered here to be a line terminator and will be removed.
425 if len
== 0 then return self
426 var l
= self.chars
.last
428 return substring
(0, len-1
)
429 else if l
!= '\n' then
431 else if len
> 1 and self.chars
[len-2
] == '\r' then
432 return substring
(0, len-2
)
434 return substring
(0, len-1
)
438 # Justify a self in a space of `length`
440 # `left` is the space ratio on the left side.
441 # * 0.0 for left-justified (no space at the left)
442 # * 1.0 for right-justified (all spaces at the left)
443 # * 0.5 for centered (half the spaces at the left)
447 # assert "hello".justify(10, 0.0) == "hello "
448 # assert "hello".justify(10, 1.0) == " hello"
449 # assert "hello".justify(10, 0.5) == " hello "
451 # If `length` is not enough, `self` is returned as is.
453 # assert "hello".justify(2, 0.0) == "hello"
455 # REQUIRE: `left >= 0.0 and left <= 1.0`
456 # ENSURE: `self.length <= length implies result.length == length`
457 # ENSURE: `self.length >= length implies result == self`
458 fun justify
(length
: Int, left
: Float): String
460 var diff
= length
- self.length
461 if diff
<= 0 then return to_s
462 assert left
>= 0.0 and left
<= 1.0
463 var before
= (diff
.to_f
* left
).to_i
464 return " " * before
+ self + " " * (diff-before
)
467 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
469 # This method is injective (two different inputs never produce the same
470 # output) and the returned string always respect the following rules:
472 # * Contains only US-ASCII letters, digits and underscores.
473 # * Never starts with a digit.
474 # * Never ends with an underscore.
475 # * Never contains two contiguous underscores.
477 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
478 # assert "__".to_cmangle == "_95d_95d"
479 # assert "__d".to_cmangle == "_95d_d"
480 # assert "_d_".to_cmangle == "_d_95d"
481 # assert "_42".to_cmangle == "_95d42"
482 # assert "foo".to_cmangle == "foo"
483 # assert "".to_cmangle == ""
484 fun to_cmangle
: String
486 if is_empty
then return ""
488 var underscore
= false
492 if c
>= '0' and c
<= '9' then
494 res
.append
(c
.ascii
.to_s
)
498 for i
in [start
..length
[ do
500 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
506 res
.append
('_'.ascii
.to_s
)
509 if c
>= '0' and c
<= '9' then
512 else if c
== '_' then
517 res
.append
(c
.ascii
.to_s
)
523 res
.append
('_'.ascii
.to_s
)
529 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
531 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
532 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
534 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
535 # Three digits are always used to avoid following digits to be interpreted as an element
536 # of the octal sequence.
538 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
540 # The exceptions are the common `\t` and `\n`.
541 fun escape_to_c
: String
544 for i
in [0..length
[ do
548 else if c
== '\t' then
550 else if c
== '\0' then
552 else if c
== '"' then
554 else if c == '\'' then
556 else if c == '\\
' then
558 else if c.ascii < 32 then
560 var oct = c.ascii.to_base(8, false)
561 # Force 3 octal digits since it is the
562 # maximum allowed in the C specification
563 if oct.length == 1 then
566 else if oct.length == 2 then
577 # Escape additionnal characters
578 # The result might no be legal in C but be used in other languages
580 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
581 fun escape_more_to_c(chars: String): String
584 for c in escape_to_c.chars do
585 if chars.chars.has(c) then
593 # Escape to C plus braces
595 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
596 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
598 # Escape to POSIX Shell (sh).
600 # Abort if the text contains a null byte.
602 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
603 fun escape_to_sh
: String do
606 for i in [0..length[ do
611 assert without_null_byte
: c
!= '\0'
619 # Escape to include in a Makefile
621 # Unfortunately, some characters are not escapable in Makefile.
622 # These characters are `;`, `|`, `\`, and the non-printable ones.
623 # They will be rendered as `"?{hex}"`.
624 fun escape_to_mk: String do
626 for i in [0..length[ do
630 else if c == ':' or c == ' ' or c == '#' then
633 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
634 b
.append
("?{c.ascii.to_base(16, false)}")
642 # Return a string where Nit escape sequences are transformed.
645 # assert s.length == 2
646 # var u = s.unescape_nit
647 # assert u.length == 1
648 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
649 fun unescape_nit
: String
651 var res
= new Buffer.with_cap
(self.length
)
652 var was_slash
= false
653 for i
in [0..length
[ do
655 if not was_slash
then
666 else if c
== 'r' then
668 else if c
== 't' then
670 else if c
== '0' then
679 # Encode `self` to percent (or URL) encoding
681 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
682 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
683 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
684 fun to_percent_encoding
: String
688 for i
in [0..length
[ do
690 if (c
>= '0' and c
<= '9') or
691 (c
>= 'a' and c
<= 'z') or
692 (c
>= 'A' and c
<= 'Z') or
693 c
== '-' or c
== '.' or
697 else buf
.append
"%{c.ascii.to_hex}"
703 # Decode `self` from percent (or URL) encoding to a clear string
705 # Replace invalid use of '%' with '?'.
707 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
708 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
709 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
710 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
711 # assert "incomplete %".from_percent_encoding == "incomplete ?"
712 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
713 fun from_percent_encoding
: String
721 if i
+ 2 >= length
then
722 # What follows % has been cut off
726 var hex_s
= substring
(i
, 2)
728 var hex_i
= hex_s
.to_hex
732 # What follows a % is not Hex
745 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
747 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
749 # 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>
750 fun html_escape
: String
754 for i
in [0..length
[ do
758 else if c
== '<' then
760 else if c
== '>' then
762 else if c
== '"' then
764 else if c
== '\'' then
766 else if c == '/' then
775 # Two pieces of text are equals if thez have the same characters in the same order.
777 # assert "hello" == "hello"
778 # assert "hello" != "HELLO"
779 # assert "hello" == "hel"+"lo"
781 # Things that are not Text are not equal.
784 # assert "9" != ['9']
787 # assert "9".chars.first == '9' # equality of Char
788 # assert "9".chars == ['9'] # equality of Sequence
789 # assert "9".to_i == 9 # equality of Int
792 if o == null then return false
793 if not o isa Text then return false
794 if self.is_same_instance(o) then return true
795 if self.length != o.length then return false
796 return self.chars == o.chars
799 # Lexicographical comparaison
801 # assert "abc" < "xy"
802 # assert "ABC" < "abc"
805 var self_chars = self.chars.iterator
806 var other_chars = other.chars.iterator
808 while self_chars.is_ok and other_chars.is_ok do
809 if self_chars.item < other_chars.item then return true
810 if self_chars.item > other_chars.item then return false
815 if self_chars.is_ok then
822 # Escape string used in labels for graphviz
824 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
825 fun escape_to_dot: String
827 return escape_more_to_c("|\{\}<>")
830 private var hash_cache: nullable Int = null
834 if hash_cache == null then
835 # djb2 hash algorithm
838 for i in [0..length[ do
840 h = h.lshift(5) + h + char.ascii
845 return hash_cache.as(not null)
848 # Gives the formatted string back as a Nit string with `args` in place
850 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
851 # assert "\\%1 This string".format("String") == "\\%1 This string"
852 fun format(args: Object...): String do
853 var s = new Array[Text]
857 # Skip escaped characters
858 if self[i] == '\\
' then
861 else if self[i] == '%' then
865 while i < length and self[i].is_numeric do
870 var ciph_len = fmt_end - ciph_st + 1
871 s.push substring(curr_st, fmt_st - curr_st)
872 s.push args[substring(ciph_st, ciph_len).to_i - 1].to_s
877 s.push substring(curr_st, length - curr_st)
881 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
883 # Basically a high-level synonym of NativeString::copy_to
885 # REQUIRE: `n` must be large enough to contain `len` bytes
887 # var ns = new NativeString(8)
888 # "Text is String".copy_to_native(ns, 8, 2, 0)
889 # assert ns.to_s_with_length(8) == "xt is St"
891 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
892 var mypos = src_offset
893 var itspos = dest_offset
895 dest[itspos] = self.chars[mypos]
904 # All kinds of array-based text representations.
905 abstract class FlatText
908 # Underlying C-String (`char*`)
910 # Warning : Might be void in some subclasses, be sure to check
911 # if set before using it.
912 private var items: NativeString is noinit
914 # Real items, used as cache for to_cstring is called
915 private var real_items: nullable NativeString = null
917 # Returns a char* starting at position `index_from`
919 # WARNING: If you choose to use this service, be careful of the following.
921 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
922 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
923 # deallocated at any moment, rendering the pointer returned by this function invalid.
924 # Any access to freed memory may very likely cause undefined behaviour or a crash.
925 # (Failure to do so will most certainly result in long and painful debugging hours)
927 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
928 # then immediately return).
930 # As always, do not modify the content of the String in C code, if this is what you want
931 # copy locally the char* as Nit Strings are immutable.
932 private fun fast_cstring: NativeString is abstract
945 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
946 items.copy_to(dest, n, src_offset, dest_offset)
950 # Abstract class for the SequenceRead compatible
951 # views on String and Buffer objects
952 private abstract class StringCharView
953 super SequenceRead[Char]
959 redef fun is_empty do return target.is_empty
961 redef fun length do return target.length
963 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
965 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
968 # Immutable sequence of characters.
970 # String objects may be created using literals.
972 # assert "Hello World!" isa String
973 abstract class String
976 redef type SELFTYPE: String is fixed
978 redef fun to_s do return self
980 # Concatenates `o` to `self`
982 # assert "hello" + "world" == "helloworld"
983 # assert "" + "hello" + "" == "hello"
984 fun +(o: Text): SELFTYPE is abstract
986 # Concatenates self `i` times
988 # assert "abc" * 4 == "abcabcabcabc"
989 # assert "abc" * 1 == "abc"
990 # assert "abc" * 0 == ""
991 fun *(i: Int): SELFTYPE is abstract
993 # Insert `s` at `pos`.
995 # assert "helloworld".insert_at(" ", 5) == "hello world"
996 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
998 redef fun substrings is abstract
1000 # Returns a reversed version of self
1002 # assert "hello".reversed == "olleh"
1003 # assert "bob".reversed == "bob"
1004 # assert "".reversed == ""
1005 fun reversed: SELFTYPE is abstract
1007 # A upper case version of `self`
1009 # assert "Hello World!".to_upper == "HELLO WORLD!"
1010 fun to_upper: SELFTYPE is abstract
1012 # A lower case version of `self`
1014 # assert "Hello World!".to_lower == "hello world!"
1015 fun to_lower : SELFTYPE is abstract
1017 # Takes a camel case `self` and converts it to snake case
1019 # assert "randomMethodId".to_snake_case == "random_method_id"
1021 # The rules are the following:
1023 # An uppercase is always converted to a lowercase
1025 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1027 # An uppercase that follows a lowercase is prefixed with an underscore
1029 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1031 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1033 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1035 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1037 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1038 fun to_snake_case: SELFTYPE
1040 if self.is_lower then return self
1042 var new_str = new Buffer.with_cap(self.length)
1043 var prev_is_lower = false
1044 var prev_is_upper = false
1046 for i in [0..length[ do
1048 if char.is_lower then
1050 prev_is_lower = true
1051 prev_is_upper = false
1052 else if char.is_upper then
1053 if prev_is_lower then
1055 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1058 new_str.add(char.to_lower)
1059 prev_is_lower = false
1060 prev_is_upper = true
1063 prev_is_lower = false
1064 prev_is_upper = false
1071 # Takes a snake case `self` and converts it to camel case
1073 # assert "random_method_id".to_camel_case == "randomMethodId"
1075 # If the identifier is prefixed by an underscore, the underscore is ignored
1077 # assert "_private_field".to_camel_case == "_privateField"
1079 # If `self` is upper, it is returned unchanged
1081 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1083 # If there are several consecutive underscores, they are considered as a single one
1085 # assert "random__method_id".to_camel_case == "randomMethodId"
1086 fun to_camel_case: SELFTYPE
1088 if self.is_upper then return self
1090 var new_str = new Buffer
1091 var is_first_char = true
1092 var follows_us = false
1094 for i in [0..length[ do
1096 if is_first_char then
1098 is_first_char = false
1099 else if char == '_
' then
1101 else if follows_us then
1102 new_str.add(char.to_upper)
1112 # Returns a capitalized `self`
1114 # Letters that follow a letter are lowercased
1115 # Letters that follow a non-letter are upcased.
1117 # SEE : `Char::is_letter` for the definition of letter.
1119 # assert "jAVASCRIPT".capitalized == "Javascript"
1120 # assert "i am root".capitalized == "I Am Root"
1121 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1122 fun capitalized: SELFTYPE do
1123 if length == 0 then return self
1125 var buf = new Buffer.with_cap(length)
1127 var curr = chars[0].to_upper
1131 for i in [1 .. length[ do
1134 if prev.is_letter then
1135 buf[i] = curr.to_lower
1137 buf[i] = curr.to_upper
1145 # A mutable sequence of characters.
1146 abstract class Buffer
1149 # Returns an arbitrary subclass of `Buffer` with default parameters
1152 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1153 new with_cap(i: Int) is abstract
1155 redef type SELFTYPE: Buffer is fixed
1157 # Specific implementations MUST set this to `true` in order to invalidate caches
1158 protected var is_dirty = true
1160 # Copy-On-Write flag
1162 # If the `Buffer` was to_s'd
, the next in-place altering
1163 # operation will cause the current `Buffer` to be re-allocated.
1165 # The flag will then be set at `false`.
1166 protected var written
= false
1168 # Modifies the char contained at pos `index`
1170 # DEPRECATED : Use self.chars.[]= instead
1171 fun []=(index
: Int, item
: Char) is abstract
1173 # Adds a char `c` at the end of self
1175 # DEPRECATED : Use self.chars.add instead
1176 fun add
(c
: Char) is abstract
1180 # var b = new Buffer
1182 # assert not b.is_empty
1185 fun clear
is abstract
1187 # Enlarges the subsequent array containing the chars of self
1188 fun enlarge
(cap
: Int) is abstract
1190 # Adds the content of text `s` at the end of self
1192 # var b = new Buffer
1195 # assert b == "helloworld"
1196 fun append
(s
: Text) is abstract
1198 # `self` is appended in such a way that `self` is repeated `r` times
1200 # var b = new Buffer
1203 # assert b == "hellohellohello"
1204 fun times
(r
: Int) is abstract
1206 # Reverses itself in-place
1208 # var b = new Buffer
1211 # assert b == "olleh"
1212 fun reverse
is abstract
1214 # Changes each lower-case char in `self` by its upper-case variant
1216 # var b = new Buffer
1217 # b.append("Hello World!")
1219 # assert b == "HELLO WORLD!"
1220 fun upper
is abstract
1222 # Changes each upper-case char in `self` by its lower-case variant
1224 # var b = new Buffer
1225 # b.append("Hello World!")
1227 # assert b == "hello world!"
1228 fun lower
is abstract
1230 # Capitalizes each word in `self`
1232 # Letters that follow a letter are lowercased
1233 # Letters that follow a non-letter are upcased.
1235 # SEE: `Char::is_letter` for the definition of a letter.
1237 # var b = new FlatBuffer.from("jAVAsCriPt")
1239 # assert b == "Javascript"
1240 # b = new FlatBuffer.from("i am root")
1242 # assert b == "I Am Root"
1243 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1245 # assert b == "Ab_C -Ab0C Ab\nC"
1247 if length
== 0 then return
1248 var c
= self[0].to_upper
1251 for i
in [1 .. length
[ do
1254 if prev
.is_letter
then
1255 self[i
] = c
.to_lower
1257 self[i
] = c
.to_upper
1264 if is_dirty
then hash_cache
= null
1268 # In Buffers, the internal sequence of character is mutable
1269 # Thus, `chars` can be used to modify the buffer.
1270 redef fun chars
: Sequence[Char] is abstract
1273 # View on Buffer objects, extends Sequence
1274 # for mutation operations
1275 private abstract class BufferCharView
1276 super StringCharView
1277 super Sequence[Char]
1279 redef type SELFTYPE: Buffer
1284 # User readable representation of `self`.
1285 fun to_s
: String do return inspect
1287 # The class name of the object in NativeString format.
1288 private fun native_class_name
: NativeString is intern
1290 # The class name of the object.
1292 # assert 5.class_name == "Int"
1293 fun class_name
: String do return native_class_name
.to_s
1295 # Developer readable representation of `self`.
1296 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1299 return "<{inspect_head}>"
1302 # Return "CLASSNAME:#OBJECTID".
1303 # This function is mainly used with the redefinition of the inspect method
1304 protected fun inspect_head
: String
1306 return "{class_name}:#{object_id.to_hex}"
1311 # assert true.to_s == "true"
1312 # assert false.to_s == "false"
1324 # C function to calculate the length of the `NativeString` to receive `self`
1325 private fun byte_to_s_len
: Int is extern "native_byte_length_str"
1327 # C function to convert an nit Int to a NativeString (char*)
1328 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) is extern "native_byte_to_s"
1330 # Displayable byte in its hexadecimal form (0x..)
1332 # assert 1.to_b.to_s == "0x01"
1333 # assert (-123).to_b.to_s == "0x85"
1335 var nslen
= byte_to_s_len
1336 var ns
= new NativeString(nslen
+ 1)
1338 native_byte_to_s
(ns
, nslen
+ 1)
1339 return ns
.to_s_with_length
(nslen
)
1345 # Wrapper of strerror C function
1346 private fun strerror_ext
: NativeString is extern "strerror"
1348 # Returns a string describing error number
1349 fun strerror
: String do return strerror_ext
.to_s
1351 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1352 # assume < to_c max const of char
1353 private fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
1360 else if self == 0 then
1367 var pos
= digit_count
(base
) - 1
1368 while pos
>= 0 and n
> 0 do
1369 s
.chars
[pos
] = (n
% base
).to_c
1375 # C function to calculate the length of the `NativeString` to receive `self`
1376 private fun int_to_s_len
: Int is extern "native_int_length_str"
1378 # C function to convert an nit Int to a NativeString (char*)
1379 private fun native_int_to_s
(nstr
: NativeString, strlen
: Int) is extern "native_int_to_s"
1381 # return displayable int in base base and signed
1382 fun to_base
(base
: Int, signed
: Bool): String is abstract
1384 # return displayable int in hexadecimal
1386 # assert 1.to_hex == "1"
1387 # assert (-255).to_hex == "-ff"
1388 fun to_hex
: String do return to_base
(16,false)
1392 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1394 # assert 12.34.to_s == "12.34"
1395 # assert (-0120.030).to_s == "-120.03"
1397 # see `to_precision` for a custom precision.
1399 var str
= to_precision
( 3 )
1400 if is_inf
!= 0 or is_nan
then return str
1401 var len
= str
.length
1402 for i
in [0..len-1
] do
1404 var c
= str
.chars
[j
]
1407 else if c
== '.' then
1408 return str
.substring
( 0, j
+2 )
1410 return str
.substring
( 0, j
+1 )
1416 # `String` representation of `self` with the given number of `decimals`
1418 # assert 12.345.to_precision(0) == "12"
1419 # assert 12.345.to_precision(3) == "12.345"
1420 # assert (-12.345).to_precision(3) == "-12.345"
1421 # assert (-0.123).to_precision(3) == "-0.123"
1422 # assert 0.999.to_precision(2) == "1.00"
1423 # assert 0.999.to_precision(4) == "0.9990"
1424 fun to_precision
(decimals
: Int): String
1426 if is_nan
then return "nan"
1428 var isinf
= self.is_inf
1431 else if isinf
== -1 then
1435 if decimals
== 0 then return self.to_i
.to_s
1437 for i
in [0..decimals
[ do f
= f
* 10.0
1444 if i
== 0 then return "0." + "0"*decimals
1446 # Prepare both parts of the float, before and after the "."
1451 if sl
> decimals
then
1452 # Has something before the "."
1453 p1
= s
.substring
(0, sl-decimals
)
1454 p2
= s
.substring
(sl-decimals
, decimals
)
1457 p2
= "0"*(decimals-sl
) + s
1460 if i
< 0 then p1
= "-" + p1
1462 return p1
+ "." + p2
1467 # assert 'x'.to_s == "x"
1470 var s
= new Buffer.with_cap
(1)
1475 # Returns true if the char is a numerical digit
1477 # assert '0'.is_numeric
1478 # assert '9'.is_numeric
1479 # assert not 'a'.is_numeric
1480 # assert not '?'.is_numeric
1481 fun is_numeric
: Bool
1483 return self >= '0' and self <= '9'
1486 # Returns true if the char is an alpha digit
1488 # assert 'a'.is_alpha
1489 # assert 'Z'.is_alpha
1490 # assert not '0'.is_alpha
1491 # assert not '?'.is_alpha
1494 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1497 # Returns true if the char is an alpha or a numeric digit
1499 # assert 'a'.is_alphanumeric
1500 # assert 'Z'.is_alphanumeric
1501 # assert '0'.is_alphanumeric
1502 # assert '9'.is_alphanumeric
1503 # assert not '?'.is_alphanumeric
1504 fun is_alphanumeric
: Bool
1506 return self.is_numeric
or self.is_alpha
1510 redef class Collection[E
]
1511 # String representation of the content of the collection.
1513 # The standard representation is the list of elements separated with commas.
1516 # assert [1,2,3].to_s == "[1,2,3]"
1517 # assert [1..3].to_s == "[1,2,3]"
1518 # assert (new Array[Int]).to_s == "[]" # empty collection
1521 # Subclasses may return a more specific string representation.
1524 return "[" + join
(",") + "]"
1527 # Concatenate elements without separators
1530 # assert [1,2,3].plain_to_s == "123"
1531 # assert [11..13].plain_to_s == "111213"
1532 # assert (new Array[Int]).plain_to_s == "" # empty collection
1534 fun plain_to_s
: String
1537 for e
in self do if e
!= null then s
.append
(e
.to_s
)
1541 # Concatenate and separate each elements with `sep`.
1543 # assert [1, 2, 3].join(":") == "1:2:3"
1544 # assert [1..3].join(":") == "1:2:3"
1545 fun join
(sep
: Text): String
1547 if is_empty
then return ""
1549 var s
= new Buffer # Result
1554 if e
!= null then s
.append
(e
.to_s
)
1556 # Concat other items
1561 if e
!= null then s
.append
(e
.to_s
)
1568 redef class Map[K
,V
]
1569 # Concatenate couple of 'key value'.
1570 # key and value are separated by `couple_sep`.
1571 # each couple is separated each couple with `sep`.
1573 # var m = new ArrayMap[Int, String]
1576 # assert m.join("; ", "=") == "1=one; 10=ten"
1577 fun join
(sep
: String, couple_sep
: String): String is abstract
1581 private var args_cache
: nullable Sequence[String] = null
1583 # The arguments of the program as given by the OS
1584 fun program_args
: Sequence[String]
1586 if _args_cache
== null then init_args
1587 return _args_cache
.as(not null)
1590 # The name of the program as given by the OS
1591 fun program_name
: String
1593 return native_argv
(0).to_s
1596 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
1597 private fun init_args
1599 var argc
= native_argc
1600 var args
= new Array[String].with_capacity
(0)
1603 args
[i-1
] = native_argv
(i
).to_s
1609 # First argument of the main C function.
1610 private fun native_argc
: Int is intern
1612 # Second argument of the main C function.
1613 private fun native_argv
(i
: Int): NativeString is intern
1616 # Comparator that efficienlty use `to_s` to compare things
1618 # The comparaison call `to_s` on object and use the result to order things.
1620 # var a = [1, 2, 3, 10, 20]
1621 # (new CachedAlphaComparator).sort(a)
1622 # assert a == [1, 10, 2, 20, 3]
1624 # Internally the result of `to_s` is cached in a HashMap to counter
1625 # uneficient implementation of `to_s`.
1627 # Note: it caching is not usefull, see `alpha_comparator`
1628 class CachedAlphaComparator
1630 redef type COMPARED: Object
1632 private var cache
= new HashMap[Object, String]
1634 private fun do_to_s
(a
: Object): String do
1635 if cache
.has_key
(a
) then return cache
[a
]
1641 redef fun compare
(a
, b
) do
1642 return do_to_s
(a
) <=> do_to_s
(b
)
1646 # see `alpha_comparator`
1647 private class AlphaComparator
1649 redef fun compare
(a
, b
) do return a
.to_s
<=> b
.to_s
1652 # Stateless comparator that naively use `to_s` to compare things.
1654 # Note: the result of `to_s` is not cached, thus can be invoked a lot
1655 # on a single instace. See `CachedAlphaComparator` as an alternative.
1657 # var a = [1, 2, 3, 10, 20]
1658 # alpha_comparator.sort(a)
1659 # assert a == [1, 10, 2, 20, 3]
1660 fun alpha_comparator
: Comparator do return once
new AlphaComparator
1662 # The arguments of the program as given by the OS
1663 fun args
: Sequence[String]
1665 return sys
.program_args
1668 redef class NativeString
1669 # Returns `self` as a new String.
1670 fun to_s_with_copy
: String is abstract
1672 # Returns `self` as a String of `length`.
1673 fun to_s_with_length
(length
: Int): String is abstract
1676 redef class NativeArray[E
]
1677 # Join all the elements using `to_s`
1679 # REQUIRE: `self isa NativeArray[String]`
1680 # REQUIRE: all elements are initialized
1681 fun native_to_s
: String is abstract