28ad7b5c098eb3b25689aa30edddaf5b85a55805
[nit.git] / lib / standard / string.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2004-2008 Jean Privat <jean@pryen.org>
4 # Copyright 2006-2008 Floréal Morandat <morandat@lirmm.fr>
5 #
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
12 # another product.
13
14 # Basic manipulations of strings of characters
15 module string
16
17 import math
18 import collection
19 intrude import collection::array
20
21 `{
22 #include <stdio.h>
23 #include <string.h>
24 `}
25
26 ###############################################################################
27 # String #
28 ###############################################################################
29
30 # High-level abstraction for all text representations
31 abstract class Text
32 super Comparable
33 super StringCapable
34
35 redef type OTHER: Text
36
37 # Type of self (used for factorization of several methods, ex : substring_from, empty...)
38 type SELFTYPE: Text
39
40 # Gets a view on the chars of the Text object
41 #
42 # assert "hello".chars.to_a == ['h', 'e', 'l', 'l', 'o']
43 fun chars: SequenceRead[Char] is abstract
44
45 # Number of characters contained in self.
46 #
47 # assert "12345".length == 5
48 # assert "".length == 0
49 fun length: Int is abstract
50
51 # Create a substring.
52 #
53 # assert "abcd".substring(1, 2) == "bc"
54 # assert "abcd".substring(-1, 2) == "a"
55 # assert "abcd".substring(1, 0) == ""
56 # assert "abcd".substring(2, 5) == "cd"
57 #
58 # A `from` index < 0 will be replaced by 0.
59 # Unless a `count` value is > 0 at the same time.
60 # In this case, `from += count` and `count -= from`.
61 fun substring(from: Int, count: Int): SELFTYPE is abstract
62
63 # Iterates on the substrings of self if any
64 fun substrings: Iterator[Text] is abstract
65
66 # Is the current Text empty (== "")
67 #
68 # assert "".is_empty
69 # assert not "foo".is_empty
70 fun is_empty: Bool do return self.length == 0
71
72 # Returns an empty Text of the right type
73 #
74 # This method is used internally to get the right
75 # implementation of an empty string.
76 protected fun empty: SELFTYPE is abstract
77
78 # Gets the first char of the Text
79 #
80 # DEPRECATED : Use self.chars.first instead
81 fun first: Char do return self.chars[0]
82
83 # Access a character at `index` in the string.
84 #
85 # assert "abcd"[2] == 'c'
86 #
87 # DEPRECATED : Use self.chars.[] instead
88 fun [](index: Int): Char do return self.chars[index]
89
90 # Gets the index of the first occurence of 'c'
91 #
92 # Returns -1 if not found
93 #
94 # DEPRECATED : Use self.chars.index_of instead
95 fun index_of(c: Char): Int
96 do
97 return index_of_from(c, 0)
98 end
99
100 # Gets the last char of self
101 #
102 # DEPRECATED : Use self.chars.last instead
103 fun last: Char do return self.chars[length-1]
104
105 # Gets the index of the first occurence of ´c´ starting from ´pos´
106 #
107 # Returns -1 if not found
108 #
109 # DEPRECATED : Use self.chars.index_of_from instead
110 fun index_of_from(c: Char, pos: Int): Int
111 do
112 var iter = self.chars.iterator_from(pos)
113 while iter.is_ok do
114 if iter.item == c then return iter.index
115 iter.next
116 end
117 return -1
118 end
119
120 # Gets the last index of char ´c´
121 #
122 # Returns -1 if not found
123 #
124 # DEPRECATED : Use self.chars.last_index_of instead
125 fun last_index_of(c: Char): Int
126 do
127 return last_index_of_from(c, length - 1)
128 end
129
130 # Return a null terminated char *
131 fun to_cstring: NativeString do return flatten.to_cstring
132
133 # The index of the last occurrence of an element starting from pos (in reverse order).
134 #
135 # var s = "/etc/bin/test/test.nit"
136 # assert s.last_index_of_from('/', s.length-1) == 13
137 # assert s.last_index_of_from('/', 12) == 8
138 #
139 # Returns -1 if not found
140 #
141 # DEPRECATED : Use self.chars.last_index_of_from instead
142 fun last_index_of_from(item: Char, pos: Int): Int
143 do
144 var iter = self.chars.reverse_iterator_from(pos)
145 while iter.is_ok do
146 if iter.item == item then return iter.index
147 iter.next
148 end
149 return -1
150 end
151
152 # Gets an iterator on the chars of self
153 #
154 # DEPRECATED : Use self.chars.iterator instead
155 fun iterator: Iterator[Char]
156 do
157 return self.chars.iterator
158 end
159
160
161 # Gets an Array containing the chars of self
162 #
163 # DEPRECATED : Use self.chars.to_a instead
164 fun to_a: Array[Char] do return chars.to_a
165
166 # Create a substring from `self` beginning at the `from` position
167 #
168 # assert "abcd".substring_from(1) == "bcd"
169 # assert "abcd".substring_from(-1) == "abcd"
170 # assert "abcd".substring_from(2) == "cd"
171 #
172 # As with substring, a `from` index < 0 will be replaced by 0
173 fun substring_from(from: Int): SELFTYPE
174 do
175 if from >= self.length then return empty
176 if from < 0 then from = 0
177 return substring(from, length - from)
178 end
179
180 # Does self have a substring `str` starting from position `pos`?
181 #
182 # assert "abcd".has_substring("bc",1) == true
183 # assert "abcd".has_substring("bc",2) == false
184 #
185 # Returns true iff all characters of `str` are presents
186 # at the expected index in `self.`
187 # The first character of `str` being at `pos`, the second
188 # character being at `pos+1` and so on...
189 #
190 # This means that all characters of `str` need to be inside `self`.
191 #
192 # assert "abcd".has_substring("xab", -1) == false
193 # assert "abcd".has_substring("cdx", 2) == false
194 #
195 # And that the empty string is always a valid substring.
196 #
197 # assert "abcd".has_substring("", 2) == true
198 # assert "abcd".has_substring("", 200) == true
199 fun has_substring(str: String, pos: Int): Bool
200 do
201 if str.is_empty then return true
202 if pos < 0 or pos + str.length > length then return false
203 var myiter = self.chars.iterator_from(pos)
204 var itsiter = str.chars.iterator
205 while myiter.is_ok and itsiter.is_ok do
206 if myiter.item != itsiter.item then return false
207 myiter.next
208 itsiter.next
209 end
210 if itsiter.is_ok then return false
211 return true
212 end
213
214 # Is this string prefixed by `prefix`?
215 #
216 # assert "abcd".has_prefix("ab") == true
217 # assert "abcbc".has_prefix("bc") == false
218 # assert "ab".has_prefix("abcd") == false
219 fun has_prefix(prefix: String): Bool do return has_substring(prefix,0)
220
221 # Is this string suffixed by `suffix`?
222 #
223 # assert "abcd".has_suffix("abc") == false
224 # assert "abcd".has_suffix("bcd") == true
225 fun has_suffix(suffix: String): Bool do return has_substring(suffix, length - suffix.length)
226
227 # If `self` contains only digits, return the corresponding integer
228 #
229 # assert "123".to_i == 123
230 # assert "-1".to_i == -1
231 fun to_i: Int
232 do
233 # Shortcut
234 return to_s.to_cstring.atoi
235 end
236
237 # If `self` contains a float, return the corresponding float
238 #
239 # assert "123".to_f == 123.0
240 # assert "-1".to_f == -1.0
241 # assert "-1.2e-3".to_f == -0.0012
242 fun to_f: Float
243 do
244 # Shortcut
245 return to_s.to_cstring.atof
246 end
247
248 # If `self` contains only digits and alpha <= 'f', return the corresponding integer.
249 #
250 # assert "ff".to_hex == 255
251 fun to_hex: Int do return a_to(16)
252
253 # If `self` contains only digits and letters, return the corresponding integer in a given base
254 #
255 # assert "120".a_to(3) == 15
256 fun a_to(base: Int) : Int
257 do
258 var i = 0
259 var neg = false
260
261 for j in [0..length[ do
262 var c = chars[j]
263 var v = c.to_i
264 if v > base then
265 if neg then
266 return -i
267 else
268 return i
269 end
270 else if v < 0 then
271 neg = true
272 else
273 i = i * base + v
274 end
275 end
276 if neg then
277 return -i
278 else
279 return i
280 end
281 end
282
283 # Returns `true` if the string contains only Numeric values (and one "," or one "." character)
284 #
285 # assert "123".is_numeric == true
286 # assert "1.2".is_numeric == true
287 # assert "1,2".is_numeric == true
288 # assert "1..2".is_numeric == false
289 fun is_numeric: Bool
290 do
291 var has_point_or_comma = false
292 for i in [0..length[ do
293 var c = chars[i]
294 if not c.is_numeric then
295 if (c == '.' or c == ',') and not has_point_or_comma then
296 has_point_or_comma = true
297 else
298 return false
299 end
300 end
301 end
302 return true
303 end
304
305 # Returns `true` if the string contains only Hex chars
306 #
307 # assert "048bf".is_hex == true
308 # assert "ABCDEF".is_hex == true
309 # assert "0G".is_hex == false
310 fun is_hex: Bool
311 do
312 for i in [0..length[ do
313 var c = chars[i]
314 if not (c >= 'a' and c <= 'f') and
315 not (c >= 'A' and c <= 'F') and
316 not (c >= '0' and c <= '9') then return false
317 end
318 return true
319 end
320
321 # Are all letters in `self` upper-case ?
322 #
323 # assert "HELLO WORLD".is_upper == true
324 # assert "%$&%!".is_upper == true
325 # assert "hello world".is_upper == false
326 # assert "Hello World".is_upper == false
327 fun is_upper: Bool
328 do
329 for i in [0..length[ do
330 var char = chars[i]
331 if char.is_lower then return false
332 end
333 return true
334 end
335
336 # Are all letters in `self` lower-case ?
337 #
338 # assert "hello world".is_lower == true
339 # assert "%$&%!".is_lower == true
340 # assert "Hello World".is_lower == false
341 fun is_lower: Bool
342 do
343 for i in [0..length[ do
344 var char = chars[i]
345 if char.is_upper then return false
346 end
347 return true
348 end
349
350 # Removes the whitespaces at the beginning of self
351 #
352 # assert " \n\thello \n\t".l_trim == "hello \n\t"
353 #
354 # A whitespace is defined as any character which ascii value is less than or equal to 32
355 fun l_trim: SELFTYPE
356 do
357 var iter = self.chars.iterator
358 while iter.is_ok do
359 if iter.item.ascii > 32 then break
360 iter.next
361 end
362 if iter.index == length then return self.empty
363 return self.substring_from(iter.index)
364 end
365
366 # Removes the whitespaces at the end of self
367 #
368 # assert " \n\thello \n\t".r_trim == " \n\thello"
369 #
370 # A whitespace is defined as any character which ascii value is less than or equal to 32
371 fun r_trim: SELFTYPE
372 do
373 var iter = self.chars.reverse_iterator
374 while iter.is_ok do
375 if iter.item.ascii > 32 then break
376 iter.next
377 end
378 if iter.index < 0 then return self.empty
379 return self.substring(0, iter.index + 1)
380 end
381
382 # Trims trailing and preceding white spaces
383 # A whitespace is defined as any character which ascii value is less than or equal to 32
384 #
385 # assert " Hello World ! ".trim == "Hello World !"
386 # assert "\na\nb\tc\t".trim == "a\nb\tc"
387 fun trim: SELFTYPE do return (self.l_trim).r_trim
388
389 # Justify a self in a space of `length`
390 #
391 # `left` is the space ratio on the left side.
392 # * 0.0 for left-justified (no space at the left)
393 # * 1.0 for right-justified (all spaces at the left)
394 # * 0.5 for centered (half the spaces at the left)
395 #
396 # assert "hello".justify(10, 0.0) == "hello "
397 # assert "hello".justify(10, 1.0) == " hello"
398 # assert "hello".justify(10, 0.5) == " hello "
399 #
400 # If `length` is not enough, `self` is returned as is.
401 #
402 # assert "hello".justify(2, 0.0) == "hello"
403 #
404 # REQUIRE: left >= 0.0 and left <= 1.0
405 # ENSURE: `self.length <= length implies result.length == length`
406 # ENSURE: `self.length >= length implies result == self
407 fun justify(length: Int, left: Float): SELFTYPE
408 do
409 var diff = length - self.length
410 if diff <= 0 then return self
411 assert left >= 0.0 and left <= 1.0
412 var before = (diff.to_f * left).to_i
413 return " " * before + self + " " * (diff-before)
414 end
415
416 # Mangle a string to be a unique string only made of alphanumeric characters
417 fun to_cmangle: String
418 do
419 var res = new FlatBuffer
420 var underscore = false
421 for i in [0..length[ do
422 var c = chars[i]
423 if (c >= 'a' and c <= 'z') or (c >='A' and c <= 'Z') then
424 res.add(c)
425 underscore = false
426 continue
427 end
428 if underscore then
429 res.append('_'.ascii.to_s)
430 res.add('d')
431 end
432 if c >= '0' and c <= '9' then
433 res.add(c)
434 underscore = false
435 else if c == '_' then
436 res.add(c)
437 underscore = true
438 else
439 res.add('_')
440 res.append(c.ascii.to_s)
441 res.add('d')
442 underscore = false
443 end
444 end
445 return res.to_s
446 end
447
448 # Escape " \ ' and non printable characters using the rules of literal C strings and characters
449 #
450 # assert "abAB12<>&".escape_to_c == "abAB12<>&"
451 # assert "\n\"'\\".escape_to_c == "\\n\\\"\\'\\\\"
452 fun escape_to_c: String
453 do
454 var b = new FlatBuffer
455 for i in [0..length[ do
456 var c = chars[i]
457 if c == '\n' then
458 b.append("\\n")
459 else if c == '\0' then
460 b.append("\\0")
461 else if c == '"' then
462 b.append("\\\"")
463 else if c == '\'' then
464 b.append("\\\'")
465 else if c == '\\' then
466 b.append("\\\\")
467 else if c.ascii < 32 then
468 b.append("\\{c.ascii.to_base(8, false)}")
469 else
470 b.add(c)
471 end
472 end
473 return b.to_s
474 end
475
476 # Escape additionnal characters
477 # The result might no be legal in C but be used in other languages
478 #
479 # assert "ab|\{\}".escape_more_to_c("|\{\}") == "ab\\|\\\{\\\}"
480 fun escape_more_to_c(chars: String): String
481 do
482 var b = new FlatBuffer
483 for c in escape_to_c.chars do
484 if chars.chars.has(c) then
485 b.add('\\')
486 end
487 b.add(c)
488 end
489 return b.to_s
490 end
491
492 # Escape to C plus braces
493 #
494 # assert "\n\"'\\\{\}".escape_to_nit == "\\n\\\"\\'\\\\\\\{\\\}"
495 fun escape_to_nit: String do return escape_more_to_c("\{\}")
496
497 # Escape to POSIX Shell (sh).
498 #
499 # Abort if the text contains a null byte.
500 #
501 # assert "\n\"'\\\{\}0".escape_to_sh == "'\n\"'\\''\\\{\}0'"
502 fun escape_to_sh: String do
503 var b = new FlatBuffer
504 b.chars.add '\''
505 for i in [0..length[ do
506 var c = chars[i]
507 if c == '\'' then
508 b.append("'\\''")
509 else
510 assert without_null_byte: c != '\0'
511 b.add(c)
512 end
513 end
514 b.chars.add '\''
515 return b.to_s
516 end
517
518 # Return a string where Nit escape sequences are transformed.
519 #
520 # var s = "\\n"
521 # assert s.length == 2
522 # var u = s.unescape_nit
523 # assert u.length == 1
524 # assert u.chars[0].ascii == 10 # (the ASCII value of the "new line" character)
525 fun unescape_nit: String
526 do
527 var res = new FlatBuffer.with_capacity(self.length)
528 var was_slash = false
529 for i in [0..length[ do
530 var c = chars[i]
531 if not was_slash then
532 if c == '\\' then
533 was_slash = true
534 else
535 res.add(c)
536 end
537 continue
538 end
539 was_slash = false
540 if c == 'n' then
541 res.add('\n')
542 else if c == 'r' then
543 res.add('\r')
544 else if c == 't' then
545 res.add('\t')
546 else if c == '0' then
547 res.add('\0')
548 else
549 res.add(c)
550 end
551 end
552 return res.to_s
553 end
554
555 # Encode `self` to percent (or URL) encoding
556 #
557 # assert "aBc09-._~".to_percent_encoding == "aBc09-._~"
558 # assert "%()< >".to_percent_encoding == "%25%28%29%3c%20%3e"
559 # assert ".com/post?e=asdf&f=123".to_percent_encoding == ".com%2fpost%3fe%3dasdf%26f%3d123"
560 fun to_percent_encoding: String
561 do
562 var buf = new FlatBuffer
563
564 for i in [0..length[ do
565 var c = chars[i]
566 if (c >= '0' and c <= '9') or
567 (c >= 'a' and c <= 'z') or
568 (c >= 'A' and c <= 'Z') or
569 c == '-' or c == '.' or
570 c == '_' or c == '~'
571 then
572 buf.add c
573 else buf.append "%{c.ascii.to_hex}"
574 end
575
576 return buf.to_s
577 end
578
579 # Decode `self` from percent (or URL) encoding to a clear string
580 #
581 # Replace invalid use of '%' with '?'.
582 #
583 # assert "aBc09-._~".from_percent_encoding == "aBc09-._~"
584 # assert "%25%28%29%3c%20%3e".from_percent_encoding == "%()< >"
585 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".from_percent_encoding == ".com/post?e=asdf&f=123"
586 # assert "%25%28%29%3C%20%3E".from_percent_encoding == "%()< >"
587 # assert "incomplete %".from_percent_encoding == "incomplete ?"
588 # assert "invalid % usage".from_percent_encoding == "invalid ? usage"
589 fun from_percent_encoding: String
590 do
591 var buf = new FlatBuffer
592
593 var i = 0
594 while i < length do
595 var c = chars[i]
596 if c == '%' then
597 if i + 2 >= length then
598 # What follows % has been cut off
599 buf.add '?'
600 else
601 i += 1
602 var hex_s = substring(i, 2)
603 if hex_s.is_hex then
604 var hex_i = hex_s.to_hex
605 buf.add hex_i.ascii
606 i += 1
607 else
608 # What follows a % is not Hex
609 buf.add '?'
610 i -= 1
611 end
612 end
613 else buf.add c
614
615 i += 1
616 end
617
618 return buf.to_s
619 end
620
621 # Escape the four characters `<`, `>`, `&`, and `"` with their html counterpart
622 #
623 # assert "a&b->\"x\"".html_escape == "a&amp;b-&gt;&quot;x&quot;"
624 fun html_escape: SELFTYPE
625 do
626 var buf = new FlatBuffer
627
628 for i in [0..length[ do
629 var c = chars[i]
630 if c == '&' then
631 buf.append "&amp;"
632 else if c == '<' then
633 buf.append "&lt;"
634 else if c == '>' then
635 buf.append "&gt;"
636 else if c == '"' then
637 buf.append "&quot;"
638 else buf.add c
639 end
640
641 return buf.to_s
642 end
643
644 # Equality of text
645 # Two pieces of text are equals if thez have the same characters in the same order.
646 #
647 # assert "hello" == "hello"
648 # assert "hello" != "HELLO"
649 # assert "hello" == "hel"+"lo"
650 #
651 # Things that are not Text are not equal.
652 #
653 # assert "9" != '9'
654 # assert "9" != ['9']
655 # assert "9" != 9
656 #
657 # assert "9".chars.first == '9' # equality of Char
658 # assert "9".chars == ['9'] # equality of Sequence
659 # assert "9".to_i == 9 # equality of Int
660 redef fun ==(o)
661 do
662 if o == null then return false
663 if not o isa Text then return false
664 if self.is_same_instance(o) then return true
665 if self.length != o.length then return false
666 return self.chars == o.chars
667 end
668
669 # Lexicographical comparaison
670 #
671 # assert "abc" < "xy"
672 # assert "ABC" < "abc"
673 redef fun <(other)
674 do
675 var self_chars = self.chars.iterator
676 var other_chars = other.chars.iterator
677
678 while self_chars.is_ok and other_chars.is_ok do
679 if self_chars.item < other_chars.item then return true
680 if self_chars.item > other_chars.item then return false
681 self_chars.next
682 other_chars.next
683 end
684
685 if self_chars.is_ok then
686 return false
687 else
688 return true
689 end
690 end
691
692 # Escape string used in labels for graphviz
693 #
694 # assert ">><<".escape_to_dot == "\\>\\>\\<\\<"
695 fun escape_to_dot: String
696 do
697 return escape_more_to_c("|\{\}<>")
698 end
699
700 # Flat representation of self
701 fun flatten: FlatText is abstract
702
703 private var hash_cache: nullable Int = null
704
705 redef fun hash
706 do
707 if hash_cache == null then
708 # djb2 hash algorithm
709 var h = 5381
710
711 for i in [0..length[ do
712 var char = chars[i]
713 h = h.lshift(5) + h + char.ascii
714 end
715
716 hash_cache = h
717 end
718 return hash_cache.as(not null)
719 end
720
721 end
722
723 # All kinds of array-based text representations.
724 abstract class FlatText
725 super Text
726
727 # Underlying C-String (`char*`)
728 #
729 # Warning : Might be void in some subclasses, be sure to check
730 # if set before using it.
731 private var items: NativeString is noinit
732
733 # Real items, used as cache for to_cstring is called
734 private var real_items: nullable NativeString = null
735
736 redef var length: Int = 0
737
738 init do end
739
740 redef fun output
741 do
742 var i = 0
743 while i < length do
744 items[i].output
745 i += 1
746 end
747 end
748
749 redef fun flatten do return self
750 end
751
752 # Abstract class for the SequenceRead compatible
753 # views on String and Buffer objects
754 private abstract class StringCharView
755 super SequenceRead[Char]
756
757 type SELFTYPE: Text
758
759 private var target: SELFTYPE
760
761 redef fun is_empty do return target.is_empty
762
763 redef fun length do return target.length
764
765 redef fun iterator: IndexedIterator[Char] do return self.iterator_from(0)
766
767 redef fun reverse_iterator do return self.reverse_iterator_from(self.length - 1)
768 end
769
770 # View on Buffer objects, extends Sequence
771 # for mutation operations
772 private abstract class BufferCharView
773 super StringCharView
774 super Sequence[Char]
775
776 redef type SELFTYPE: Buffer
777
778 end
779
780 abstract class String
781 super Text
782
783 redef type SELFTYPE: String
784
785 redef fun to_s do return self
786
787 # Concatenates `o` to `self`
788 #
789 # assert "hello" + "world" == "helloworld"
790 # assert "" + "hello" + "" == "hello"
791 fun +(o: Text): SELFTYPE is abstract
792
793 # Concatenates self `i` times
794 #
795 # assert "abc" * 4 == "abcabcabcabc"
796 # assert "abc" * 1 == "abc"
797 # assert "abc" * 0 == ""
798 fun *(i: Int): SELFTYPE is abstract
799
800 fun insert_at(s: String, pos: Int): SELFTYPE is abstract
801
802 redef fun substrings: Iterator[String] is abstract
803
804 # Returns a reversed version of self
805 #
806 # assert "hello".reversed == "olleh"
807 # assert "bob".reversed == "bob"
808 # assert "".reversed == ""
809 fun reversed: SELFTYPE is abstract
810
811 # A upper case version of `self`
812 #
813 # assert "Hello World!".to_upper == "HELLO WORLD!"
814 fun to_upper: SELFTYPE is abstract
815
816 # A lower case version of `self`
817 #
818 # assert "Hello World!".to_lower == "hello world!"
819 fun to_lower : SELFTYPE is abstract
820
821 # Takes a camel case `self` and converts it to snake case
822 #
823 # assert "randomMethodId".to_snake_case == "random_method_id"
824 #
825 # If `self` is upper, it is returned unchanged
826 #
827 # assert "RANDOM_METHOD_ID".to_snake_case == "RANDOM_METHOD_ID"
828 #
829 # If the identifier is prefixed by an underscore, the underscore is ignored
830 #
831 # assert "_privateField".to_snake_case == "_private_field"
832 fun to_snake_case: SELFTYPE
833 do
834 if self.is_upper then return self
835
836 var new_str = new FlatBuffer.with_capacity(self.length)
837 var is_first_char = true
838
839 for i in [0..length[ do
840 var char = chars[i]
841 if is_first_char then
842 new_str.add(char.to_lower)
843 is_first_char = false
844 else if char.is_upper then
845 new_str.add('_')
846 new_str.add(char.to_lower)
847 else
848 new_str.add(char)
849 end
850 end
851
852 return new_str.to_s
853 end
854
855 # Takes a snake case `self` and converts it to camel case
856 #
857 # assert "random_method_id".to_camel_case == "randomMethodId"
858 #
859 # If the identifier is prefixed by an underscore, the underscore is ignored
860 #
861 # assert "_private_field".to_camel_case == "_privateField"
862 #
863 # If `self` is upper, it is returned unchanged
864 #
865 # assert "RANDOM_ID".to_camel_case == "RANDOM_ID"
866 #
867 # If there are several consecutive underscores, they are considered as a single one
868 #
869 # assert "random__method_id".to_camel_case == "randomMethodId"
870 fun to_camel_case: SELFTYPE
871 do
872 if self.is_upper then return self
873
874 var new_str = new FlatBuffer
875 var is_first_char = true
876 var follows_us = false
877
878 for i in [0..length[ do
879 var char = chars[i]
880 if is_first_char then
881 new_str.add(char)
882 is_first_char = false
883 else if char == '_' then
884 follows_us = true
885 else if follows_us then
886 new_str.add(char.to_upper)
887 follows_us = false
888 else
889 new_str.add(char)
890 end
891 end
892
893 return new_str.to_s
894 end
895
896 # Returns a capitalized `self`
897 #
898 # Letters that follow a letter are lowercased
899 # Letters that follow a non-letter are upcased.
900 #
901 # SEE : `Char::is_letter` for the definition of letter.
902 #
903 # assert "jAVASCRIPT".capitalized == "Javascript"
904 # assert "i am root".capitalized == "I Am Root"
905 # assert "ab_c -ab0c ab\nc".capitalized == "Ab_C -Ab0C Ab\nC"
906 fun capitalized: SELFTYPE do
907 if length == 0 then return self
908
909 var buf = new FlatBuffer.with_capacity(length)
910
911 var curr = chars[0].to_upper
912 var prev = curr
913 buf[0] = curr
914
915 for i in [1 .. length[ do
916 prev = curr
917 curr = self[i]
918 if prev.is_letter then
919 buf[i] = curr.to_lower
920 else
921 buf[i] = curr.to_upper
922 end
923 end
924
925 return buf.to_s
926 end
927 end
928
929 private class FlatSubstringsIter
930 super Iterator[FlatText]
931
932 var tgt: nullable FlatText
933
934 redef fun item do
935 assert is_ok
936 return tgt.as(not null)
937 end
938
939 redef fun is_ok do return tgt != null
940
941 redef fun next do tgt = null
942 end
943
944 # Immutable strings of characters.
945 class FlatString
946 super FlatText
947 super String
948
949 # Index in _items of the start of the string
950 private var index_from: Int is noinit
951
952 # Indes in _items of the last item of the string
953 private var index_to: Int is noinit
954
955 redef var chars: SequenceRead[Char] = new FlatStringCharView(self)
956
957 redef fun [](index)
958 do
959 # Check that the index (+ index_from) is not larger than indexTo
960 # In other terms, if the index is valid
961 assert index >= 0
962 assert (index + index_from) <= index_to
963 return items[index + index_from]
964 end
965
966 ################################################
967 # AbstractString specific methods #
968 ################################################
969
970 redef fun reversed
971 do
972 var native = calloc_string(self.length + 1)
973 var length = self.length
974 var items = self.items
975 var pos = 0
976 var ipos = length-1
977 while pos < length do
978 native[pos] = items[ipos]
979 pos += 1
980 ipos -= 1
981 end
982 return native.to_s_with_length(self.length)
983 end
984
985 redef fun substring(from, count)
986 do
987 assert count >= 0
988
989 if from < 0 then
990 count += from
991 if count < 0 then count = 0
992 from = 0
993 end
994
995 var realFrom = index_from + from
996
997 if (realFrom + count) > index_to then return new FlatString.with_infos(items, index_to - realFrom + 1, realFrom, index_to)
998
999 if count == 0 then return empty
1000
1001 var to = realFrom + count - 1
1002
1003 return new FlatString.with_infos(items, to - realFrom + 1, realFrom, to)
1004 end
1005
1006 redef fun empty do return "".as(FlatString)
1007
1008 redef fun to_upper
1009 do
1010 var outstr = calloc_string(self.length + 1)
1011 var out_index = 0
1012
1013 var myitems = self.items
1014 var index_from = self.index_from
1015 var max = self.index_to
1016
1017 while index_from <= max do
1018 outstr[out_index] = myitems[index_from].to_upper
1019 out_index += 1
1020 index_from += 1
1021 end
1022
1023 outstr[self.length] = '\0'
1024
1025 return outstr.to_s_with_length(self.length)
1026 end
1027
1028 redef fun to_lower
1029 do
1030 var outstr = calloc_string(self.length + 1)
1031 var out_index = 0
1032
1033 var myitems = self.items
1034 var index_from = self.index_from
1035 var max = self.index_to
1036
1037 while index_from <= max do
1038 outstr[out_index] = myitems[index_from].to_lower
1039 out_index += 1
1040 index_from += 1
1041 end
1042
1043 outstr[self.length] = '\0'
1044
1045 return outstr.to_s_with_length(self.length)
1046 end
1047
1048 redef fun output
1049 do
1050 var i = self.index_from
1051 var imax = self.index_to
1052 while i <= imax do
1053 items[i].output
1054 i += 1
1055 end
1056 end
1057
1058 ##################################################
1059 # String Specific Methods #
1060 ##################################################
1061
1062 private init with_infos(items: NativeString, len: Int, from: Int, to: Int)
1063 do
1064 self.items = items
1065 length = len
1066 index_from = from
1067 index_to = to
1068 end
1069
1070 redef fun to_cstring: NativeString
1071 do
1072 if real_items != null then
1073 return real_items.as(not null)
1074 else
1075 var newItems = calloc_string(length + 1)
1076 self.items.copy_to(newItems, length, index_from, 0)
1077 newItems[length] = '\0'
1078 self.real_items = newItems
1079 return newItems
1080 end
1081 end
1082
1083 redef fun ==(other)
1084 do
1085 if not other isa FlatString then return super
1086
1087 if self.object_id == other.object_id then return true
1088
1089 var my_length = length
1090
1091 if other.length != my_length then return false
1092
1093 var my_index = index_from
1094 var its_index = other.index_from
1095
1096 var last_iteration = my_index + my_length
1097
1098 var itsitems = other.items
1099 var myitems = self.items
1100
1101 while my_index < last_iteration do
1102 if myitems[my_index] != itsitems[its_index] then return false
1103 my_index += 1
1104 its_index += 1
1105 end
1106
1107 return true
1108 end
1109
1110 redef fun <(other)
1111 do
1112 if not other isa FlatString then return super
1113
1114 if self.object_id == other.object_id then return false
1115
1116 var my_curr_char : Char
1117 var its_curr_char : Char
1118
1119 var curr_id_self = self.index_from
1120 var curr_id_other = other.index_from
1121
1122 var my_items = self.items
1123 var its_items = other.items
1124
1125 var my_length = self.length
1126 var its_length = other.length
1127
1128 var max_iterations = curr_id_self + my_length
1129
1130 while curr_id_self < max_iterations do
1131 my_curr_char = my_items[curr_id_self]
1132 its_curr_char = its_items[curr_id_other]
1133
1134 if my_curr_char != its_curr_char then
1135 if my_curr_char < its_curr_char then return true
1136 return false
1137 end
1138
1139 curr_id_self += 1
1140 curr_id_other += 1
1141 end
1142
1143 return my_length < its_length
1144 end
1145
1146 redef fun +(s)
1147 do
1148 var my_length = self.length
1149 var its_length = s.length
1150
1151 var total_length = my_length + its_length
1152
1153 var target_string = calloc_string(my_length + its_length + 1)
1154
1155 self.items.copy_to(target_string, my_length, index_from, 0)
1156 if s isa FlatString then
1157 s.items.copy_to(target_string, its_length, s.index_from, my_length)
1158 else if s isa FlatBuffer then
1159 s.items.copy_to(target_string, its_length, 0, my_length)
1160 else
1161 var curr_pos = my_length
1162 for i in [0..s.length[ do
1163 var c = s.chars[i]
1164 target_string[curr_pos] = c
1165 curr_pos += 1
1166 end
1167 end
1168
1169 target_string[total_length] = '\0'
1170
1171 return target_string.to_s_with_length(total_length)
1172 end
1173
1174 redef fun *(i)
1175 do
1176 assert i >= 0
1177
1178 var my_length = self.length
1179
1180 var final_length = my_length * i
1181
1182 var my_items = self.items
1183
1184 var target_string = calloc_string((final_length) + 1)
1185
1186 target_string[final_length] = '\0'
1187
1188 var current_last = 0
1189
1190 for iteration in [1 .. i] do
1191 my_items.copy_to(target_string, my_length, 0, current_last)
1192 current_last += my_length
1193 end
1194
1195 return target_string.to_s_with_length(final_length)
1196 end
1197
1198 redef fun hash
1199 do
1200 if hash_cache == null then
1201 # djb2 hash algorithm
1202 var h = 5381
1203 var i = index_from
1204
1205 var myitems = items
1206
1207 while i <= index_to do
1208 h = h.lshift(5) + h + myitems[i].ascii
1209 i += 1
1210 end
1211
1212 hash_cache = h
1213 end
1214
1215 return hash_cache.as(not null)
1216 end
1217
1218 redef fun substrings do return new FlatSubstringsIter(self)
1219 end
1220
1221 private class FlatStringReverseIterator
1222 super IndexedIterator[Char]
1223
1224 var target: FlatString
1225
1226 var target_items: NativeString
1227
1228 var curr_pos: Int
1229
1230 init with_pos(tgt: FlatString, pos: Int)
1231 do
1232 target = tgt
1233 target_items = tgt.items
1234 curr_pos = pos + tgt.index_from
1235 end
1236
1237 redef fun is_ok do return curr_pos >= target.index_from
1238
1239 redef fun item do return target_items[curr_pos]
1240
1241 redef fun next do curr_pos -= 1
1242
1243 redef fun index do return curr_pos - target.index_from
1244
1245 end
1246
1247 private class FlatStringIterator
1248 super IndexedIterator[Char]
1249
1250 var target: FlatString
1251
1252 var target_items: NativeString
1253
1254 var curr_pos: Int
1255
1256 init with_pos(tgt: FlatString, pos: Int)
1257 do
1258 target = tgt
1259 target_items = tgt.items
1260 curr_pos = pos + target.index_from
1261 end
1262
1263 redef fun is_ok do return curr_pos <= target.index_to
1264
1265 redef fun item do return target_items[curr_pos]
1266
1267 redef fun next do curr_pos += 1
1268
1269 redef fun index do return curr_pos - target.index_from
1270
1271 end
1272
1273 private class FlatStringCharView
1274 super StringCharView
1275
1276 redef type SELFTYPE: FlatString
1277
1278 redef fun [](index)
1279 do
1280 # Check that the index (+ index_from) is not larger than indexTo
1281 # In other terms, if the index is valid
1282 assert index >= 0
1283 var target = self.target
1284 assert (index + target.index_from) <= target.index_to
1285 return target.items[index + target.index_from]
1286 end
1287
1288 redef fun iterator_from(start) do return new FlatStringIterator.with_pos(target, start)
1289
1290 redef fun reverse_iterator_from(start) do return new FlatStringReverseIterator.with_pos(target, start)
1291
1292 end
1293
1294 abstract class Buffer
1295 super Text
1296
1297 redef type SELFTYPE: Buffer
1298
1299 # Specific implementations MUST set this to `true` in order to invalidate caches
1300 protected var is_dirty = true
1301
1302 # Copy-On-Write flag
1303 #
1304 # If the `Buffer` was to_s'd, the next in-place altering
1305 # operation will cause the current `Buffer` to be re-allocated.
1306 #
1307 # The flag will then be set at `false`.
1308 protected var written = false
1309
1310 # Modifies the char contained at pos `index`
1311 #
1312 # DEPRECATED : Use self.chars.[]= instead
1313 fun []=(index: Int, item: Char) is abstract
1314
1315 # Adds a char `c` at the end of self
1316 #
1317 # DEPRECATED : Use self.chars.add instead
1318 fun add(c: Char) is abstract
1319
1320 # Clears the buffer
1321 #
1322 # var b = new FlatBuffer
1323 # b.append "hello"
1324 # assert not b.is_empty
1325 # b.clear
1326 # assert b.is_empty
1327 fun clear is abstract
1328
1329 # Enlarges the subsequent array containing the chars of self
1330 fun enlarge(cap: Int) is abstract
1331
1332 # Adds the content of text `s` at the end of self
1333 #
1334 # var b = new FlatBuffer
1335 # b.append "hello"
1336 # b.append "world"
1337 # assert b == "helloworld"
1338 fun append(s: Text) is abstract
1339
1340 # `self` is appended in such a way that `self` is repeated `r` times
1341 #
1342 # var b = new FlatBuffer
1343 # b.append "hello"
1344 # b.times 3
1345 # assert b == "hellohellohello"
1346 fun times(r: Int) is abstract
1347
1348 # Reverses itself in-place
1349 #
1350 # var b = new FlatBuffer
1351 # b.append("hello")
1352 # b.reverse
1353 # assert b == "olleh"
1354 fun reverse is abstract
1355
1356 # Changes each lower-case char in `self` by its upper-case variant
1357 #
1358 # var b = new FlatBuffer
1359 # b.append("Hello World!")
1360 # b.upper
1361 # assert b == "HELLO WORLD!"
1362 fun upper is abstract
1363
1364 # Changes each upper-case char in `self` by its lower-case variant
1365 #
1366 # var b = new FlatBuffer
1367 # b.append("Hello World!")
1368 # b.lower
1369 # assert b == "hello world!"
1370 fun lower is abstract
1371
1372 # Capitalizes each word in `self`
1373 #
1374 # Letters that follow a letter are lowercased
1375 # Letters that follow a non-letter are upcased.
1376 #
1377 # SEE: `Char::is_letter` for the definition of a letter.
1378 #
1379 # var b = new FlatBuffer.from("jAVAsCriPt")"
1380 # b.capitalize
1381 # assert b == "Javascript"
1382 # b = new FlatBuffer.from("i am root")
1383 # b.capitalize
1384 # assert b == "I Am Root"
1385 # b = new FlatBuffer.from("ab_c -ab0c ab\nc")
1386 # b.capitalize
1387 # assert b == "Ab_C -Ab0C Ab\nC"
1388 fun capitalize do
1389 if length == 0 then return
1390 var c = self[0].to_upper
1391 self[0] = c
1392 var prev: Char = c
1393 for i in [1 .. length[ do
1394 prev = c
1395 c = self[i]
1396 if prev.is_letter then
1397 self[i] = c.to_lower
1398 else
1399 self[i] = c.to_upper
1400 end
1401 end
1402 end
1403
1404 redef fun hash
1405 do
1406 if is_dirty then hash_cache = null
1407 return super
1408 end
1409
1410 # In Buffers, the internal sequence of character is mutable
1411 # Thus, `chars` can be used to modify the buffer.
1412 redef fun chars: Sequence[Char] is abstract
1413 end
1414
1415 # Mutable strings of characters.
1416 class FlatBuffer
1417 super FlatText
1418 super Buffer
1419
1420 redef type SELFTYPE: FlatBuffer
1421
1422 redef var chars: Sequence[Char] = new FlatBufferCharView(self)
1423
1424 private var capacity: Int = 0
1425
1426 redef fun substrings do return new FlatSubstringsIter(self)
1427
1428 # Re-copies the `NativeString` into a new one and sets it as the new `Buffer`
1429 #
1430 # This happens when an operation modifies the current `Buffer` and
1431 # the Copy-On-Write flag `written` is set at true.
1432 private fun reset do
1433 var nns = new NativeString(capacity)
1434 items.copy_to(nns, length, 0, 0)
1435 items = nns
1436 written = false
1437 end
1438
1439 redef fun [](index)
1440 do
1441 assert index >= 0
1442 assert index < length
1443 return items[index]
1444 end
1445
1446 redef fun []=(index, item)
1447 do
1448 is_dirty = true
1449 if index == length then
1450 add(item)
1451 return
1452 end
1453 if written then reset
1454 assert index >= 0 and index < length
1455 items[index] = item
1456 end
1457
1458 redef fun add(c)
1459 do
1460 is_dirty = true
1461 if capacity <= length then enlarge(length + 5)
1462 items[length] = c
1463 length += 1
1464 end
1465
1466 redef fun clear do
1467 is_dirty = true
1468 if written then reset
1469 length = 0
1470 end
1471
1472 redef fun empty do return new FlatBuffer
1473
1474 redef fun enlarge(cap)
1475 do
1476 var c = capacity
1477 if cap <= c then return
1478 while c <= cap do c = c * 2 + 2
1479 # The COW flag can be set at false here, since
1480 # it does a copy of the current `Buffer`
1481 written = false
1482 var a = calloc_string(c+1)
1483 if length > 0 then items.copy_to(a, length, 0, 0)
1484 items = a
1485 capacity = c
1486 end
1487
1488 redef fun to_s: String
1489 do
1490 written = true
1491 if length == 0 then items = new NativeString(1)
1492 return new FlatString.with_infos(items, length, 0, length - 1)
1493 end
1494
1495 redef fun to_cstring
1496 do
1497 if is_dirty then
1498 var new_native = calloc_string(length + 1)
1499 new_native[length] = '\0'
1500 if length > 0 then items.copy_to(new_native, length, 0, 0)
1501 real_items = new_native
1502 is_dirty = false
1503 end
1504 return real_items.as(not null)
1505 end
1506
1507 # Create a new empty string.
1508 init do end
1509
1510 init from(s: Text)
1511 do
1512 capacity = s.length + 1
1513 length = s.length
1514 items = calloc_string(capacity)
1515 if s isa FlatString then
1516 s.items.copy_to(items, length, s.index_from, 0)
1517 else if s isa FlatBuffer then
1518 s.items.copy_to(items, length, 0, 0)
1519 else
1520 var curr_pos = 0
1521 for i in [0..s.length[ do
1522 var c = s.chars[i]
1523 items[curr_pos] = c
1524 curr_pos += 1
1525 end
1526 end
1527 end
1528
1529 # Create a new empty string with a given capacity.
1530 init with_capacity(cap: Int)
1531 do
1532 assert cap >= 0
1533 # _items = new NativeString.calloc(cap)
1534 items = calloc_string(cap+1)
1535 capacity = cap
1536 length = 0
1537 end
1538
1539 redef fun append(s)
1540 do
1541 if s.is_empty then return
1542 is_dirty = true
1543 var sl = s.length
1544 if capacity < length + sl then enlarge(length + sl)
1545 if s isa FlatString then
1546 s.items.copy_to(items, sl, s.index_from, length)
1547 else if s isa FlatBuffer then
1548 s.items.copy_to(items, sl, 0, length)
1549 else
1550 var curr_pos = self.length
1551 for i in [0..s.length[ do
1552 var c = s.chars[i]
1553 items[curr_pos] = c
1554 curr_pos += 1
1555 end
1556 end
1557 length += sl
1558 end
1559
1560 # Copies the content of self in `dest`
1561 fun copy(start: Int, len: Int, dest: Buffer, new_start: Int)
1562 do
1563 var self_chars = self.chars
1564 var dest_chars = dest.chars
1565 for i in [0..len-1] do
1566 dest_chars[new_start+i] = self_chars[start+i]
1567 end
1568 end
1569
1570 redef fun substring(from, count)
1571 do
1572 assert count >= 0
1573 count += from
1574 if from < 0 then from = 0
1575 if count > length then count = length
1576 if from < count then
1577 var r = new FlatBuffer.with_capacity(count - from)
1578 while from < count do
1579 r.chars.push(items[from])
1580 from += 1
1581 end
1582 return r
1583 else
1584 return new FlatBuffer
1585 end
1586 end
1587
1588 redef fun reverse
1589 do
1590 written = false
1591 var ns = calloc_string(capacity)
1592 var si = length - 1
1593 var ni = 0
1594 var it = items
1595 while si >= 0 do
1596 ns[ni] = it[si]
1597 ni += 1
1598 si -= 1
1599 end
1600 items = ns
1601 end
1602
1603 redef fun times(repeats)
1604 do
1605 var x = new FlatString.with_infos(items, length, 0, length - 1)
1606 for i in [1..repeats[ do
1607 append(x)
1608 end
1609 end
1610
1611 redef fun upper
1612 do
1613 if written then reset
1614 var it = items
1615 var id = length - 1
1616 while id >= 0 do
1617 it[id] = it[id].to_upper
1618 id -= 1
1619 end
1620 end
1621
1622 redef fun lower
1623 do
1624 if written then reset
1625 var it = items
1626 var id = length - 1
1627 while id >= 0 do
1628 it[id] = it[id].to_lower
1629 id -= 1
1630 end
1631 end
1632 end
1633
1634 private class FlatBufferReverseIterator
1635 super IndexedIterator[Char]
1636
1637 var target: FlatBuffer
1638
1639 var target_items: NativeString
1640
1641 var curr_pos: Int
1642
1643 init with_pos(tgt: FlatBuffer, pos: Int)
1644 do
1645 target = tgt
1646 if tgt.length > 0 then target_items = tgt.items
1647 curr_pos = pos
1648 end
1649
1650 redef fun index do return curr_pos
1651
1652 redef fun is_ok do return curr_pos >= 0
1653
1654 redef fun item do return target_items[curr_pos]
1655
1656 redef fun next do curr_pos -= 1
1657
1658 end
1659
1660 private class FlatBufferCharView
1661 super BufferCharView
1662 super StringCapable
1663
1664 redef type SELFTYPE: FlatBuffer
1665
1666 redef fun [](index) do return target.items[index]
1667
1668 redef fun []=(index, item)
1669 do
1670 assert index >= 0 and index <= length
1671 if index == length then
1672 add(item)
1673 return
1674 end
1675 target.items[index] = item
1676 end
1677
1678 redef fun push(c)
1679 do
1680 target.add(c)
1681 end
1682
1683 redef fun add(c)
1684 do
1685 target.add(c)
1686 end
1687
1688 fun enlarge(cap: Int)
1689 do
1690 target.enlarge(cap)
1691 end
1692
1693 redef fun append(s)
1694 do
1695 var my_items = target.items
1696 var s_length = s.length
1697 if target.capacity < s.length then enlarge(s_length + target.length)
1698 end
1699
1700 redef fun iterator_from(pos) do return new FlatBufferIterator.with_pos(target, pos)
1701
1702 redef fun reverse_iterator_from(pos) do return new FlatBufferReverseIterator.with_pos(target, pos)
1703
1704 end
1705
1706 private class FlatBufferIterator
1707 super IndexedIterator[Char]
1708
1709 var target: FlatBuffer
1710
1711 var target_items: NativeString
1712
1713 var curr_pos: Int
1714
1715 init with_pos(tgt: FlatBuffer, pos: Int)
1716 do
1717 target = tgt
1718 if tgt.length > 0 then target_items = tgt.items
1719 curr_pos = pos
1720 end
1721
1722 redef fun index do return curr_pos
1723
1724 redef fun is_ok do return curr_pos < target.length
1725
1726 redef fun item do return target_items[curr_pos]
1727
1728 redef fun next do curr_pos += 1
1729
1730 end
1731
1732 ###############################################################################
1733 # Refinement #
1734 ###############################################################################
1735
1736 redef class Object
1737 # User readable representation of `self`.
1738 fun to_s: String do return inspect
1739
1740 # The class name of the object in NativeString format.
1741 private fun native_class_name: NativeString is intern
1742
1743 # The class name of the object.
1744 #
1745 # assert 5.class_name == "Int"
1746 fun class_name: String do return native_class_name.to_s
1747
1748 # Developer readable representation of `self`.
1749 # Usually, it uses the form "<CLASSNAME:#OBJECTID bla bla bla>"
1750 fun inspect: String
1751 do
1752 return "<{inspect_head}>"
1753 end
1754
1755 # Return "CLASSNAME:#OBJECTID".
1756 # This function is mainly used with the redefinition of the inspect method
1757 protected fun inspect_head: String
1758 do
1759 return "{class_name}:#{object_id.to_hex}"
1760 end
1761 end
1762
1763 redef class Bool
1764 # assert true.to_s == "true"
1765 # assert false.to_s == "false"
1766 redef fun to_s
1767 do
1768 if self then
1769 return once "true"
1770 else
1771 return once "false"
1772 end
1773 end
1774 end
1775
1776 redef class Int
1777
1778 # Wrapper of strerror C function
1779 private fun strerror_ext: NativeString is extern `{
1780 return strerror(recv);
1781 `}
1782
1783 # Returns a string describing error number
1784 fun strerror: String do return strerror_ext.to_s
1785
1786 # Fill `s` with the digits in base `base` of `self` (and with the '-' sign if 'signed' and negative).
1787 # assume < to_c max const of char
1788 private fun fill_buffer(s: Buffer, base: Int, signed: Bool)
1789 do
1790 var n: Int
1791 # Sign
1792 if self < 0 then
1793 n = - self
1794 s.chars[0] = '-'
1795 else if self == 0 then
1796 s.chars[0] = '0'
1797 return
1798 else
1799 n = self
1800 end
1801 # Fill digits
1802 var pos = digit_count(base) - 1
1803 while pos >= 0 and n > 0 do
1804 s.chars[pos] = (n % base).to_c
1805 n = n / base # /
1806 pos -= 1
1807 end
1808 end
1809
1810 # C function to convert an nit Int to a NativeString (char*)
1811 private fun native_int_to_s: NativeString is extern "native_int_to_s"
1812
1813 # return displayable int in base 10 and signed
1814 #
1815 # assert 1.to_s == "1"
1816 # assert (-123).to_s == "-123"
1817 redef fun to_s do
1818 return native_int_to_s.to_s
1819 end
1820
1821 # return displayable int in hexadecimal
1822 #
1823 # assert 1.to_hex == "1"
1824 # assert (-255).to_hex == "-ff"
1825 fun to_hex: String do return to_base(16,false)
1826
1827 # return displayable int in base base and signed
1828 fun to_base(base: Int, signed: Bool): String
1829 do
1830 var l = digit_count(base)
1831 var s = new FlatBuffer.from(" " * l)
1832 fill_buffer(s, base, signed)
1833 return s.to_s
1834 end
1835 end
1836
1837 redef class Float
1838 # Pretty representation of `self`, with decimals as needed from 1 to a maximum of 3
1839 #
1840 # assert 12.34.to_s == "12.34"
1841 # assert (-0120.030).to_s == "-120.03"
1842 #
1843 # see `to_precision` for a custom precision.
1844 redef fun to_s do
1845 var str = to_precision( 3 )
1846 if is_inf != 0 or is_nan then return str
1847 var len = str.length
1848 for i in [0..len-1] do
1849 var j = len-1-i
1850 var c = str.chars[j]
1851 if c == '0' then
1852 continue
1853 else if c == '.' then
1854 return str.substring( 0, j+2 )
1855 else
1856 return str.substring( 0, j+1 )
1857 end
1858 end
1859 return str
1860 end
1861
1862 # `String` representation of `self` with the given number of `decimals`
1863 #
1864 # assert 12.345.to_precision(0) == "12"
1865 # assert 12.345.to_precision(3) == "12.345"
1866 # assert (-12.345).to_precision(3) == "-12.345"
1867 # assert (-0.123).to_precision(3) == "-0.123"
1868 # assert 0.999.to_precision(2) == "1.00"
1869 # assert 0.999.to_precision(4) == "0.9990"
1870 fun to_precision(decimals: Int): String
1871 do
1872 if is_nan then return "nan"
1873
1874 var isinf = self.is_inf
1875 if isinf == 1 then
1876 return "inf"
1877 else if isinf == -1 then
1878 return "-inf"
1879 end
1880
1881 if decimals == 0 then return self.to_i.to_s
1882 var f = self
1883 for i in [0..decimals[ do f = f * 10.0
1884 if self > 0.0 then
1885 f = f + 0.5
1886 else
1887 f = f - 0.5
1888 end
1889 var i = f.to_i
1890 if i == 0 then return "0." + "0"*decimals
1891
1892 # Prepare both parts of the float, before and after the "."
1893 var s = i.abs.to_s
1894 var sl = s.length
1895 var p1
1896 var p2
1897 if sl > decimals then
1898 # Has something before the "."
1899 p1 = s.substring(0, sl-decimals)
1900 p2 = s.substring(sl-decimals, decimals)
1901 else
1902 p1 = "0"
1903 p2 = "0"*(decimals-sl) + s
1904 end
1905
1906 if i < 0 then p1 = "-" + p1
1907
1908 return p1 + "." + p2
1909 end
1910
1911 # `self` representation with `nb` digits after the '.'.
1912 #
1913 # assert 12.345.to_precision_native(1) == "12.3"
1914 # assert 12.345.to_precision_native(2) == "12.35"
1915 # assert 12.345.to_precision_native(3) == "12.345"
1916 # assert 12.345.to_precision_native(4) == "12.3450"
1917 fun to_precision_native(nb: Int): String import NativeString.to_s `{
1918 int size;
1919 char *str;
1920
1921 size = snprintf(NULL, 0, "%.*f", (int)nb, recv);
1922 str = malloc(size + 1);
1923 sprintf(str, "%.*f", (int)nb, recv );
1924
1925 return NativeString_to_s( str );
1926 `}
1927 end
1928
1929 redef class Char
1930 # assert 'x'.to_s == "x"
1931 redef fun to_s
1932 do
1933 var s = new FlatBuffer.with_capacity(1)
1934 s.chars[0] = self
1935 return s.to_s
1936 end
1937
1938 # Returns true if the char is a numerical digit
1939 #
1940 # assert '0'.is_numeric
1941 # assert '9'.is_numeric
1942 # assert not 'a'.is_numeric
1943 # assert not '?'.is_numeric
1944 fun is_numeric: Bool
1945 do
1946 return self >= '0' and self <= '9'
1947 end
1948
1949 # Returns true if the char is an alpha digit
1950 #
1951 # assert 'a'.is_alpha
1952 # assert 'Z'.is_alpha
1953 # assert not '0'.is_alpha
1954 # assert not '?'.is_alpha
1955 fun is_alpha: Bool
1956 do
1957 return (self >= 'a' and self <= 'z') or (self >= 'A' and self <= 'Z')
1958 end
1959
1960 # Returns true if the char is an alpha or a numeric digit
1961 #
1962 # assert 'a'.is_alphanumeric
1963 # assert 'Z'.is_alphanumeric
1964 # assert '0'.is_alphanumeric
1965 # assert '9'.is_alphanumeric
1966 # assert not '?'.is_alphanumeric
1967 fun is_alphanumeric: Bool
1968 do
1969 return self.is_numeric or self.is_alpha
1970 end
1971 end
1972
1973 redef class Collection[E]
1974 # Concatenate elements.
1975 redef fun to_s
1976 do
1977 var s = new FlatBuffer
1978 for e in self do if e != null then s.append(e.to_s)
1979 return s.to_s
1980 end
1981
1982 # Concatenate and separate each elements with `sep`.
1983 #
1984 # assert [1, 2, 3].join(":") == "1:2:3"
1985 # assert [1..3].join(":") == "1:2:3"
1986 fun join(sep: Text): String
1987 do
1988 if is_empty then return ""
1989
1990 var s = new FlatBuffer # Result
1991
1992 # Concat first item
1993 var i = iterator
1994 var e = i.item
1995 if e != null then s.append(e.to_s)
1996
1997 # Concat other items
1998 i.next
1999 while i.is_ok do
2000 s.append(sep)
2001 e = i.item
2002 if e != null then s.append(e.to_s)
2003 i.next
2004 end
2005 return s.to_s
2006 end
2007 end
2008
2009 redef class Array[E]
2010
2011 # Fast implementation
2012 redef fun to_s
2013 do
2014 var l = length
2015 if l == 0 then return ""
2016 if l == 1 then if self[0] == null then return "" else return self[0].to_s
2017 var its = _items
2018 var na = new NativeArray[String](l)
2019 var i = 0
2020 var sl = 0
2021 var mypos = 0
2022 while i < l do
2023 var itsi = its[i]
2024 if itsi == null then
2025 i += 1
2026 continue
2027 end
2028 var tmp = itsi.to_s
2029 sl += tmp.length
2030 na[mypos] = tmp
2031 i += 1
2032 mypos += 1
2033 end
2034 var ns = new NativeString(sl + 1)
2035 ns[sl] = '\0'
2036 i = 0
2037 var off = 0
2038 while i < mypos do
2039 var tmp = na[i]
2040 var tpl = tmp.length
2041 if tmp isa FlatString then
2042 tmp.items.copy_to(ns, tpl, tmp.index_from, off)
2043 off += tpl
2044 else
2045 for j in tmp.substrings do
2046 var s = j.as(FlatString)
2047 var slen = s.length
2048 s.items.copy_to(ns, slen, s.index_from, off)
2049 off += slen
2050 end
2051 end
2052 i += 1
2053 end
2054 return ns.to_s_with_length(sl)
2055 end
2056 end
2057
2058 redef class Map[K,V]
2059 # Concatenate couple of 'key value'.
2060 # key and value are separated by `couple_sep`.
2061 # each couple is separated each couple with `sep`.
2062 #
2063 # var m = new ArrayMap[Int, String]
2064 # m[1] = "one"
2065 # m[10] = "ten"
2066 # assert m.join("; ", "=") == "1=one; 10=ten"
2067 fun join(sep: String, couple_sep: String): String
2068 do
2069 if is_empty then return ""
2070
2071 var s = new FlatBuffer # Result
2072
2073 # Concat first item
2074 var i = iterator
2075 var k = i.key
2076 var e = i.item
2077 s.append("{k}{couple_sep}{e or else "<null>"}")
2078
2079 # Concat other items
2080 i.next
2081 while i.is_ok do
2082 s.append(sep)
2083 k = i.key
2084 e = i.item
2085 s.append("{k}{couple_sep}{e or else "<null>"}")
2086 i.next
2087 end
2088 return s.to_s
2089 end
2090 end
2091
2092 ###############################################################################
2093 # Native classes #
2094 ###############################################################################
2095
2096 # Native strings are simple C char *
2097 extern class NativeString `{ char* `}
2098 super StringCapable
2099 # Creates a new NativeString with a capacity of `length`
2100 new(length: Int) is intern
2101 fun [](index: Int): Char is intern
2102 fun []=(index: Int, item: Char) is intern
2103 fun copy_to(dest: NativeString, length: Int, from: Int, to: Int) is intern
2104
2105 # Position of the first nul character.
2106 fun cstring_length: Int
2107 do
2108 var l = 0
2109 while self[l] != '\0' do l += 1
2110 return l
2111 end
2112 fun atoi: Int is intern
2113 fun atof: Float is extern "atof"
2114
2115 redef fun to_s
2116 do
2117 return to_s_with_length(cstring_length)
2118 end
2119
2120 fun to_s_with_length(length: Int): FlatString
2121 do
2122 assert length >= 0
2123 var str = new FlatString.with_infos(self, length, 0, length - 1)
2124 return str
2125 end
2126
2127 fun to_s_with_copy: FlatString
2128 do
2129 var length = cstring_length
2130 var new_self = calloc_string(length + 1)
2131 copy_to(new_self, length, 0, 0)
2132 var str = new FlatString.with_infos(new_self, length, 0, length - 1)
2133 new_self[length] = '\0'
2134 str.real_items = new_self
2135 return str
2136 end
2137 end
2138
2139 # StringCapable objects can create native strings
2140 interface StringCapable
2141 protected fun calloc_string(size: Int): NativeString is intern
2142 end
2143
2144 redef class Sys
2145 private var args_cache: nullable Sequence[String]
2146
2147 # The arguments of the program as given by the OS
2148 fun program_args: Sequence[String]
2149 do
2150 if _args_cache == null then init_args
2151 return _args_cache.as(not null)
2152 end
2153
2154 # The name of the program as given by the OS
2155 fun program_name: String
2156 do
2157 return native_argv(0).to_s
2158 end
2159
2160 # Initialize `program_args` with the contents of `native_argc` and `native_argv`.
2161 private fun init_args
2162 do
2163 var argc = native_argc
2164 var args = new Array[String].with_capacity(0)
2165 var i = 1
2166 while i < argc do
2167 args[i-1] = native_argv(i).to_s
2168 i += 1
2169 end
2170 _args_cache = args
2171 end
2172
2173 # First argument of the main C function.
2174 private fun native_argc: Int is intern
2175
2176 # Second argument of the main C function.
2177 private fun native_argv(i: Int): NativeString is intern
2178 end
2179
2180 # Comparator that efficienlty use `to_s` to compare things
2181 #
2182 # The comparaison call `to_s` on object and use the result to order things.
2183 #
2184 # var a = [1, 2, 3, 10, 20]
2185 # (new CachedAlphaComparator).sort(a)
2186 # assert a == [1, 10, 2, 20, 3]
2187 #
2188 # Internally the result of `to_s` is cached in a HashMap to counter
2189 # uneficient implementation of `to_s`.
2190 #
2191 # Note: it caching is not usefull, see `alpha_comparator`
2192 class CachedAlphaComparator
2193 super Comparator
2194 redef type COMPARED: Object
2195
2196 private var cache = new HashMap[Object, String]
2197
2198 private fun do_to_s(a: Object): String do
2199 if cache.has_key(a) then return cache[a]
2200 var res = a.to_s
2201 cache[a] = res
2202 return res
2203 end
2204
2205 redef fun compare(a, b) do
2206 return do_to_s(a) <=> do_to_s(b)
2207 end
2208 end
2209
2210 # see `alpha_comparator`
2211 private class AlphaComparator
2212 super Comparator
2213 redef fun compare(a, b) do return a.to_s <=> b.to_s
2214 end
2215
2216 # Stateless comparator that naively use `to_s` to compare things.
2217 #
2218 # Note: the result of `to_s` is not cached, thus can be invoked a lot
2219 # on a single instace. See `CachedAlphaComparator` as an alternative.
2220 #
2221 # var a = [1, 2, 3, 10, 20]
2222 # alpha_comparator.sort(a)
2223 # assert a == [1, 10, 2, 20, 3]
2224 fun alpha_comparator: Comparator do return once new AlphaComparator
2225
2226 # The arguments of the program as given by the OS
2227 fun args: Sequence[String]
2228 do
2229 return sys.program_args
2230 end