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
25 # High-level abstraction for all text representations
29 redef type OTHER: Text
31 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
34 # Gets a view on the chars of the Text object
36 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
37 fun chars
: SequenceRead[Char] is abstract
39 # Number of characters contained in self.
41 # assert "12345".length == 5
42 # assert "".length == 0
43 fun length
: Int is abstract
47 # assert "abcd".substring(1, 2) == "bc"
48 # assert "abcd".substring(-1, 2) == "a"
49 # assert "abcd".substring(1, 0) == ""
50 # assert "abcd".substring(2, 5) == "cd"
52 # A `from` index < 0 will be replaced by 0.
53 # Unless a `count` value is > 0 at the same time.
54 # In this case, `from += count` and `count -= from`.
55 fun substring
(from
: Int, count
: Int): SELFTYPE is abstract
57 # Iterates on the substrings of self if any
58 fun substrings
: Iterator[FlatText] is abstract
60 # Is the current Text empty (== "")
63 # assert not "foo".is_empty
64 fun is_empty
: Bool do return self.length
== 0
66 # Returns an empty Text of the right type
68 # This method is used internally to get the right
69 # implementation of an empty string.
70 protected fun empty
: SELFTYPE is abstract
72 # Gets the first char of the Text
74 # DEPRECATED : Use self.chars.first instead
75 fun first
: Char do return self.chars
[0]
77 # Access a character at `index` in the string.
79 # assert "abcd"[2] == 'c'
81 # DEPRECATED : Use self.chars.[] instead
82 fun [](index
: Int): Char do return self.chars
[index
]
84 # Gets the index of the first occurence of 'c'
86 # Returns -1 if not found
88 # DEPRECATED : Use self.chars.index_of instead
89 fun index_of
(c
: Char): Int
91 return index_of_from
(c
, 0)
94 # Gets the last char of self
96 # DEPRECATED : Use self.chars.last instead
97 fun last
: Char do return self.chars
[length-1
]
99 # Gets the index of the first occurence of ´c´ starting from ´pos´
101 # Returns -1 if not found
103 # DEPRECATED : Use self.chars.index_of_from instead
104 fun index_of_from
(c
: Char, pos
: Int): Int
106 var iter
= self.chars
.iterator_from
(pos
)
108 if iter
.item
== c
then return iter
.index
114 # Gets the last index of char ´c´
116 # Returns -1 if not found
118 # DEPRECATED : Use self.chars.last_index_of instead
119 fun last_index_of
(c
: Char): Int
121 return last_index_of_from
(c
, length
- 1)
124 # Return a null terminated char *
125 fun to_cstring
: NativeString is abstract
127 # The index of the last occurrence of an element starting from pos (in reverse order).
129 # var s = "/etc/bin/test/test.nit"
130 # assert s.last_index_of_from('/', s.length-1) == 13
131 # assert s.last_index_of_from('/', 12) == 8
133 # Returns -1 if not found
135 # DEPRECATED : Use self.chars.last_index_of_from instead
136 fun last_index_of_from
(item
: Char, pos
: Int): Int
138 var iter
= self.chars
.reverse_iterator_from
(pos
)
140 if iter
.item
== item
then return iter
.index
146 # Gets an iterator on the chars of self
148 # DEPRECATED : Use self.chars.iterator instead
149 fun iterator
: Iterator[Char]
151 return self.chars
.iterator
155 # Gets an Array containing the chars of self
157 # DEPRECATED : Use self.chars.to_a instead
158 fun to_a
: Array[Char] do return chars
.to_a
160 # Create a substring from `self` beginning at the `from` position
162 # assert "abcd".substring_from(1) == "bcd"
163 # assert "abcd".substring_from(-1) == "abcd"
164 # assert "abcd".substring_from(2) == "cd"
166 # As with substring, a `from` index < 0 will be replaced by 0
167 fun substring_from
(from
: Int): SELFTYPE
169 if from
>= self.length
then return empty
170 if from
< 0 then from
= 0
171 return substring
(from
, length
- from
)
174 # Does self have a substring `str` starting from position `pos`?
176 # assert "abcd".has_substring("bc",1) == true
177 # assert "abcd".has_substring("bc",2) == false
179 # Returns true iff all characters of `str` are presents
180 # at the expected index in `self.`
181 # The first character of `str` being at `pos`, the second
182 # character being at `pos+1` and so on...
184 # This means that all characters of `str` need to be inside `self`.
186 # assert "abcd".has_substring("xab", -1) == false
187 # assert "abcd".has_substring("cdx", 2) == false
189 # And that the empty string is always a valid substring.
191 # assert "abcd".has_substring("", 2) == true
192 # assert "abcd".has_substring("", 200) == true
193 fun has_substring
(str
: String, pos
: Int): Bool
195 if str
.is_empty
then return true
196 if pos
< 0 or pos
+ str
.length
> length
then return false
197 var myiter
= self.chars
.iterator_from
(pos
)
198 var itsiter
= str
.chars
.iterator
199 while myiter
.is_ok
and itsiter
.is_ok
do
200 if myiter
.item
!= itsiter
.item
then return false
204 if itsiter
.is_ok
then return false
208 # Is this string prefixed by `prefix`?
210 # assert "abcd".has_prefix("ab") == true
211 # assert "abcbc".has_prefix("bc") == false
212 # assert "ab".has_prefix("abcd") == false
213 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
215 # Is this string suffixed by `suffix`?
217 # assert "abcd".has_suffix("abc") == false
218 # assert "abcd".has_suffix("bcd") == true
219 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
221 # If `self` contains only digits, return the corresponding integer
223 # assert "123".to_i == 123
224 # assert "-1".to_i == -1
228 return to_s
.to_cstring
.atoi
231 # If `self` contains a float, return the corresponding float
233 # assert "123".to_f == 123.0
234 # assert "-1".to_f == -1.0
235 # assert "-1.2e-3".to_f == -0.0012
239 return to_s
.to_cstring
.atof
242 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
244 # assert "ff".to_hex == 255
245 fun to_hex
: Int do return a_to
(16)
247 # If `self` contains only digits <= '7', return the corresponding integer.
249 # assert "714".to_oct == 460
250 fun to_oct
: Int do return a_to
(8)
252 # If `self` contains only '0' et '1', return the corresponding integer.
254 # assert "101101".to_bin == 45
255 fun to_bin
: Int do return a_to
(2)
257 # If `self` contains only digits and letters, return the corresponding integer in a given base
259 # assert "120".a_to(3) == 15
260 fun a_to
(base
: Int) : Int
265 for j
in [0..length
[ do
287 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
289 # assert "123".is_numeric == true
290 # assert "1.2".is_numeric == true
291 # assert "1,2".is_numeric == true
292 # assert "1..2".is_numeric == false
295 var has_point_or_comma
= false
296 for i
in [0..length
[ do
298 if not c
.is_numeric
then
299 if (c
== '.' or c
== ',') and not has_point_or_comma
then
300 has_point_or_comma
= true
309 # Returns `true` if the string contains only Hex chars
311 # assert "048bf".is_hex == true
312 # assert "ABCDEF".is_hex == true
313 # assert "0G".is_hex == false
316 for i
in [0..length
[ do
318 if not (c
>= 'a' and c
<= 'f') and
319 not (c
>= 'A' and c
<= 'F') and
320 not (c
>= '0' and c
<= '9') then return false
325 # Are all letters in `self` upper-case ?
327 # assert "HELLO WORLD".is_upper == true
328 # assert "%$&%!".is_upper == true
329 # assert "hello world".is_upper == false
330 # assert "Hello World".is_upper == false
333 for i
in [0..length
[ do
335 if char
.is_lower
then return false
340 # Are all letters in `self` lower-case ?
342 # assert "hello world".is_lower == true
343 # assert "%$&%!".is_lower == true
344 # assert "Hello World".is_lower == false
347 for i
in [0..length
[ do
349 if char
.is_upper
then return false
354 # Removes the whitespaces at the beginning of self
356 # assert " \n\thello \n\t".l_trim == "hello \n\t"
358 # `Char::is_whitespace` determines what is a whitespace.
361 var iter
= self.chars
.iterator
363 if not iter
.item
.is_whitespace
then break
366 if iter
.index
== length
then return self.empty
367 return self.substring_from
(iter
.index
)
370 # Removes the whitespaces at the end of self
372 # assert " \n\thello \n\t".r_trim == " \n\thello"
374 # `Char::is_whitespace` determines what is a whitespace.
377 var iter
= self.chars
.reverse_iterator
379 if not iter
.item
.is_whitespace
then break
382 if iter
.index
< 0 then return self.empty
383 return self.substring
(0, iter
.index
+ 1)
386 # Trims trailing and preceding white spaces
388 # assert " Hello World ! ".trim == "Hello World !"
389 # assert "\na\nb\tc\t".trim == "a\nb\tc"
391 # `Char::is_whitespace` determines what is a whitespace.
392 fun trim
: SELFTYPE do return (self.l_trim
).r_trim
394 # Is the string non-empty but only made of whitespaces?
396 # assert " \n\t ".is_whitespace == true
397 # assert " hello ".is_whitespace == false
398 # assert "".is_whitespace == false
400 # `Char::is_whitespace` determines what is a whitespace.
401 fun is_whitespace
: Bool
403 if is_empty
then return false
404 for c
in self.chars
do
405 if not c
.is_whitespace
then return false
410 # Returns `self` removed from its last line terminator (if any).
412 # assert "Hello\n".chomp == "Hello"
413 # assert "Hello".chomp == "Hello"
415 # assert "\n".chomp == ""
416 # assert "".chomp == ""
418 # Line terminators are `"\n"`, `"\r\n"` and `"\r"`.
419 # A single line terminator, the last one, is removed.
421 # assert "\r\n".chomp == ""
422 # assert "\r\n\n".chomp == "\r\n"
423 # assert "\r\n\r\n".chomp == "\r\n"
424 # assert "\r\n\r".chomp == "\r\n"
426 # Note: unlike with most IO methods like `Reader::read_line`,
427 # a single `\r` is considered here to be a line terminator and will be removed.
431 if len
== 0 then return self
432 var l
= self.chars
.last
434 return substring
(0, len-1
)
435 else if l
!= '\n' then
437 else if len
> 1 and self.chars
[len-2
] == '\r' then
438 return substring
(0, len-2
)
440 return substring
(0, len-1
)
444 # Justify a self in a space of `length`
446 # `left` is the space ratio on the left side.
447 # * 0.0 for left-justified (no space at the left)
448 # * 1.0 for right-justified (all spaces at the left)
449 # * 0.5 for centered (half the spaces at the left)
453 # assert "hello".justify(10, 0.0) == "hello "
454 # assert "hello".justify(10, 1.0) == " hello"
455 # assert "hello".justify(10, 0.5) == " hello "
457 # If `length` is not enough, `self` is returned as is.
459 # assert "hello".justify(2, 0.0) == "hello"
461 # REQUIRE: `left >= 0.0 and left <= 1.0`
462 # ENSURE: `self.length <= length implies result.length == length`
463 # ENSURE: `self.length >= length implies result == self`
464 fun justify
(length
: Int, left
: Float): String
466 var diff
= length
- self.length
467 if diff
<= 0 then return to_s
468 assert left
>= 0.0 and left
<= 1.0
469 var before
= (diff
.to_f
* left
).to_i
470 return " " * before
+ self + " " * (diff-before
)
473 # Mangle a string to be a unique string only made of alphanumeric characters and underscores.
475 # This method is injective (two different inputs never produce the same
476 # output) and the returned string always respect the following rules:
478 # * Contains only US-ASCII letters, digits and underscores.
479 # * Never starts with a digit.
480 # * Never ends with an underscore.
481 # * Never contains two contiguous underscores.
483 # assert "42_is/The answer!".to_cmangle == "_52d2_is_47dThe_32danswer_33d"
484 # assert "__".to_cmangle == "_95d_95d"
485 # assert "__d".to_cmangle == "_95d_d"
486 # assert "_d_".to_cmangle == "_d_95d"
487 # assert "_42".to_cmangle == "_95d42"
488 # assert "foo".to_cmangle == "foo"
489 # assert "".to_cmangle == ""
490 fun to_cmangle
: String
492 if is_empty
then return ""
494 var underscore
= false
498 if c
>= '0' and c
<= '9' then
500 res
.append
(c
.ascii
.to_s
)
504 for i
in [start
..length
[ do
506 if (c
>= 'a' and c
<= 'z') or (c
>='A' and c
<= 'Z') then
512 res
.append
('_'.ascii
.to_s
)
515 if c
>= '0' and c
<= '9' then
518 else if c
== '_' then
523 res
.append
(c
.ascii
.to_s
)
529 res
.append
('_'.ascii
.to_s
)
535 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
537 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
538 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
540 # Most non-printable characters (bellow ASCII 32) are escaped to an octal form `\nnn`.
541 # Three digits are always used to avoid following digits to be interpreted as an element
542 # of the octal sequence.
544 # assert "{0.ascii}{1.ascii}{8.ascii}{31.ascii}{32.ascii}".escape_to_c == "\\000\\001\\010\\037 "
546 # The exceptions are the common `\t` and `\n`.
547 fun escape_to_c
: String
550 for i
in [0..length
[ do
554 else if c
== '\t' then
556 else if c
== '\0' then
558 else if c
== '"' then
560 else if c == '\'' then
562 else if c == '\\
' then
564 else if c.ascii < 32 then
566 var oct = c.ascii.to_base(8, false)
567 # Force 3 octal digits since it is the
568 # maximum allowed in the C specification
569 if oct.length == 1 then
572 else if oct.length == 2 then
583 # Escape additionnal characters
584 # The result might no be legal in C but be used in other languages
586 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
587 fun escape_more_to_c(chars: String): String
590 for c in escape_to_c.chars do
591 if chars.chars.has(c) then
599 # Escape to C plus braces
601 # assert "\n\"'\\\
{\}".escape_to_nit == "\\n\\\
"\\'\\\\\\\{\\\}"
602 fun escape_to_nit
: String do return escape_more_to_c
("\{\}")
604 # Escape to POSIX Shell (sh).
606 # Abort if the text contains a null byte.
608 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
609 fun escape_to_sh
: String do
612 for i in [0..length[ do
617 assert without_null_byte
: c
!= '\0'
625 # Escape to include in a Makefile
627 # Unfortunately, some characters are not escapable in Makefile.
628 # These characters are `;`, `|`, `\`, and the non-printable ones.
629 # They will be rendered as `"?{hex}"`.
630 fun escape_to_mk: String do
632 for i in [0..length[ do
636 else if c == ':' or c == ' ' or c == '#' then
639 else if c
.ascii
< 32 or c
== ';' or c
== '|' or c
== '\\' or c
== '=' then
640 b
.append
("?{c.ascii.to_base(16, false)}")
648 # Return a string where Nit escape sequences are transformed.
651 # assert s.length == 2
652 # var u = s.unescape_nit
653 # assert u.length == 1
654 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
655 fun unescape_nit
: String
657 var res
= new Buffer.with_cap
(self.length
)
658 var was_slash
= false
659 for i
in [0..length
[ do
661 if not was_slash
then
672 else if c
== 'r' then
674 else if c
== 't' then
676 else if c
== '0' then
685 # Encode `self` to percent (or URL) encoding
687 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
688 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
689 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
690 fun to_percent_encoding
: String
694 for i
in [0..length
[ do
696 if (c
>= '0' and c
<= '9') or
697 (c
>= 'a' and c
<= 'z') or
698 (c
>= 'A' and c
<= 'Z') or
699 c
== '-' or c
== '.' or
703 else buf
.append
"%{c.ascii.to_hex}"
709 # Decode `self` from percent (or URL) encoding to a clear string
711 # Replace invalid use of '%' with '?'.
713 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
714 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
715 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
716 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
717 # assert "incomplete %".from_percent_encoding == "incomplete ?"
718 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
719 fun from_percent_encoding
: String
727 if i
+ 2 >= length
then
728 # What follows % has been cut off
732 var hex_s
= substring
(i
, 2)
734 var hex_i
= hex_s
.to_hex
738 # What follows a % is not Hex
751 # Escape the characters `<`, `>`, `&`, `"`, `'` and `/` as HTML/XML entity references.
753 # assert "a&b-<>\"x\"/'".html_escape == "a&b-<>"x"/'"
755 # 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>
756 fun html_escape
: String
760 for i
in [0..length
[ do
764 else if c
== '<' then
766 else if c
== '>' then
768 else if c
== '"' then
770 else if c
== '\'' then
772 else if c == '/' then
781 # Two pieces of text are equals if thez have the same characters in the same order.
783 # assert "hello" == "hello"
784 # assert "hello" != "HELLO"
785 # assert "hello" == "hel"+"lo"
787 # Things that are not Text are not equal.
790 # assert "9" != ['9']
793 # assert "9".chars.first == '9' # equality of Char
794 # assert "9".chars == ['9'] # equality of Sequence
795 # assert "9".to_i == 9 # equality of Int
798 if o == null then return false
799 if not o isa Text then return false
800 if self.is_same_instance(o) then return true
801 if self.length != o.length then return false
802 return self.chars == o.chars
805 # Lexicographical comparaison
807 # assert "abc" < "xy"
808 # assert "ABC" < "abc"
811 var self_chars = self.chars.iterator
812 var other_chars = other.chars.iterator
814 while self_chars.is_ok and other_chars.is_ok do
815 if self_chars.item < other_chars.item then return true
816 if self_chars.item > other_chars.item then return false
821 if self_chars.is_ok then
828 # Escape string used in labels for graphviz
830 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
831 fun escape_to_dot: String
833 return escape_more_to_c("|\{\}<>")
836 private var hash_cache: nullable Int = null
840 if hash_cache == null then
841 # djb2 hash algorithm
844 for i in [0..length[ do
846 h = h.lshift(5) + h + char.ascii
851 return hash_cache.as(not null)
854 # Gives the formatted string back as a Nit string with `args` in place
856 # assert "This %1 is a %2.".format("String", "formatted String") == "This String is a formatted String."
857 # assert "\\%1 This string".format("String") == "\\%1 This string"
858 fun format(args: Object...): String do
859 var s = new Array[Text]
863 # Skip escaped characters
864 if self[i] == '\\
' then
867 else if self[i] == '%' then
871 while i < length and self[i].is_numeric do
876 var ciph_len = fmt_end - ciph_st + 1
878 var arg_index = substring(ciph_st, ciph_len).to_i - 1
879 if arg_index >= args.length then continue
881 s.push substring(curr_st, fmt_st - curr_st)
882 s.push args[arg_index].to_s
887 s.push substring(curr_st, length - curr_st)
891 # Copies `n` bytes from `self` at `src_offset` into `dest` starting at `dest_offset`
893 # Basically a high-level synonym of NativeString::copy_to
895 # REQUIRE: `n` must be large enough to contain `len` bytes
897 # var ns = new NativeString(8)
898 # "Text is String".copy_to_native(ns, 8, 2, 0)
899 # assert ns.to_s_with_length(8) == "xt is St"
901 fun copy_to_native(dest: NativeString, n, src_offset, dest_offset: Int) do
902 var mypos = src_offset
903 var itspos = dest_offset
905 dest[itspos] = self.chars[mypos]
914 # All kinds of array-based text representations.
915 abstract class FlatText
918 # Underlying C-String (`char*`)
920 # Warning : Might be void in some subclasses, be sure to check
921 # if set before using it.
922 private var items: NativeString is noinit
924 # Real items, used as cache for to_cstring is called
925 private var real_items: nullable NativeString = null
927 # Returns a char* starting at position `index_from`
929 # WARNING: If you choose to use this service, be careful of the following.
931 # Strings and NativeString are *ideally* always allocated through a Garbage Collector.
932 # Since the GC tracks the use of the pointer for the beginning of the char*, it may be
933 # deallocated at any moment, rendering the pointer returned by this function invalid.
934 # Any access to freed memory may very likely cause undefined behaviour or a crash.
935 # (Failure to do so will most certainly result in long and painful debugging hours)
937 # The only safe use of this pointer is if it is ephemeral (e.g. read in a C function
938 # then immediately return).
940 # As always, do not modify the content of the String in C code, if this is what you want
941 # copy locally the char* as Nit Strings are immutable.
942 private fun fast_cstring: NativeString is abstract
955 redef fun copy_to_native(dest, n, src_offset, dest_offset) do
956 items.copy_to(dest, n, src_offset, dest_offset)
960 # Abstract class for the SequenceRead compatible
961 # views on String and Buffer objects
962 private abstract class StringCharView
963 super SequenceRead[Char]
969 redef fun is_empty do return target.is_empty
971 redef fun length do return target.length
973 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
975 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
978 # Immutable sequence of characters.
980 # String objects may be created using literals.
982 # assert "Hello World!" isa String
983 abstract class String
986 redef type SELFTYPE: String is fixed
988 redef fun to_s do return self
990 # Concatenates `o` to `self`
992 # assert "hello" + "world" == "helloworld"
993 # assert "" + "hello" + "" == "hello"
994 fun +(o: Text): SELFTYPE is abstract
996 # Concatenates self `i` times
998 # assert "abc" * 4 == "abcabcabcabc"
999 # assert "abc" * 1 == "abc"
1000 # assert "abc" * 0 == ""
1001 fun *(i: Int): SELFTYPE is abstract
1003 # Insert `s` at `pos`.
1005 # assert "helloworld".insert_at(" ", 5) == "hello world"
1006 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
1008 redef fun substrings is abstract
1010 # Returns a reversed version of self
1012 # assert "hello".reversed == "olleh"
1013 # assert "bob".reversed == "bob"
1014 # assert "".reversed == ""
1015 fun reversed: SELFTYPE is abstract
1017 # A upper case version of `self`
1019 # assert "Hello World!".to_upper == "HELLO WORLD!"
1020 fun to_upper: SELFTYPE is abstract
1022 # A lower case version of `self`
1024 # assert "Hello World!".to_lower == "hello world!"
1025 fun to_lower : SELFTYPE is abstract
1027 # Takes a camel case `self` and converts it to snake case
1029 # assert "randomMethodId".to_snake_case == "random_method_id"
1031 # The rules are the following:
1033 # An uppercase is always converted to a lowercase
1035 # assert "HELLO_WORLD".to_snake_case == "hello_world"
1037 # An uppercase that follows a lowercase is prefixed with an underscore
1039 # assert "HelloTheWORLD".to_snake_case == "hello_the_world"
1041 # An uppercase that follows an uppercase and is followed by a lowercase, is prefixed with an underscore
1043 # assert "HelloTHEWorld".to_snake_case == "hello_the_world"
1045 # All other characters are kept as is; `self` does not need to be a proper CamelCased string.
1047 # assert "=-_H3ll0Th3W0rld_-=".to_snake_case == "=-_h3ll0th3w0rld_-="
1048 fun to_snake_case: SELFTYPE
1050 if self.is_lower then return self
1052 var new_str = new Buffer.with_cap(self.length)
1053 var prev_is_lower = false
1054 var prev_is_upper = false
1056 for i in [0..length[ do
1058 if char.is_lower then
1060 prev_is_lower = true
1061 prev_is_upper = false
1062 else if char.is_upper then
1063 if prev_is_lower then
1065 else if prev_is_upper and i+1 < length and chars[i+1].is_lower then
1068 new_str.add(char.to_lower)
1069 prev_is_lower = false
1070 prev_is_upper = true
1073 prev_is_lower = false
1074 prev_is_upper = false
1081 # Takes a snake case `self` and converts it to camel case
1083 # assert "random_method_id".to_camel_case == "randomMethodId"
1085 # If the identifier is prefixed by an underscore, the underscore is ignored
1087 # assert "_private_field".to_camel_case == "_privateField"
1089 # If `self` is upper, it is returned unchanged
1091 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
1093 # If there are several consecutive underscores, they are considered as a single one
1095 # assert "random__method_id".to_camel_case == "randomMethodId"
1096 fun to_camel_case: SELFTYPE
1098 if self.is_upper then return self
1100 var new_str = new Buffer
1101 var is_first_char = true
1102 var follows_us = false
1104 for i in [0..length[ do
1106 if is_first_char then
1108 is_first_char = false
1109 else if char == '_
' then
1111 else if follows_us then
1112 new_str.add(char.to_upper)
1122 # Returns a capitalized `self`
1124 # Letters that follow a letter are lowercased
1125 # Letters that follow a non-letter are upcased.
1127 # SEE : `Char::is_letter` for the definition of letter.
1129 # assert "jAVASCRIPT".capitalized == "Javascript"
1130 # assert "i am root".capitalized == "I Am Root"
1131 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
1132 fun capitalized: SELFTYPE do
1133 if length == 0 then return self
1135 var buf = new Buffer.with_cap(length)
1137 var curr = chars[0].to_upper
1141 for i in [1 .. length[ do
1144 if prev.is_letter then
1145 buf[i] = curr.to_lower
1147 buf[i] = curr.to_upper
1155 # A mutable sequence of characters.
1156 abstract class Buffer
1159 # Returns an arbitrary subclass of `Buffer` with default parameters
1162 # Returns an instance of a subclass of `Buffer` with `i` base capacity
1163 new with_cap(i: Int) is abstract
1165 redef type SELFTYPE: Buffer is fixed
1167 # Specific implementations MUST set this to `true` in order to invalidate caches
1168 protected var is_dirty = true
1170 # Copy-On-Write flag
1172 # If the `Buffer` was to_s'd
, the next in-place altering
1173 # operation will cause the current `Buffer` to be re-allocated.
1175 # The flag will then be set at `false`.
1176 protected var written
= false
1178 # Modifies the char contained at pos `index`
1180 # DEPRECATED : Use self.chars.[]= instead
1181 fun []=(index
: Int, item
: Char) is abstract
1183 # Adds a char `c` at the end of self
1185 # DEPRECATED : Use self.chars.add instead
1186 fun add
(c
: Char) is abstract
1190 # var b = new Buffer
1192 # assert not b.is_empty
1195 fun clear
is abstract
1197 # Enlarges the subsequent array containing the chars of self
1198 fun enlarge
(cap
: Int) is abstract
1200 # Adds the content of text `s` at the end of self
1202 # var b = new Buffer
1205 # assert b == "helloworld"
1206 fun append
(s
: Text) is abstract
1208 # `self` is appended in such a way that `self` is repeated `r` times
1210 # var b = new Buffer
1213 # assert b == "hellohellohello"
1214 fun times
(r
: Int) is abstract
1216 # Reverses itself in-place
1218 # var b = new Buffer
1221 # assert b == "olleh"
1222 fun reverse
is abstract
1224 # Changes each lower-case char in `self` by its upper-case variant
1226 # var b = new Buffer
1227 # b.append("Hello World!")
1229 # assert b == "HELLO WORLD!"
1230 fun upper
is abstract
1232 # Changes each upper-case char in `self` by its lower-case variant
1234 # var b = new Buffer
1235 # b.append("Hello World!")
1237 # assert b == "hello world!"
1238 fun lower
is abstract
1240 # Capitalizes each word in `self`
1242 # Letters that follow a letter are lowercased
1243 # Letters that follow a non-letter are upcased.
1245 # SEE: `Char::is_letter` for the definition of a letter.
1247 # var b = new FlatBuffer.from("jAVAsCriPt")
1249 # assert b == "Javascript"
1250 # b = new FlatBuffer.from("i am root")
1252 # assert b == "I Am Root"
1253 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1255 # assert b == "Ab_C -Ab0C Ab\nC"
1257 if length
== 0 then return
1258 var c
= self[0].to_upper
1261 for i
in [1 .. length
[ do
1264 if prev
.is_letter
then
1265 self[i
] = c
.to_lower
1267 self[i
] = c
.to_upper
1274 if is_dirty
then hash_cache
= null
1278 # In Buffers, the internal sequence of character is mutable
1279 # Thus, `chars` can be used to modify the buffer.
1280 redef fun chars
: Sequence[Char] is abstract
1283 # View on Buffer objects, extends Sequence
1284 # for mutation operations
1285 private abstract class BufferCharView
1286 super StringCharView
1287 super Sequence[Char]
1289 redef type SELFTYPE: Buffer
1294 # User readable representation of `self`.
1295 fun to_s
: String do return inspect
1297 # The class name of the object in NativeString format.
1298 private fun native_class_name
: NativeString is intern
1300 # The class name of the object.
1302 # assert 5.class_name == "Int"
1303 fun class_name
: String do return native_class_name
.to_s
1305 # Developer readable representation of `self`.
1306 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1309 return "<{inspect_head}>"
1312 # Return "CLASSNAME:#OBJECTID".
1313 # This function is mainly used with the redefinition of the inspect method
1314 protected fun inspect_head
: String
1316 return "{class_name}:#{object_id.to_hex}"
1321 # assert true.to_s == "true"
1322 # assert false.to_s == "false"
1334 # C function to calculate the length of the `NativeString` to receive `self`
1335 private fun byte_to_s_len
: Int `{
1336 return snprintf(NULL, 0, "0x%02x", self);
1339 # C function to convert an nit Int to a NativeString (char*)
1340 private fun native_byte_to_s
(nstr
: NativeString, strlen
: Int) `{
1341 snprintf(nstr, strlen, "0x%02x", self);
1344 # Displayable byte in its hexadecimal form (0x..)
1346 # assert 1.to_b.to_s == "0x01"
1347 # assert (-123).to_b.to_s == "0x85"
1349 var nslen
= byte_to_s_len
1350 var ns
= new NativeString(nslen
+ 1)
1352 native_byte_to_s
(ns
, nslen
+ 1)
1353 return ns
.to_s_with_length
(nslen
)
1359 # Wrapper of strerror C function
1360 private fun strerror_ext
: NativeString `{ return strerror(self); `}
1362 # Returns a string describing error number
1363 fun strerror: String do return strerror_ext.to_s
1365 # Fill `s
` with the digits in base `base
` of `self` (and with the '-' sign if 'signed' and negative).
1366 # assume < to_c max const of char
1367 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1374 else if self == 0 then
1381 var pos = digit_count(base) - 1
1382 while pos >= 0 and n > 0 do
1383 s.chars[pos] = (n % base).to_c
1389 # C function to calculate the length of the `NativeString` to receive `self`
1390 private fun int_to_s_len: Int `{
1391 return snprintf
(NULL, 0, "%ld", self);
1394 # C function to convert an nit Int to a NativeString (char*)
1395 private fun native_int_to_s(nstr: NativeString, strlen: Int) `{
1396 snprintf
(nstr
, strlen
, "%ld", self);
1399 # return displayable int in base base and signed
1400 fun to_base(base: Int, signed: Bool): String is abstract
1402 # return displayable int in hexadecimal
1404 # assert 1.to_hex == "1"
1405 # assert (-255).to_hex == "-ff"
1406 fun to_hex: String do return to_base(16,false)
1410 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1412 # assert 12.34.to_s == "12.34"
1413 # assert (-0120.030).to_s == "-120.03"
1415 # see `to_precision
` for a custom precision.
1417 var str = to_precision( 3 )
1418 if is_inf != 0 or is_nan then return str
1419 var len = str.length
1420 for i in [0..len-1] do
1422 var c = str.chars[j]
1425 else if c == '.' then
1426 return str.substring( 0, j+2 )
1428 return str.substring( 0, j+1 )
1434 # `String` representation of `self` with the given number of `decimals
`
1436 # assert 12.345.to_precision(0) == "12"
1437 # assert 12.345.to_precision(3) == "12.345"
1438 # assert (-12.345).to_precision(3) == "-12.345"
1439 # assert (-0.123).to_precision(3) == "-0.123"
1440 # assert 0.999.to_precision(2) == "1.00"
1441 # assert 0.999.to_precision(4) == "0.9990"
1442 fun to_precision(decimals: Int): String
1444 if is_nan then return "nan"
1446 var isinf = self.is_inf
1449 else if isinf == -1 then
1453 if decimals == 0 then return self.to_i.to_s
1455 for i in [0..decimals[ do f = f * 10.0
1462 if i == 0 then return "0." + "0"*decimals
1464 # Prepare both parts of the float, before and after the "."
1469 if sl > decimals then
1470 # Has something before the "."
1471 p1 = s.substring(0, sl-decimals)
1472 p2 = s.substring(sl-decimals, decimals)
1475 p2 = "0"*(decimals-sl) + s
1478 if i < 0 then p1 = "-" + p1
1480 return p1 + "." + p2
1485 # assert 'x'.to_s == "x"
1488 var s = new Buffer.with_cap(1)
1493 # Returns true if the char is a numerical digit
1495 # assert '0'.is_numeric
1496 # assert '9'.is_numeric
1497 # assert not 'a'.is_numeric
1498 # assert not '?'.is_numeric
1499 fun is_numeric: Bool
1501 return self >= '0' and self <= '9'
1504 # Returns true if the char is an alpha digit
1506 # assert 'a'.is_alpha
1507 # assert 'Z'.is_alpha
1508 # assert not '0'.is_alpha
1509 # assert not '?'.is_alpha
1512 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1515 # Returns true if the char is an alpha or a numeric digit
1517 # assert 'a'.is_alphanumeric
1518 # assert 'Z'.is_alphanumeric
1519 # assert '0'.is_alphanumeric
1520 # assert '9'.is_alphanumeric
1521 # assert not '?'.is_alphanumeric
1522 fun is_alphanumeric: Bool
1524 return self.is_numeric or self.is_alpha
1528 redef class Collection[E]
1529 # String representation of the content of the collection.
1531 # The standard representation is the list of elements separated with commas.
1534 # assert [1,2,3].to_s == "[1,2,3]"
1535 # assert [1..3].to_s == "[1,2,3]"
1536 # assert (new Array[Int]).to_s == "[]" # empty collection
1539 # Subclasses may return a more specific string representation.
1542 return "[" + join(",") + "]"
1545 # Concatenate elements without separators
1548 # assert [1,2,3].plain_to_s == "123"
1549 # assert [11..13].plain_to_s == "111213"
1550 # assert (new Array[Int]).plain_to_s == "" # empty collection
1552 fun plain_to_s: String
1555 for e in self do if e != null then s.append(e.to_s)
1559 # Concatenate and separate each elements with `sep
`.
1561 # assert [1, 2, 3].join(":") == "1:2:3"
1562 # assert [1..3].join(":") == "1:2:3"
1563 fun join(sep: Text): String
1565 if is_empty then return ""
1567 var s = new Buffer # Result
1572 if e != null then s.append(e.to_s)
1574 # Concat other items
1579 if e != null then s.append(e.to_s)
1586 redef class Map[K,V]
1587 # Concatenate couple of 'key value'.
1588 # key and value are separated by `couple_sep
`.
1589 # each couple is separated each couple with `sep
`.
1591 # var m = new ArrayMap[Int, String]
1594 # assert m.join("; ", "=") == "1=one; 10=ten"
1595 fun join(sep: String, couple_sep: String): String is abstract
1599 private var args_cache: nullable Sequence[String] = null
1601 # The arguments of the program as given by the OS
1602 fun program_args: Sequence[String]
1604 if _args_cache == null then init_args
1605 return _args_cache.as(not null)
1608 # The name of the program as given by the OS
1609 fun program_name: String
1611 return native_argv(0).to_s
1614 # Initialize `program_args
` with the contents of `native_argc
` and `native_argv
`.
1615 private fun init_args
1617 var argc = native_argc
1618 var args = new Array[String].with_capacity(0)
1621 args[i-1] = native_argv(i).to_s
1627 # First argument of the main C function.
1628 private fun native_argc: Int is intern
1630 # Second argument of the main C function.
1631 private fun native_argv(i: Int): NativeString is intern
1634 # Comparator that efficienlty use `to_s
` to compare things
1636 # The comparaison call `to_s
` on object and use the result to order things.
1638 # var a = [1, 2, 3, 10, 20]
1639 # (new CachedAlphaComparator).sort(a)
1640 # assert a == [1, 10, 2, 20, 3]
1642 # Internally the result of `to_s
` is cached in a HashMap to counter
1643 # uneficient implementation of `to_s
`.
1645 # Note: it caching is not usefull, see `alpha_comparator
`
1646 class CachedAlphaComparator
1648 redef type COMPARED: Object
1650 private var cache = new HashMap[Object, String]
1652 private fun do_to_s(a: Object): String do
1653 if cache.has_key(a) then return cache[a]
1659 redef fun compare(a, b) do
1660 return do_to_s(a) <=> do_to_s(b)
1664 # see `alpha_comparator
`
1665 private class AlphaComparator
1667 redef fun compare(a, b) do return a.to_s <=> b.to_s
1670 # Stateless comparator that naively use `to_s
` to compare things.
1672 # Note: the result of `to_s
` is not cached, thus can be invoked a lot
1673 # on a single instace. See `CachedAlphaComparator` as an alternative.
1675 # var a = [1, 2, 3, 10, 20]
1676 # alpha_comparator.sort(a)
1677 # assert a == [1, 10, 2, 20, 3]
1678 fun alpha_comparator: Comparator do return once new AlphaComparator
1680 # The arguments of the program as given by the OS
1681 fun args: Sequence[String]
1683 return sys.program_args
1686 redef class NativeString
1687 # Returns `self` as a new String.
1688 fun to_s_with_copy: String is abstract
1690 # Returns `self` as a String of `length
`.
1691 fun to_s_with_length(length: Int): String is abstract
1694 redef class NativeArray[E]
1695 # Join all the elements using `to_s
`
1697 # REQUIRE: `self isa NativeArray[String]`
1698 # REQUIRE: all elements are initialized
1699 fun native_to_s: String is abstract