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