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
17 intrude import collection
# FIXME should be collection::array
24 ###############################################################################
26 ###############################################################################
28 # Common subclass for String and Buffer
29 abstract class AbstractString
30 super AbstractArrayRead[Char]
32 readable private var _items
: NativeString
34 # Access a character at `index` in the string.
36 # assert "abcd"[2] == 'c'
37 redef fun [](index
) do return _items
[index
]
41 # assert "abcd".substring(1, 2) == "bc"
42 # assert "abcd".substring(-1, ) == "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): String
53 if from
< 0 then from
= 0
54 if count
> length
then count
= length
56 var r
= new Buffer.with_capacity
(count
- from
)
67 # Create a substring from `self` beginning at the `from` position
69 # assert "abcd".substring_from(1) == "bcd"
70 # assert "abcd".substring_from(-1) == "abcd"
71 # assert "abcd".substring_from(2) == "cd"
73 # As with substring, a `from` index < 0 will be replaced by 0
74 fun substring_from
(from
: Int): String
77 return substring
(from
, length
- from
)
80 # Does self have a substring `str` starting from position `pos`?
82 # assert "abcd".has_substring("bc",1) == true
83 # assert "abcd".has_substring("bc",2) == false
84 fun has_substring
(str
: String, pos
: Int): Bool
86 var itsindex
= str
.length
- 1
87 var myindex
= pos
+ itsindex
89 var itsitems
= str
._items
90 if myindex
> length
or itsindex
> myindex
then return false
91 var its_index_from
= str
._index_from
92 itsindex
+= its_index_from
93 while itsindex
>= its_index_from
do
94 if myitems
[myindex
] != itsitems
[itsindex
] then return false
101 # Is this string prefixed by `prefix`?
103 # assert "abcd".has_prefix("ab") == true
104 # assert "abcbc".has_prefix("bc") == false
105 fun has_prefix
(prefix
: String): Bool do return has_substring
(prefix
,0)
107 # Is this string suffixed by `suffix`?
109 # assert "abcd".has_suffix("abc") == false
110 # assert "abcd".has_suffix("bcd") == true
111 fun has_suffix
(suffix
: String): Bool do return has_substring
(suffix
, length
- suffix
.length
)
113 # If `self` contains only digits, return the corresponding integer
115 # assert "123".to_i == 123
116 # assert "-1".to_i == -1
120 return to_s
.to_cstring
.atoi
123 # If `self` contains a float, return the corresponding float
125 # assert "123".to_f == 123.0
126 # assert "-1".to_f == -1.0
127 # assert "-1.2e-3".to_f == -1.2e-3
131 return to_s
.to_cstring
.atof
134 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
135 fun to_hex
: Int do return a_to
(16)
137 # If `self` contains only digits and letters, return the corresponding integer in a given base
139 # assert "120".a_to(3) == 15
140 fun a_to
(base
: Int) : Int
167 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
169 # assert "123".is_numeric == true
170 # assert "1.2".is_numeric == true
171 # assert "1,2".is_numeric == true
172 # assert "1..2".is_numeric == false
175 var has_point_or_comma
= false
180 if (i
== '.' or i
== ',') and not has_point_or_comma
182 has_point_or_comma
= true
191 # A upper case version of `self`
193 # assert "Hello World!".to_upper == "HELLO WORLD!"
196 var s
= new Buffer.with_capacity
(length
)
197 for i
in self do s
.add
(i
.to_upper
)
201 # A lower case version of `self`
203 # assert "Hello World!".to_lower == "hello world!"
204 fun to_lower
: String
206 var s
= new Buffer.with_capacity
(length
)
207 for i
in self do s
.add
(i
.to_lower
)
211 # Trims trailing and preceding white spaces
212 # A whitespace is defined as any character which ascii value is less than or equal to 32
214 # assert " Hello World ! ".trim == "Hello World !"
215 # assert "\na\nb\tc\t".trim == "a\nb\tc"
218 if self._length
== 0 then return self.to_s
219 # find position of the first non white space char (ascii < 32) from the start of the string
221 while self[start_pos
].ascii
<= 32 do
223 if start_pos
== _length
then return ""
225 # find position of the first non white space char from the end of the string
226 var end_pos
= length
- 1
227 while self[end_pos
].ascii
<= 32 do
229 if end_pos
== start_pos
then return self[start_pos
].to_s
231 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
244 # Immutable strings of characters.
250 redef type OTHER: String
252 # Index in _items of the start of the string
253 readable var _index_from
: Int
255 # Indes in _items of the last item of the string
256 readable var _index_to
: Int
258 ################################################
259 # AbstractString specific methods #
260 ################################################
262 redef fun [](index
) do
264 # Check that the index (+ index_from) is not larger than indexTo
265 # In other terms, if the index is valid
266 assert (index
+ _index_from
) <= _index_to
267 return _items
[index
+ _index_from
]
270 redef fun substring
(from
: Int, count
: Int): String
276 if count
< 0 then count
= 0
280 var realFrom
= _index_from
+ from
282 if (realFrom
+ count
) > _index_to
then return new String.from_substring
(realFrom
, _index_to
, _items
)
284 if count
== 0 then return ""
286 return new String.from_substring
(realFrom
, realFrom
+ count
- 1, _items
)
289 redef fun substring_from
(from
: Int): String
291 if from
> _length
then return ""
292 if from
< 0 then from
= 0
293 return substring
(from
, _length
)
296 redef fun has_substring
(str
: String, pos
: Int): Bool
298 var itsindex
= str
._length
- 1
300 var myindex
= pos
+ itsindex
303 var itsitems
= str
._items
305 if myindex
> _length
or itsindex
> myindex
then return false
307 var itsindexfrom
= str
.index_from
308 itsindex
+= itsindexfrom
309 myindex
+= index_from
311 while itsindex
>= itsindexfrom
do
312 if myitems
[myindex
] != itsitems
[itsindex
] then return false
320 redef fun to_upper
: String
322 var outstr
= calloc_string
(self._length
+ 1)
325 var myitems
= self._items
326 var index_from
= self._index_from
327 var max
= self._index_to
329 while index_from
<= max
do
330 outstr
[out_index
] = myitems
[index_from
].to_upper
335 outstr
[self.length
] = '\0'
337 return new String.with_native
(outstr
, self._length
)
340 redef fun to_lower
: String
342 var outstr
= calloc_string
(self._length
+ 1)
345 var myitems
= self._items
346 var index_from
= self._index_from
347 var max
= self._index_to
349 while index_from
<= max
do
350 outstr
[out_index
] = myitems
[index_from
].to_lower
355 outstr
[self.length
] = '\0'
357 return new String.with_native
(outstr
, self._length
)
360 redef fun trim
: String
362 if self._length
== 0 then return self
363 # find position of the first non white space char (ascii < 32) from the start of the string
364 var start_pos
= self._index_from
365 while _items
[start_pos
].ascii
<= 32 do
367 if start_pos
== _index_to
+ 1 then return ""
369 # find position of the first non white space char from the end of the string
370 var end_pos
= _index_to
371 while _items
[end_pos
].ascii
<= 32 do
373 if end_pos
== start_pos
then return _items
[start_pos
].to_s
375 start_pos
-= index_from
376 end_pos
-= index_from
377 return self.substring
(start_pos
, end_pos
- start_pos
+ 1)
382 var i
= self._index_from
383 var imax
= self._index_to
390 ##################################################
391 # String Specific Methods #
392 ##################################################
394 # Creates a String object as a substring of another String
396 # From : index to start at
398 # To : Index to stop at (from + count -1)
400 private init from_substring
(from
: Int, to
: Int, internalString
: NativeString)
402 _items
= internalString
405 _length
= to
- from
+ 1
408 # Create a new string from a given char *.
409 init with_native
(nat
: NativeString, size
: Int)
415 _index_to
= _length
- 1
418 # Create a new string from a null terminated char *.
419 init from_cstring
(str
: NativeString)
421 with_native
(str
,str
.cstring_length
)
424 # Creates a new Nit String from an existing CString
425 # Pretty much equals to from_cstring but copies instead
426 # of passing a reference
427 # Avoids manual/automatic dealloc problems when dealing with native C code
428 init copy_from_native
(str
: NativeString)
430 var temp_length
= str
.cstring_length
431 var new_str
= calloc_string
(temp_length
+ 1)
432 str
.copy_to
(new_str
, temp_length
, 0, 0)
433 new_str
[temp_length
] = '\0'
434 with_native
(new_str
, temp_length
)
437 # Return a null terminated char *
438 fun to_cstring
: NativeString
441 if _index_from
> 0 or _index_to
!= items
.cstring_length
- 1 then
442 var newItems
= calloc_string
(_length
+ 1)
443 self.items
.copy_to
(newItems
, _length
, _index_from
, 0)
444 newItems
[length
] = '\0'
452 if not other
isa String or other
is null then return false
454 if self.object_id
== other
.object_id
then return true
456 var my_length
= _length
458 if other
._length
!= my_length
then return false
460 var my_index
= _index_from
461 var its_index
= other
._index_from
463 var last_iteration
= my_index
+ my_length
465 var itsitems
= other
._items
466 var myitems
= self._items
468 while my_index
< last_iteration
do
469 if myitems
[my_index
] != itsitems
[its_index
] then return false
477 # The comparison between two strings is done on a lexicographical basis
479 # assert "aa" < "b" == true
482 if self.object_id
== other
.object_id
then return false
484 var my_curr_char
: Char
485 var its_curr_char
: Char
487 var curr_id_self
= self._index_from
488 var curr_id_other
= other
._index_from
490 var my_items
= self._items
491 var its_items
= other
._items
493 var my_length
= self._length
494 var its_length
= other
._length
496 var max_iterations
= curr_id_self
+ my_length
498 while curr_id_self
< max_iterations
do
499 my_curr_char
= my_items
[curr_id_self
]
500 its_curr_char
= its_items
[curr_id_other
]
502 if my_curr_char
!= its_curr_char
then
503 if my_curr_char
< its_curr_char
then return true
511 return my_length
< its_length
514 # The concatenation of `self` with `s`
516 # assert "hello " + "world!" == "hello world!"
517 fun +(s
: String): String
519 var my_length
= self._length
520 var its_length
= s
._length
522 var target_string
= calloc_string
(my_length
+ its_length
+ 1)
524 self._items
.copy_to
(target_string
, my_length
, _index_from
, 0)
525 s
._items
.copy_to
(target_string
, its_length
, s
._index_from
, my_length
)
527 target_string
[my_length
+ its_length
] = '\0'
529 return new String.with_native
(target_string
, my_length
+ its_length
)
532 # `i` repetitions of `self`
534 # assert "abc"*3 == "abcabcabc"
535 # assert "abc"*1 == "abc"
536 # assert "abc"*0 == ""
537 fun *(i
: Int): String
541 var my_length
= self._length
543 var final_length
= my_length
* i
545 var my_items
= self._items
547 var target_string
= calloc_string
((final_length
) + 1)
549 target_string
[final_length
] = '\0'
553 for iteration
in [1 .. i
] do
554 my_items
.copy_to
(target_string
, my_length
, 0, current_last
)
555 current_last
+= my_length
558 return new String.with_native
(target_string
, final_length
)
561 redef fun to_s
do return self
565 # djb2 hash algorythm
570 var strStart
= _index_from
574 while i
>= strStart
do
575 h
= (h
* 32) + h
+ self._items
[i
].ascii
583 # Mutable strings of characters.
588 super AbstractArray[Char]
590 redef type OTHER: String
592 redef fun []=(index
, item
)
594 if index
== length
then
598 assert index
>= 0 and index
< length
604 if _capacity
<= length
then enlarge
(length
+ 5)
609 redef fun enlarge
(cap
)
612 if cap
<= c
then return
613 while c
<= cap
do c
= c
* 2 + 2
614 var a
= calloc_string
(c
+1)
615 _items
.copy_to
(a
, length
, 0, 0)
624 if _capacity
< _length
+ sl
then enlarge
(_length
+ sl
)
625 s
.items
.copy_to
(_items
, sl
, s
._index_from
, _length
)
632 redef fun to_s
: String
635 var a
= calloc_string
(l
+1)
636 _items
.copy_to
(a
, l
, 0, 0)
638 # Ensure the afterlast byte is '\0' to nul-terminated char *
641 return new String.with_native
(a
, length
)
649 while i
< l1
and i
< l2
do
650 var c1
= self[i
].ascii
666 # Create a new empty string.
674 _capacity
= s
.length
+ 1
676 _items
= calloc_string
(_capacity
)
677 s
.items
.copy_to
(_items
, _length
, s
._index_from
, 0)
680 # Create a new empty string with a given capacity.
681 init with_capacity
(cap
: Int)
684 # _items = new NativeString.calloc(cap)
685 _items
= calloc_string
(cap
+1)
692 if not o
isa Buffer or o
is null then return false
694 if o
.length
!= l
then return false
699 if it
[i
] != oit
[i
] then return false
705 readable private var _capacity
: Int
708 ###############################################################################
710 ###############################################################################
713 # User readable representation of `self`.
714 fun to_s
: String do return inspect
716 # The class name of the object in NativeString format.
717 private fun native_class_name
: NativeString is intern
719 # The class name of the object.
721 # assert 5.class_name == "Int"
722 fun class_name
: String do return new String.from_cstring
(native_class_name
)
724 # Developer readable representation of `self`.
725 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
728 return "<{inspect_head}>"
731 # Return "CLASSNAME:#OBJECTID".
732 # This function is mainly used with the redefinition of the inspect method
733 protected fun inspect_head
: String
735 return "{class_name}:#{object_id.to_hex}"
738 protected fun args
: Sequence[String]
745 # assert true.to_s == "true"
746 # assert false.to_s == "false"
758 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
759 # assume < to_c max const of char
760 fun fill_buffer
(s
: Buffer, base
: Int, signed
: Bool)
767 else if self == 0 then
774 var pos
= digit_count
(base
) - 1
775 while pos
>= 0 and n
> 0 do
776 s
[pos
] = (n
% base
).to_c
782 # C function to convert an nit Int to a NativeString (char*)
783 private fun native_int_to_s
(len
: Int): NativeString is extern "native_int_to_s"
785 # return displayable int in base 10 and signed
787 # assert 1.to_s == "1"
788 # assert (-123).to_s == "-123"
790 var len
= digit_count
(10)
791 return new String.from_cstring
(native_int_to_s
(len
))
794 # return displayable int in hexadecimal (unsigned (not now))
795 fun to_hex
: String do return to_base
(16,false)
797 # return displayable int in base base and signed
798 fun to_base
(base
: Int, signed
: Bool): String
800 var l
= digit_count
(base
)
801 var s
= new Buffer.from
(" " * l
)
802 fill_buffer
(s
, base
, signed
)
808 # Pretty print self, print needoed decimals up to a max of 3.
810 var str
= to_precision
( 3 )
812 for i
in [0..len-1
] do
817 else if c
== '.' then
818 return str
.substring
( 0, j
+2 )
820 return str
.substring
( 0, j
+1 )
826 # `self` representation with `nb` digits after the '.'.
827 fun to_precision
(nb
: Int): String
829 if nb
== 0 then return self.to_i
.to_s
831 for i
in [0..nb
[ do f
= f
* 10.0
838 if i
== 0 then return "0.0"
842 var p1
= s
.substring
(0, s
.length-nb
)
843 var p2
= s
.substring
(s
.length-nb
, nb
)
846 return "0." + ("0"*(nb-sl
)) + s
850 fun to_precision_native
(nb
: Int): String import String::from_cstring
`{
854 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
855 str = malloc(size + 1);
856 sprintf(str, "%.*f", (int)nb, recv );
858 return new_String_from_cstring( str );
863 # assert 'x'.to_s == "x"
866 var s
= new Buffer.with_capacity
(1)
871 # Returns true if the char is a numerical digit
874 if self >= '0' and self <= '9'
881 # Returns true if the char is an alpha digit
884 if (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z') then return true
888 # Returns true if the char is an alpha or a numeric digit
889 fun is_alphanumeric
: Bool
891 if self.is_numeric
or self.is_alpha
then return true
896 redef class Collection[E
]
897 # Concatenate elements.
901 for e
in self do if e
!= null then s
.append
(e
.to_s
)
905 # Concatenate and separate each elements with `sep`.
907 # assert [1, 2, 3].join(":") == "1:2:3"
908 # assert [1..3].join(":") == "1:2:3"
909 fun join
(sep
: String): String
911 if is_empty
then return ""
913 var s
= new Buffer # Result
918 if e
!= null then s
.append
(e
.to_s
)
925 if e
!= null then s
.append
(e
.to_s
)
933 # Fast implementation
941 if e
!= null then s
.append
(e
.to_s
)
949 # Concatenate couple of 'key value'.
950 # key and value are separated by `couple_sep`.
951 # each couple is separated each couple with `sep`.
953 # var m = new ArrayMap[Int, String]
956 # assert m.join("; ", "=") == "1=one; 10=ten"
957 fun join
(sep
: String, couple_sep
: String): String
959 if is_empty
then return ""
961 var s
= new Buffer # Result
967 if e
!= null then s
.append
("{k}{couple_sep}{e}")
975 if e
!= null then s
.append
("{k}{couple_sep}{e}")
982 ###############################################################################
984 ###############################################################################
986 # Native strings are simple C char *
988 fun [](index
: Int): Char is intern
989 fun []=(index
: Int, item
: Char) is intern
990 fun copy_to
(dest
: NativeString, length
: Int, from
: Int, to
: Int) is intern
992 # Position of the first nul character.
993 fun cstring_length
: Int
996 while self[l
] != '\0' do l
+= 1
999 fun atoi
: Int is intern
1000 fun atof
: Float is extern "atof"
1003 # StringCapable objects can create native strings
1004 interface StringCapable
1005 protected fun calloc_string
(size
: Int): NativeString is intern
1009 var _args_cache
: nullable Sequence[String]
1011 redef fun args
: Sequence[String]
1013 if _args_cache
== null then init_args
1014 return _args_cache
.as(not null)
1017 # The name of the program as given by the OS
1018 fun program_name
: String
1020 return new String.from_cstring
(native_argv
(0))
1023 # Initialize `args` with the contents of `native_argc` and `native_argv`.
1024 private fun init_args
1026 var argc
= native_argc
1027 var args
= new Array[String].with_capacity
(0)
1030 args
[i-1
] = new String.from_cstring
(native_argv
(i
))
1036 # First argument of the main C function.
1037 private fun native_argc
: Int is intern
1039 # Second argument of the main C function.
1040 private fun native_argv
(i
: Int): NativeString is intern