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