f386c47af738a511f880c8dba10a5a659d53d0c0
[nit.git] / lib / core / bytes.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Services for byte streams and arrays
16 module bytes
17
18 import kernel
19 import collection::array
20 intrude import text::flat
21
22 # Any kind of entity which can be searched for in a Sequence of Byte
23 interface BytePattern
24 # Return the first occurence of `self` in `b`, or -1 if not found
25 fun first_index_in(b: SequenceRead[Int]): Int do return first_index_in_from(b, 0)
26
27 # Return the first occurence of `self` in `b` starting at `from`, or -1 if not found
28 fun first_index_in_from(b: SequenceRead[Int], from: Int): Int is abstract
29
30 # Return the last occurence of `self` in `b`, or -1 if not found
31 fun last_index_in(b: SequenceRead[Int]): Int do return last_index_in_from(b, b.length - 1)
32
33 # Return the last occurence of `self` in `b`, or -1 if not found
34 fun last_index_in_from(b: SequenceRead[Int], from: Int): Int is abstract
35
36 # Returns the indexes of all the occurences of `self` in `b`
37 fun search_all_in(b: SequenceRead[Int]): SequenceRead[Int] is abstract
38
39 # Length of the pattern
40 fun pattern_length: Int is abstract
41
42 # Appends `self` to `b`
43 fun append_to(b: Sequence[Int]) is abstract
44
45 # Is `self` a prefix for `b` ?
46 fun is_prefix(b: SequenceRead[Int]): Bool is abstract
47
48 # Is `self` a suffix for `b` ?
49 fun is_suffix(b: SequenceRead[Int]): Bool is abstract
50 end
51
52 redef class Int
53 super BytePattern
54
55 # Write self as a string into `ns` at position `pos`
56 private fun add_digest_at(ns: CString, pos: Int) do
57 var tmp = (0xF0 & self) >> 4
58 ns[pos] = if tmp >= 0x0A then tmp + 0x37 else tmp + 0x30
59 tmp = 0x0F & self
60 ns[pos + 1] = if tmp >= 0x0A then tmp + 0x37 else tmp + 0x30
61 end
62
63 # Is `self` a valid hexadecimal digit (in ASCII)
64 #
65 # ~~~nit
66 # intrude import core::bytes
67 # assert not u'/'.is_valid_hexdigit
68 # assert u'0'.is_valid_hexdigit
69 # assert u'9'.is_valid_hexdigit
70 # assert not u':'.is_valid_hexdigit
71 # assert not u'@'.is_valid_hexdigit
72 # assert u'A'.is_valid_hexdigit
73 # assert u'F'.is_valid_hexdigit
74 # assert not u'G'.is_valid_hexdigit
75 # assert not u'`'.is_valid_hexdigit
76 # assert u'a'.is_valid_hexdigit
77 # assert u'f'.is_valid_hexdigit
78 # assert not u'g'.is_valid_hexdigit
79 # ~~~
80 private fun is_valid_hexdigit: Bool do
81 return (self >= 0x30 and self <= 0x39) or
82 (self >= 0x41 and self <= 0x46) or
83 (self >= 0x61 and self <= 0x66)
84 end
85
86 # `self` as a hexdigit to its byte value
87 #
88 # ~~~nit
89 # intrude import core::bytes
90 # assert 0x39.hexdigit_to_byteval == 0x09
91 # assert 0x43.hexdigit_to_byteval == 0x0C
92 # ~~~
93 #
94 # REQUIRE: `self.is_valid_hexdigit`
95 private fun hexdigit_to_byteval: Int do
96 if self >= 0x30 and self <= 0x39 then
97 return self - 0x30
98 else if self >= 0x41 and self <= 0x46 then
99 return self - 0x37
100 else if self >= 0x61 and self <= 0x66 then
101 return self - 0x57
102 end
103 # Happens only if the requirement is not met.
104 # i.e. this abort is here to please the compiler
105 abort
106 end
107
108 redef fun first_index_in_from(b, from) do
109 for i in [from .. b.length[ do if b[i] == self then return i
110 return -1
111 end
112
113 redef fun last_index_in_from(b, from) do
114 for i in [0 .. from].step(-1) do if b[i] == self then return i
115 return -1
116 end
117
118 redef fun search_all_in(b) do
119 var ret = new Array[Int]
120 var pos = 0
121 loop
122 pos = first_index_in_from(b, pos)
123 if pos == -1 then return ret
124 ret.add pos
125 pos += 1
126 end
127 end
128
129 redef fun pattern_length do return 1
130
131 redef fun append_to(b) do b.push self
132
133 # assert u'b'.is_suffix("baqsdb".to_bytes)
134 # assert not u'b'.is_suffix("baqsd".to_bytes)
135 redef fun is_suffix(b) do return b.length != 0 and b.last == self
136
137 # assert u'b'.is_prefix("baqsdb".to_bytes)
138 # assert not u'b'.is_prefix("aqsdb".to_bytes)
139 redef fun is_prefix(b) do return b.length != 0 and b.first == self
140
141 # A signed big-endian representation of `self`
142 #
143 # ~~~
144 # assert 1.to_bytes.hexdigest == "01"
145 # assert 255.to_bytes.hexdigest == "FF"
146 # assert 256.to_bytes.hexdigest == "0100"
147 # assert 65535.to_bytes.hexdigest == "FFFF"
148 # assert 65536.to_bytes.hexdigest == "010000"
149 # ~~~
150 #
151 # Negative values are converted to their two's complement.
152 # Be careful as the result can be ambiguous.
153 #
154 # ~~~
155 # assert (-1).to_bytes.hexdigest == "FF"
156 # assert (-32).to_bytes.hexdigest == "E0"
157 # assert (-512).to_bytes.hexdigest == "FE00"
158 # assert (-65794).to_bytes.hexdigest == "FEFEFE"
159 # ~~~
160 #
161 # Optionally, set `n_bytes` to the desired number of bytes in the output.
162 # This setting can disambiguate the result between positive and negative
163 # integers. Be careful with this parameter as the result may overflow.
164 #
165 # ~~~
166 # assert 1.to_bytes(2).hexdigest == "0001"
167 # assert 65535.to_bytes(2).hexdigest == "FFFF"
168 # assert (-1).to_bytes(2).hexdigest == "FFFF"
169 # assert (-512).to_bytes(4).hexdigest == "FFFFFE00"
170 # assert 0x123456.to_bytes(2).hexdigest == "3456"
171 # ~~~
172 #
173 # For 0, a Bytes object with single nul byte is returned (instead of an empty Bytes object).
174 #
175 # ~~~
176 # assert 0.to_bytes.hexdigest == "00"
177 # ~~~
178 #
179 # For positive integers, `Bytes::to_i` can reverse the operation.
180 #
181 # ~~~
182 # assert 1234.to_bytes.to_i == 1234
183 # ~~~
184 #
185 # Require self >= 0
186 fun to_bytes(n_bytes: nullable Int): Bytes do
187
188 # If 0, force using at least one byte
189 if self == 0 and n_bytes == null then n_bytes = 1
190
191 # Compute the len (log256)
192 var len = 1
193 var max = 256
194 var s = self.abs
195 while s >= max do
196 len += 1
197 max *= 256
198 end
199
200 # Two's complement
201 s = self
202 if self < 0 then
203 var ff = 0
204 for j in [0..len[ do
205 ff *= 0x100
206 ff += 0xFF
207 end
208
209 s = ((-self) ^ ff) + 1
210 end
211
212 # Cut long values
213 if n_bytes != null and len > n_bytes then len = n_bytes
214
215 # Allocate the buffer
216 var cap = n_bytes or else len
217 var res = new Bytes.with_capacity(cap)
218
219 var filler = if self < 0 then 0xFF else 0
220 for i in [0..cap[ do res[i] = filler
221
222 # Fill it starting with the end
223 var i = cap
224 var sum = s
225 while i > cap - len do
226 i -= 1
227 res[i] = sum % 256
228 sum /= 256
229 end
230
231 return res
232 end
233 end
234
235 # A buffer containing Byte-manipulation facilities
236 #
237 # Uses Copy-On-Write when persisted
238 class Bytes
239 super AbstractArray[Int]
240 super BytePattern
241
242 # A CString being a char*, it can be used as underlying representation here.
243 var items: CString
244
245 # Number of bytes in the array
246 redef var length
247
248 # Capacity of the array
249 private var capacity: Int
250
251 # Has this buffer been persisted (to_s'd)?
252 #
253 # Used for Copy-On-Write
254 private var persisted = false
255
256 # var b = new Bytes.empty
257 # assert b.to_s == ""
258 init empty do
259 var ns = new CString(0)
260 init(ns, 0, 0)
261 end
262
263 # Init a `Bytes` with capacity `cap`
264 init with_capacity(cap: Int) do
265 var ns = new CString(cap)
266 init(ns, 0, cap)
267 end
268
269 redef fun pattern_length do return length
270
271 redef fun is_empty do return length == 0
272
273 # var b = new Bytes.empty
274 # b.add 101
275 # assert b[0] == 101
276 redef fun [](i) do
277 assert i >= 0
278 assert i < length
279 return items[i]
280 end
281
282 # Returns a copy of `self`
283 fun clone: Bytes do
284 var b = new Bytes.with_capacity(length)
285 b.append(self)
286 return b
287 end
288
289 # Trims off the whitespaces at the beginning and the end of `self`
290 #
291 # var b = "102041426E6F1020" .hexdigest_to_bytes
292 # assert b.trim.hexdigest == "41426E6F"
293 #
294 # NOTE: A whitespace is defined here as a byte whose value is <= 0x20
295 fun trim: Bytes do
296 var st = 0
297 while st < length do
298 if self[st] > 0x20 then break
299 st += 1
300 end
301 if st >= length then return new Bytes.empty
302 var ed = length - 1
303 while ed > 0 do
304 if self[ed] > 0x20 then break
305 ed -= 1
306 end
307 return slice(st, ed - st + 1)
308 end
309
310 # Copy a subset of `self` starting at `from` and of `count` bytes
311 #
312 # var b = "abcd".to_bytes
313 # assert b.slice(1, 2).hexdigest == "6263"
314 # assert b.slice(-1, 2).hexdigest == "61"
315 # assert b.slice(1, 0).hexdigest == ""
316 # assert b.slice(2, 5).hexdigest == "6364"
317 fun slice(from, count: Int): Bytes do
318 if count <= 0 then return new Bytes.empty
319
320 if from < 0 then
321 count += from
322 if count < 0 then count = 0
323 from = 0
324 end
325
326 if (count + from) > length then count = length - from
327 if count <= 0 then return new Bytes.empty
328
329 var ret = new Bytes.with_capacity(count)
330
331 ret.append_ns(items.fast_cstring(from), count)
332 return ret
333 end
334
335 # Copy of `self` starting at `from`
336 #
337 # var b = "abcd".to_bytes
338 # assert b.slice_from(1).hexdigest == "626364"
339 # assert b.slice_from(-1).hexdigest == "61626364"
340 # assert b.slice_from(2).hexdigest == "6364"
341 fun slice_from(from: Int): Bytes do
342 if from >= length then return new Bytes.empty
343 if from < 0 then from = 0
344 return slice(from, length)
345 end
346
347 # Reverse the byte array in place
348 #
349 # var b = "abcd".to_bytes
350 # b.reverse
351 # assert b.to_s == "dcba"
352 fun reverse
353 do
354 var l = length
355 for i in [0..l/2[ do
356 var tmp = self[i]
357 self[i] = self[l-i-1]
358 self[l-i-1] = tmp
359 end
360 end
361
362 # Returns self as an hexadecimal digest.
363 #
364 # Also known as plain hexdump or postscript hexdump.
365 #
366 # ~~~
367 # var b = "abcd".to_bytes
368 # assert b.hexdigest == "61626364"
369 # assert b.hexdigest.hexdigest_to_bytes == b
370 # ~~~
371 fun hexdigest: String do
372 var elen = length * 2
373 var ns = new CString(elen)
374 var i = 0
375 var oi = 0
376 while i < length do
377 self[i].add_digest_at(ns, oi)
378 i += 1
379 oi += 2
380 end
381 return new FlatString.full(ns, elen, 0, elen)
382 end
383
384 # Return self as a C hexadecimal digest where bytes are prefixed by `\x`
385 #
386 # The output is compatible with literal stream of bytes for most languages
387 # including C and Nit.
388 #
389 # ~~~
390 # var b = "abcd".to_bytes
391 # assert b.chexdigest == "\\x61\\x62\\x63\\x64"
392 # assert b.chexdigest.unescape_to_bytes == b
393 # ~~~
394 fun chexdigest: String do
395 var elen = length * 4
396 var ns = new CString(elen)
397 var i = 0
398 var oi = 0
399 while i < length do
400 ns[oi] = u'\\'
401 ns[oi+1] = u'x'
402 self[i].add_digest_at(ns, oi+2)
403 i += 1
404 oi += 4
405 end
406 return new FlatString.full(ns, elen, 0, elen)
407 end
408
409
410 # Returns self as a stream of bits (0 and 1)
411 #
412 # ~~~
413 # var b = "abcd".to_bytes
414 # assert b.binarydigest == "01100001011000100110001101100100"
415 # assert b.binarydigest.binarydigest_to_bytes == b
416 # ~~~
417 fun binarydigest: String do
418 var elen = length * 8
419 var ns = new CString(elen)
420 var i = 0
421 var oi = 0
422 while i < length do
423 var c = self[i]
424 var b = 128
425 while b > 0 do
426 if c & b == 0 then
427 ns[oi] = u'0'
428 else
429 ns[oi] = u'1'
430 end
431 oi += 1
432 b = b >> 1
433 end
434 i += 1
435 end
436 return new FlatString.full(ns, elen, 0, elen)
437 end
438
439 # Interprets `self` as a big-endian integer (unsigned by default)
440 #
441 # ~~~
442 # var b = "0102".hexdigest_to_bytes
443 # assert b.to_i == 258
444 #
445 # assert "01".hexdigest_to_bytes.to_i == 1
446 # assert "FF".hexdigest_to_bytes.to_i == 255
447 # assert "0000".hexdigest_to_bytes.to_i == 0
448 # ~~~
449 #
450 # If `self.is_empty`, 0 is returned.
451 #
452 # ~~~
453 # assert "".hexdigest_to_bytes.to_i == 0
454 # ~~~
455 #
456 # If `signed == true`, the bytes are read as a signed integer.
457 # As usual, the sign bit is the left most bit, no matter the
458 # `length` of `self`.
459 #
460 # ~~~
461 # assert "01".hexdigest_to_bytes.to_i(true) == 1
462 # assert "FF".hexdigest_to_bytes.to_i(true) == -1
463 # assert "00FF".hexdigest_to_bytes.to_i(true) == 255
464 # assert "E0".hexdigest_to_bytes.to_i(true) == -32
465 # assert "FE00".hexdigest_to_bytes.to_i(true) == -512
466 # assert "FEFEFE".hexdigest_to_bytes.to_i(true) == -65794
467 # ~~~
468 #
469 # `Int::to_bytes` is a loosely reverse method.
470 #
471 # ~~~
472 # assert b.to_i.to_bytes == b
473 # assert (b.to_i + 1).to_bytes.hexdigest == "0103"
474 # assert "0001".hexdigest_to_bytes.to_i.to_bytes.hexdigest == "01"
475 #
476 # assert (-32).to_bytes.to_i(true) == -32
477 # ~~~
478 #
479 # Warning: `Int` might overflow for bytes with more than 60 bits.
480 fun to_i(signed: nullable Bool): Int do
481 var res = 0
482 var i = 0
483 while i < length do
484 res *= 256
485 res += self[i].to_i
486 i += 1
487 end
488
489 # Two's complement is `signed`
490 if signed == true and not_empty and first > 0x80 then
491 var ff = 0
492 for j in [0..length[ do
493 ff *= 0x100
494 ff += 0xFF
495 end
496
497 res = -((res ^ ff) + 1)
498 end
499
500 return res
501 end
502
503 # var b = new Bytes.with_capacity(1)
504 # b[0] = 101
505 # assert b.to_s == "e"
506 redef fun []=(i, v) do
507 if persisted then regen
508 assert i >= 0
509 assert i <= length
510 if i == length then add(v)
511 items[i] = v
512 end
513
514 # var b = new Bytes.empty
515 # b.add 101
516 # assert b.to_s == "e"
517 redef fun add(c) do
518 if persisted then regen
519 if length >= capacity then
520 enlarge(length)
521 end
522 items[length] = c
523 length += 1
524 end
525
526 # Adds the UTF-8 representation of `c` to `self`
527 #
528 # var b = new Bytes.empty
529 # b.add_char('A')
530 # b.add_char('キ')
531 # assert b.hexdigest == "41E382AD"
532 fun add_char(c: Char) do
533 if persisted then regen
534 var cln = c.u8char_len
535 var ln = length
536 enlarge(ln + cln)
537 items.set_char_at(length, c)
538 length += cln
539 end
540
541 # var b = new Bytes.empty
542 # b.append([104, 101, 108, 108, 111])
543 # assert b.to_s == "hello"
544 redef fun append(arr) do
545 if arr isa Bytes then
546 append_ns(arr.items, arr.length)
547 else
548 for i in arr do add i
549 end
550 end
551
552 # var b = new Bytes.empty
553 # b.append([0x41, 0x41, 0x18])
554 # b.pop
555 # assert b.to_s == "AA"
556 redef fun pop do
557 assert length >= 1
558 length -= 1
559 return items[length]
560 end
561
562 redef fun clear do length = 0
563
564 # Regenerates the buffer, necessary when it was persisted
565 private fun regen do
566 var nns = new CString(capacity)
567 items.copy_to(nns, length, 0, 0)
568 persisted = false
569 end
570
571 # Appends the `ln` first bytes of `ns` to self
572 fun append_ns(ns: CString, ln: Int) do
573 if persisted then regen
574 var nlen = length + ln
575 if nlen > capacity then enlarge(nlen)
576 ns.copy_to(items, ln, 0, length)
577 length += ln
578 end
579
580 # Appends `ln` bytes from `ns` starting at index `from` to self
581 fun append_ns_from(ns: CString, ln, from: Int) do
582 if persisted then regen
583 var nlen = length + ln
584 if nlen > capacity then enlarge(nlen)
585 ns.copy_to(items, ln, from, length)
586 length += ln
587 end
588
589 # Appends the bytes of `str` to `self`
590 fun append_text(str: Text) do str.append_to_bytes self
591
592 redef fun append_to(b) do b.append self
593
594 redef fun enlarge(sz) do
595 if capacity >= sz then return
596 persisted = false
597 if capacity < 16 then capacity = 16
598 while capacity < sz do capacity = capacity * 2 + 2
599 var ns = new CString(capacity)
600 items.copy_to(ns, length, 0, 0)
601 items = ns
602 end
603
604 redef fun to_s do
605 persisted = true
606 var b = self
607 var r = b.items.to_s_unsafe(length, copy=false)
608 if r != items then persisted = false
609 return r
610 end
611
612 redef fun iterator do return new BytesIterator.with_buffer(self)
613
614 redef fun first_index_in_from(b, from) do
615 if is_empty then return -1
616 var fst = self[0]
617 var bpos = fst.first_index_in_from(self, from)
618 for i in [0 .. length[ do
619 if self[i] != b[bpos] then return first_index_in_from(b, bpos + 1)
620 bpos += 1
621 end
622 return bpos
623 end
624
625 redef fun last_index_in_from(b, from) do
626 if is_empty then return -1
627 var lst = self[length - 1]
628 var bpos = lst.last_index_in_from(b, from)
629 for i in [0 .. length[.step(-1) do
630 if self[i] != b[bpos] then return last_index_in_from(b, bpos - 1)
631 bpos -= 1
632 end
633 return bpos
634 end
635
636 redef fun search_all_in(b) do
637 var ret = new Array[Int]
638 var pos = first_index_in_from(b, 0)
639 if pos == -1 then return ret
640 pos = pos + 1
641 ret.add pos
642 loop
643 pos = first_index_in_from(b, pos)
644 if pos == -1 then return ret
645 ret.add pos
646 pos += length
647 end
648 end
649
650 # Splits the content on self when encountering `b`
651 #
652 # var a = "String is string".to_bytes.split_with(u's')
653 # assert a.length == 3
654 # assert a[0].hexdigest == "537472696E672069"
655 # assert a[1].hexdigest == "20"
656 # assert a[2].hexdigest == "7472696E67"
657 fun split_with(b: BytePattern): Array[Bytes] do
658 var fst = b.search_all_in(self)
659 if fst.is_empty then return [clone]
660 var retarr = new Array[Bytes]
661 var prev = 0
662 for i in fst do
663 retarr.add(slice(prev, i - prev))
664 prev = i + b.pattern_length
665 end
666 retarr.add slice_from(prev)
667 return retarr
668 end
669
670 # Splits `self` in two parts at the first occurence of `b`
671 #
672 # var a = "String is string".to_bytes.split_once_on(u's')
673 # assert a[0].hexdigest == "537472696E672069"
674 # assert a[1].hexdigest == "20737472696E67"
675 fun split_once_on(b: BytePattern): Array[Bytes] do
676 var spl = b.first_index_in(self)
677 if spl == -1 then return [clone]
678 var ret = new Array[Bytes].with_capacity(2)
679 ret.add(slice(0, spl))
680 ret.add(slice_from(spl + b.pattern_length))
681 return ret
682 end
683
684 # Replaces all the occurences of `this` in `self` by `by`
685 #
686 # var b = "String is string".to_bytes.replace(0x20, 0x41)
687 # assert b.hexdigest == "537472696E6741697341737472696E67"
688 fun replace(pattern: BytePattern, bytes: BytePattern): Bytes do
689 if is_empty then return new Bytes.empty
690 var pos = pattern.search_all_in(self)
691 if pos.is_empty then return clone
692 var ret = new Bytes.with_capacity(length)
693 var prev = 0
694 for i in pos do
695 ret.append_ns(items.fast_cstring(prev), i - prev)
696 bytes.append_to ret
697 prev = i + pattern.pattern_length
698 end
699 ret.append(slice_from(pos.last + pattern.pattern_length))
700 return ret
701 end
702
703 # Decode `self` from percent (or URL) encoding to a clear string
704 #
705 # Invalid '%' are not decoded.
706 #
707 # assert "aBc09-._~".to_bytes.from_percent_encoding == "aBc09-._~".to_bytes
708 # assert "%25%28%29%3c%20%3e".to_bytes.from_percent_encoding == "%()< >".to_bytes
709 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".to_bytes.from_percent_encoding == ".com/post?e=asdf&f=123".to_bytes
710 # assert "%25%28%29%3C%20%3E".to_bytes.from_percent_encoding == "%()< >".to_bytes
711 # assert "incomplete %".to_bytes.from_percent_encoding == "incomplete %".to_bytes
712 # assert "invalid % usage".to_bytes.from_percent_encoding == "invalid % usage".to_bytes
713 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".to_bytes.from_percent_encoding == "éあいう".to_bytes
714 # assert "%1 %A %C3%A9A9".to_bytes.from_percent_encoding == "%1 %A éA9".to_bytes
715 fun from_percent_encoding: Bytes do
716 var tmp = new Bytes.with_capacity(length)
717 var pos = 0
718 while pos < length do
719 var b = self[pos]
720 if b != u'%' then
721 tmp.add b
722 pos += 1
723 continue
724 end
725 if length - pos < 2 then
726 tmp.add u'%'
727 pos += 1
728 continue
729 end
730 var bn = self[pos + 1]
731 var bnn = self[pos + 2]
732 if not bn.is_valid_hexdigit or not bnn.is_valid_hexdigit then
733 tmp.add u'%'
734 pos += 1
735 continue
736 end
737 tmp.add((bn.hexdigit_to_byteval << 4) + bnn.hexdigit_to_byteval)
738 pos += 3
739 end
740 return tmp
741 end
742
743 # Is `b` a prefix of `self` ?
744 fun has_prefix(b: BytePattern): Bool do return b.is_prefix(self)
745
746 # Is `b` a suffix of `self` ?
747 fun has_suffix(b: BytePattern): Bool do return b.is_suffix(self)
748
749 redef fun is_suffix(b) do
750 if length > b.length then return false
751 var j = b.length - 1
752 var i = length - 1
753 while i > 0 do
754 if self[i] != b[j] then return false
755 i -= 1
756 j -= 1
757 end
758 return true
759 end
760
761 redef fun is_prefix(b) do
762 if length > b.length then return false
763 for i in [0 .. length[ do if self[i] != b[i] then return false
764 return true
765 end
766 end
767
768 private class BytesIterator
769 super IndexedIterator[Int]
770
771 var tgt: CString
772
773 redef var index
774
775 var max: Int
776
777 init with_buffer(b: Bytes) do init(b.items, 0, b.length)
778
779 redef fun is_ok do return index < max
780
781 redef fun next do index += 1
782
783 redef fun item do return tgt[index]
784 end
785
786 redef class Text
787 # Returns a mutable copy of `self`'s bytes
788 #
789 # ~~~nit
790 # assert "String".to_bytes isa Bytes
791 # assert "String".to_bytes == [83, 116, 114, 105, 110, 103]
792 # ~~~
793 fun to_bytes: Bytes do
794 var b = new Bytes.with_capacity(byte_length)
795 append_to_bytes b
796 return b
797 end
798
799 # Is `self` a valid hexdigest ?
800 #
801 # assert "0B1d3F".is_valid_hexdigest
802 # assert not "5G".is_valid_hexdigest
803 fun is_valid_hexdigest: Bool do
804 for i in bytes do if not i.is_valid_hexdigit then return false
805 return true
806 end
807
808 # Appends `self.bytes` to `b`
809 fun append_to_bytes(b: Bytes) do
810 for s in substrings do
811 var from = if s isa FlatString then s.first_byte else 0
812 b.append_ns_from(s.items, s.byte_length, from)
813 end
814 end
815
816 # Returns a new `Bytes` instance with the digest as content
817 #
818 # assert "0B1F4D".hexdigest_to_bytes == [0x0B, 0x1F, 0x4D]
819 # assert "0B1F4D".hexdigest_to_bytes.hexdigest == "0B1F4D"
820 #
821 # Characters that are not hexadecimal digits are ignored.
822 #
823 # assert "z0B1 F4\nD".hexdigest_to_bytes.hexdigest == "0B1F4D"
824 # assert "\\x0b1 \\xf4d".hexdigest_to_bytes.hexdigest == "0B1F4D"
825 #
826 # When the number of hexadecimal digit is not even, then a leading 0 is
827 # implicitly considered to fill the left byte (the most significant one).
828 #
829 # assert "1".hexdigest_to_bytes.hexdigest == "01"
830 # assert "FFF".hexdigest_to_bytes.hexdigest == "0FFF"
831 #
832 # `Bytes::hexdigest` is a loosely reverse method since its
833 # results contain only pairs of uppercase hexadecimal digits.
834 #
835 # assert "ABCD".hexdigest_to_bytes.hexdigest == "ABCD"
836 # assert "a b c".hexdigest_to_bytes.hexdigest == "0ABC"
837 fun hexdigest_to_bytes: Bytes do
838 var b = bytes
839 var max = byte_length
840
841 var dlength = 0 # Number of hex digits
842 var pos = 0
843 while pos < max do
844 var c = b[pos]
845 if c.is_valid_hexdigit then dlength += 1
846 pos += 1
847 end
848
849 # Allocate the result buffer
850 var ret = new Bytes.with_capacity((dlength+1) / 2)
851
852 var i = (dlength+1) % 2 # current hex digit (1=high, 0=low)
853 var byte = 0 # current accumulated byte value
854
855 pos = 0
856 while pos < max do
857 var c = b[pos]
858 if c.is_valid_hexdigit then
859 byte = byte << 4 | c.hexdigit_to_byteval
860 i -= 1
861 if i < 0 then
862 # Last digit known: store and restart
863 ret.add byte
864 i = 1
865 byte = 0
866 end
867 end
868 pos += 1
869 end
870 return ret
871 end
872
873 # Gets the hexdigest of the bytes of `self`
874 #
875 # assert "&lt;STRING&#47;&rt;".hexdigest == "266C743B535452494E47262334373B2672743B"
876 fun hexdigest: String do
877 var ln = byte_length
878 var outns = new CString(ln * 2)
879 var oi = 0
880 for i in [0 .. ln[ do
881 bytes[i].add_digest_at(outns, oi)
882 oi += 2
883 end
884 return new FlatString.with_infos(outns, ln * 2, 0)
885 end
886
887 # Return a `Bytes` instance where Nit escape sequences are transformed.
888 #
889 # assert "B\\n\\x41\\u0103D3".unescape_to_bytes.hexdigest == "420A41F0908F93"
890 #
891 # `Bytes::chexdigest` is a loosely reverse methods since its result is only made
892 # of `"\x??"` escape sequences.
893 #
894 # assert "\\x41\\x42\\x43".unescape_to_bytes.chexdigest == "\\x41\\x42\\x43"
895 # assert "B\\n\\x41\\u0103D3".unescape_to_bytes.chexdigest == "\\x42\\x0A\\x41\\xF0\\x90\\x8F\\x93"
896 fun unescape_to_bytes: Bytes do
897 var res = new Bytes.with_capacity(self.byte_length)
898 var was_slash = false
899 var i = 0
900 while i < length do
901 var c = self[i]
902 if not was_slash then
903 if c == '\\' then
904 was_slash = true
905 else
906 res.add_char(c)
907 end
908 i += 1
909 continue
910 end
911 was_slash = false
912 if c == 'n' then
913 res.add_char('\n')
914 else if c == 'r' then
915 res.add_char('\r')
916 else if c == 't' then
917 res.add_char('\t')
918 else if c == '0' then
919 res.add_char('\0')
920 else if c == 'x' or c == 'X' then
921 var hx = substring(i + 1, 2)
922 if hx.is_hex then
923 res.add hx.to_hex
924 else
925 res.add_char(c)
926 end
927 i += 2
928 else if c == 'u' or c == 'U' then
929 var hx = substring(i + 1, 6)
930 if hx.is_hex then
931 res.add_char(hx.to_hex.code_point)
932 else
933 res.add_char(c)
934 end
935 i += 6
936 else
937 res.add_char(c)
938 end
939 i += 1
940 end
941 return res
942 end
943
944 # Return a `Bytes` by reading 0 and 1.
945 #
946 # assert "1010101100001101".binarydigest_to_bytes.hexdigest == "AB0D"
947 #
948 # Note that characters that are neither 0 or 1 are just ignored.
949 #
950 # assert "a1B01 010\n1100あ001101".binarydigest_to_bytes.hexdigest == "AB0D"
951 # assert "hello".binarydigest_to_bytes.is_empty
952 #
953 # When the number of bits is not divisible by 8, then leading 0 are
954 # implicitly considered to fill the left byte (the most significant one).
955 #
956 # assert "1".binarydigest_to_bytes.hexdigest == "01"
957 # assert "1111111".binarydigest_to_bytes.hexdigest == "7F"
958 # assert "1000110100".binarydigest_to_bytes.hexdigest == "0234"
959 #
960 # `Bytes::binarydigest` is a loosely reverse method since its
961 # results contain only 1 and 0 by blocks of 8.
962 #
963 # assert "1010101100001101".binarydigest_to_bytes.binarydigest == "1010101100001101"
964 # assert "1".binarydigest_to_bytes.binarydigest == "00000001"
965 fun binarydigest_to_bytes: Bytes
966 do
967 var b = bytes
968 var max = byte_length
969
970 # Count bits
971 var bitlen = 0
972 var pos = 0
973 while pos < max do
974 var c = b[pos]
975 pos += 1
976 if c == u'0' or c == u'1' then bitlen += 1
977 end
978
979 # Allocate (and take care of the padding)
980 var ret = new Bytes.with_capacity((bitlen+7) / 8)
981
982 var i = (bitlen+7) % 8 # current bit (7th=128, 0th=1)
983 var byte = 0 # current accumulated byte value
984
985 pos = 0
986 while pos < max do
987 var c = b[pos]
988 pos += 1
989 if c == u'0' then
990 byte = byte << 1
991 else if c == u'1' then
992 byte = byte << 1 | 1
993 else
994 continue
995 end
996
997 i -= 1
998 if i < 0 then
999 # Last bit known: store and restart
1000 ret.add byte
1001 i = 7
1002 byte = 0
1003 end
1004 end
1005 return ret
1006 end
1007 end
1008
1009 redef class FlatText
1010 redef fun append_to_bytes(b) do
1011 var from = if self isa FlatString then first_byte else 0
1012 if isset _items then b.append_ns_from(items, byte_length, from)
1013 end
1014 end
1015
1016 redef class CString
1017 # Creates a new `Bytes` object from `self` with `len` as length
1018 #
1019 # If `len` is null, strlen will determine the length of the Bytes
1020 fun to_bytes(len: nullable Int): Bytes do
1021 if len == null then len = cstring_length
1022 return new Bytes(self, len, len)
1023 end
1024
1025 # Creates a new `Bytes` object from a copy of `self` with `len` as length
1026 #
1027 # If `len` is null, strlen will determine the length of the Bytes
1028 fun to_bytes_with_copy(len: nullable Int): Bytes do
1029 if len == null then len = cstring_length
1030 var nns = new CString(len)
1031 copy_to(nns, len, 0, 0)
1032 return new Bytes(nns, len, len)
1033 end
1034 end
1035
1036 # Joins an array of bytes `arr` separated by `sep`
1037 #
1038 # assert join_bytes(["String".to_bytes, "is".to_bytes, "string".to_bytes], u' ').hexdigest == "537472696E6720697320737472696E67"
1039 fun join_bytes(arr: Array[Bytes], sep: nullable BytePattern): Bytes do
1040 if arr.is_empty then return new Bytes.empty
1041 sep = sep or else new Bytes.empty
1042 var endln = sep.pattern_length * (arr.length - 1)
1043 for i in arr do endln += i.length
1044 var ret = new Bytes.with_capacity(endln)
1045 ret.append(arr.first)
1046 for i in [1 .. arr.length[ do
1047 sep.append_to(ret)
1048 ret.append arr[i]
1049 end
1050 return ret
1051 end