3f5bee80b5d716ef7c54de8b478ac3b0803dafcd
[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[Byte]): 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[Byte], 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[Byte]): 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[Byte], 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[Byte]): 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[Byte]) is abstract
44
45 # Is `self` a prefix for `b` ?
46 fun is_prefix(b: SequenceRead[Byte]): Bool is abstract
47
48 # Is `self` a suffix for `b` ?
49 fun is_suffix(b: SequenceRead[Byte]): Bool is abstract
50 end
51
52 redef class Byte
53 super BytePattern
54
55 # Write self as a string into `ns` at position `pos`
56 private fun add_digest_at(ns: NativeString, pos: Int) do
57 var tmp = (0xF0u8 & self) >> 4
58 ns[pos] = if tmp >= 0x0Au8 then tmp + 0x37u8 else tmp + 0x30u8
59 tmp = 0x0Fu8 & self
60 ns[pos + 1] = if tmp >= 0x0Au8 then tmp + 0x37u8 else tmp + 0x30u8
61 end
62
63 # Is `self` a valid hexadecimal digit (in ASCII)
64 #
65 # ~~~nit
66 # intrude import core::bytes
67 # assert not '/'.ascii.is_valid_hexdigit
68 # assert '0'.ascii.is_valid_hexdigit
69 # assert '9'.ascii.is_valid_hexdigit
70 # assert not ':'.ascii.is_valid_hexdigit
71 # assert not '@'.ascii.is_valid_hexdigit
72 # assert 'A'.ascii.is_valid_hexdigit
73 # assert 'F'.ascii.is_valid_hexdigit
74 # assert not 'G'.ascii.is_valid_hexdigit
75 # assert not '`'.ascii.is_valid_hexdigit
76 # assert 'a'.ascii.is_valid_hexdigit
77 # assert 'f'.ascii.is_valid_hexdigit
78 # assert not 'g'.ascii.is_valid_hexdigit
79 # ~~~
80 private fun is_valid_hexdigit: Bool do
81 return (self >= 0x30u8 and self <= 0x39u8) or
82 (self >= 0x41u8 and self <= 0x46u8) or
83 (self >= 0x61u8 and self <= 0x66u8)
84 end
85
86 # `self` as a hexdigit to its byte value
87 #
88 # ~~~nit
89 # intrude import core::bytes
90 # assert 0x39u8.hexdigit_to_byteval == 0x09u8
91 # assert 0x43u8.hexdigit_to_byteval == 0x0Cu8
92 # ~~~
93 #
94 # REQUIRE: `self.is_valid_hexdigit`
95 private fun hexdigit_to_byteval: Byte do
96 if self >= 0x30u8 and self <= 0x39u8 then
97 return self - 0x30u8
98 else if self >= 0x41u8 and self <= 0x46u8 then
99 return self - 0x37u8
100 else if self >= 0x61u8 and self <= 0x66u8 then
101 return self - 0x57u8
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 'b'.ascii.is_suffix("baqsdb".to_bytes)
134 # assert not 'b'.ascii.is_suffix("baqsd".to_bytes)
135 redef fun is_suffix(b) do return b.length != 0 and b.last == self
136
137 # assert 'b'.ascii.is_prefix("baqsdb".to_bytes)
138 # assert not 'b'.ascii.is_prefix("aqsdb".to_bytes)
139 redef fun is_prefix(b) do return b.length != 0 and b.first == self
140 end
141
142 # A buffer containing Byte-manipulation facilities
143 #
144 # Uses Copy-On-Write when persisted
145 class Bytes
146 super AbstractArray[Byte]
147 super BytePattern
148
149 # A NativeString being a char*, it can be used as underlying representation here.
150 var items: NativeString
151
152 # Number of bytes in the array
153 redef var length
154
155 # Capacity of the array
156 private var capacity: Int
157
158 # Has this buffer been persisted (to_s'd)?
159 #
160 # Used for Copy-On-Write
161 private var persisted = false
162
163 # var b = new Bytes.empty
164 # assert b.to_s == ""
165 init empty do
166 var ns = new NativeString(0)
167 init(ns, 0, 0)
168 end
169
170 # Init a `Bytes` with capacity `cap`
171 init with_capacity(cap: Int) do
172 var ns = new NativeString(cap)
173 init(ns, 0, cap)
174 end
175
176 redef fun pattern_length do return length
177
178 redef fun is_empty do return length == 0
179
180 # var b = new Bytes.empty
181 # b.add 101u8
182 # assert b[0] == 101u8
183 redef fun [](i) do
184 assert i >= 0
185 assert i < length
186 return items[i]
187 end
188
189 # Returns a copy of `self`
190 fun clone: Bytes do
191 var b = new Bytes.with_capacity(length)
192 b.append(self)
193 return b
194 end
195
196 # Trims off the whitespaces at the beginning and the end of `self`
197 #
198 # var b = "102041426E6F1020" .hexdigest_to_bytes
199 # assert b.trim.hexdigest == "41426E6F"
200 #
201 # NOTE: A whitespace is defined here as a byte whose value is <= 0x20
202 fun trim: Bytes do
203 var st = 0
204 while st < length do
205 if self[st] > 0x20u8 then break
206 st += 1
207 end
208 if st >= length then return new Bytes.empty
209 var ed = length - 1
210 while ed > 0 do
211 if self[ed] > 0x20u8 then break
212 ed -= 1
213 end
214 return slice(st, ed - st + 1)
215 end
216
217 # Returns a subset of the content of `self` starting at `from` and of length `count`
218 #
219 # var b = "abcd".to_bytes
220 # assert b.slice(1, 2).hexdigest == "6263"
221 # assert b.slice(-1, 2).hexdigest == "61"
222 # assert b.slice(1, 0).hexdigest == ""
223 # assert b.slice(2, 5).hexdigest == "6364"
224 fun slice(from, count: Int): Bytes do
225 if count <= 0 then return new Bytes.empty
226
227 if from < 0 then
228 count += from
229 if count < 0 then count = 0
230 from = 0
231 end
232
233 if (count + from) > length then count = length - from
234 if count <= 0 then return new Bytes.empty
235
236 var ret = new Bytes.with_capacity(count)
237
238 ret.append_ns(items.fast_cstring(from), count)
239 return ret
240 end
241
242 # Returns a copy of `self` starting at `from`
243 #
244 # var b = "abcd".to_bytes
245 # assert b.slice_from(1).hexdigest == "626364"
246 # assert b.slice_from(-1).hexdigest == "61626364"
247 # assert b.slice_from(2).hexdigest == "6364"
248 fun slice_from(from: Int): Bytes do
249 if from >= length then return new Bytes.empty
250 if from < 0 then from = 0
251 return slice(from, length)
252 end
253
254 # Returns self as a hexadecimal digest
255 fun hexdigest: String do
256 var elen = length * 2
257 var ns = new NativeString(elen)
258 var i = 0
259 var oi = 0
260 while i < length do
261 self[i].add_digest_at(ns, oi)
262 i += 1
263 oi += 2
264 end
265 return new FlatString.full(ns, elen, 0, elen - 1, elen)
266 end
267
268 # var b = new Bytes.with_capacity(1)
269 # b[0] = 101u8
270 # assert b.to_s == "e"
271 redef fun []=(i, v) do
272 if persisted then regen
273 assert i >= 0
274 assert i <= length
275 if i == length then add(v)
276 items[i] = v
277 end
278
279 # var b = new Bytes.empty
280 # b.add 101u8
281 # assert b.to_s == "e"
282 redef fun add(c) do
283 if persisted then regen
284 if length >= capacity then
285 enlarge(length)
286 end
287 items[length] = c
288 length += 1
289 end
290
291 # var b = new Bytes.empty
292 # b.append([104u8, 101u8, 108u8, 108u8, 111u8])
293 # assert b.to_s == "hello"
294 redef fun append(arr) do
295 if arr isa Bytes then
296 append_ns(arr.items, arr.length)
297 else
298 for i in arr do add i
299 end
300 end
301
302 # var b = new Bytes.empty
303 # b.append([0x41u8, 0x41u8, 0x18u8])
304 # b.pop
305 # assert b.to_s == "AA"
306 redef fun pop do
307 assert length >= 1
308 length -= 1
309 return items[length]
310 end
311
312 redef fun clear do length = 0
313
314 # Regenerates the buffer, necessary when it was persisted
315 private fun regen do
316 var nns = new NativeString(capacity)
317 items.copy_to(nns, length, 0, 0)
318 persisted = false
319 end
320
321 # Appends the `ln` first bytes of `ns` to self
322 fun append_ns(ns: NativeString, ln: Int) do
323 if persisted then regen
324 var nlen = length + ln
325 if nlen > capacity then enlarge(nlen)
326 ns.copy_to(items, ln, 0, length)
327 length += ln
328 end
329
330 # Appends `ln` bytes from `ns` starting at index `from` to self
331 fun append_ns_from(ns: NativeString, ln, from: Int) do
332 if persisted then regen
333 var nlen = length + ln
334 if nlen > capacity then enlarge(nlen)
335 ns.copy_to(items, ln, from, length)
336 length += ln
337 end
338
339 # Appends the bytes of `s` to `selftextextt`
340 fun append_text(s: Text) do
341 for i in s.substrings do
342 append_ns(i.fast_cstring, i.bytelen)
343 end
344 end
345
346 redef fun append_to(b) do b.append self
347
348 redef fun enlarge(sz) do
349 if capacity >= sz then return
350 persisted = false
351 while capacity < sz do capacity = capacity * 2 + 2
352 var ns = new NativeString(capacity)
353 items.copy_to(ns, length, 0, 0)
354 items = ns
355 end
356
357 redef fun to_s do
358 persisted = true
359 var b = self
360 var r = b.items.to_s_with_length(length)
361 if r != items then persisted = false
362 return r
363 end
364
365 redef fun iterator do return new BytesIterator.with_buffer(self)
366
367 redef fun first_index_in_from(b, from) do
368 if is_empty then return -1
369 var fst = self[0]
370 var bpos = fst.first_index_in_from(self, from)
371 for i in [0 .. length[ do
372 if self[i] != b[bpos] then return first_index_in_from(b, bpos + 1)
373 bpos += 1
374 end
375 return bpos
376 end
377
378 redef fun last_index_in_from(b, from) do
379 if is_empty then return -1
380 var lst = self[length - 1]
381 var bpos = lst.last_index_in_from(b, from)
382 for i in [0 .. length[.step(-1) do
383 if self[i] != b[bpos] then return last_index_in_from(b, bpos - 1)
384 bpos -= 1
385 end
386 return bpos
387 end
388
389 redef fun search_all_in(b) do
390 var ret = new Array[Int]
391 var pos = first_index_in_from(b, 0)
392 if pos == -1 then return ret
393 pos = pos + 1
394 ret.add pos
395 loop
396 pos = first_index_in_from(b, pos)
397 if pos == -1 then return ret
398 ret.add pos
399 pos += length
400 end
401 end
402
403 # Splits the content on self when encountering `b`
404 #
405 # var a = "String is string".to_bytes.split_with('s'.ascii)
406 # assert a.length == 3
407 # assert a[0].hexdigest == "537472696E672069"
408 # assert a[1].hexdigest == "20"
409 # assert a[2].hexdigest == "7472696E67"
410 fun split_with(b: BytePattern): Array[Bytes] do
411 var fst = b.search_all_in(self)
412 if fst.is_empty then return [clone]
413 var retarr = new Array[Bytes]
414 var prev = 0
415 for i in fst do
416 retarr.add(slice(prev, i - prev))
417 prev = i + b.pattern_length
418 end
419 retarr.add slice_from(prev)
420 return retarr
421 end
422
423 # Splits `self` in two parts at the first occurence of `b`
424 #
425 # var a = "String is string".to_bytes.split_once_on('s'.ascii)
426 # assert a[0].hexdigest == "537472696E672069"
427 # assert a[1].hexdigest == "20737472696E67"
428 fun split_once_on(b: BytePattern): Array[Bytes] do
429 var spl = b.first_index_in(self)
430 if spl == -1 then return [clone]
431 var ret = new Array[Bytes].with_capacity(2)
432 ret.add(slice(0, spl))
433 ret.add(slice_from(spl + b.pattern_length))
434 return ret
435 end
436
437 # Replaces all the occurences of `this` in `self` by `by`
438 #
439 # var b = "String is string".to_bytes.replace(0x20u8, 0x41u8)
440 # assert b.hexdigest == "537472696E6741697341737472696E67"
441 fun replace(pattern: BytePattern, bytes: BytePattern): Bytes do
442 if is_empty then return new Bytes.empty
443 var pos = pattern.search_all_in(self)
444 if pos.is_empty then return clone
445 var ret = new Bytes.with_capacity(length)
446 var prev = 0
447 for i in pos do
448 ret.append_ns(items.fast_cstring(prev), i - prev)
449 bytes.append_to ret
450 prev = i + pattern.pattern_length
451 end
452 ret.append(slice_from(pos.last + pattern.pattern_length))
453 return ret
454 end
455
456 # Decode `self` from percent (or URL) encoding to a clear string
457 #
458 # Replace invalid use of '%' with '?'.
459 #
460 # assert "aBc09-._~".to_bytes.from_percent_encoding == "aBc09-._~".to_bytes
461 # assert "%25%28%29%3c%20%3e".to_bytes.from_percent_encoding == "%()< >".to_bytes
462 # assert ".com%2fpost%3fe%3dasdf%26f%3d123".to_bytes.from_percent_encoding == ".com/post?e=asdf&f=123".to_bytes
463 # assert "%25%28%29%3C%20%3E".to_bytes.from_percent_encoding == "%()< >".to_bytes
464 # assert "incomplete %".to_bytes.from_percent_encoding == "incomplete ?".to_bytes
465 # assert "invalid % usage".to_bytes.from_percent_encoding == "invalid ? usage".to_bytes
466 # assert "%c3%a9%e3%81%82%e3%81%84%e3%81%86".to_bytes.from_percent_encoding == "éあいう".to_bytes
467 fun from_percent_encoding: Bytes do
468 var tmp = new Bytes.with_capacity(length)
469 var pos = 0
470 while pos < length do
471 var b = self[pos]
472 if b != '%'.ascii then
473 tmp.add b
474 pos += 1
475 continue
476 end
477 if length - pos < 2 then
478 tmp.add '?'.ascii
479 pos += 1
480 continue
481 end
482 var bn = self[pos + 1]
483 var bnn = self[pos + 2]
484 if not bn.is_valid_hexdigit or not bnn.is_valid_hexdigit then
485 tmp.add '?'.ascii
486 pos += 1
487 continue
488 end
489 tmp.add((bn.hexdigit_to_byteval << 4) + bnn.hexdigit_to_byteval)
490 pos += 3
491 end
492 return tmp
493 end
494
495 # Is `b` a prefix of `self` ?
496 fun has_prefix(b: BytePattern): Bool do return b.is_prefix(self)
497
498 # Is `b` a suffix of `self` ?
499 fun has_suffix(b: BytePattern): Bool do return b.is_suffix(self)
500
501 redef fun is_suffix(b) do
502 if length > b.length then return false
503 var j = b.length - 1
504 var i = length - 1
505 while i > 0 do
506 if self[i] != b[j] then return false
507 i -= 1
508 j -= 1
509 end
510 return true
511 end
512
513 redef fun is_prefix(b) do
514 if length > b.length then return false
515 for i in [0 .. length[ do if self[i] != b[i] then return false
516 return true
517 end
518 end
519
520 private class BytesIterator
521 super IndexedIterator[Byte]
522
523 var tgt: NativeString
524
525 redef var index
526
527 var max: Int
528
529 init with_buffer(b: Bytes) do init(b.items, 0, b.length)
530
531 redef fun is_ok do return index < max
532
533 redef fun next do index += 1
534
535 redef fun item do return tgt[index]
536 end
537
538 redef class Text
539 # Returns a mutable copy of `self`'s bytes
540 #
541 # ~~~nit
542 # assert "String".to_bytes isa Bytes
543 # assert "String".to_bytes == [83u8, 116u8, 114u8, 105u8, 110u8, 103u8]
544 # ~~~
545 fun to_bytes: Bytes do
546 var b = new Bytes.with_capacity(bytelen)
547 append_to_bytes b
548 return b
549 end
550
551 # Is `self` a valid hexdigest ?
552 #
553 # assert "0B1d3F".is_valid_hexdigest
554 # assert not "5G".is_valid_hexdigest
555 fun is_valid_hexdigest: Bool do
556 for i in bytes do if not i.is_valid_hexdigit then return false
557 return true
558 end
559
560 # Appends `self.bytes` to `b`
561 fun append_to_bytes(b: Bytes) do
562 for s in substrings do
563 var from = if s isa FlatString then s.first_byte else 0
564 b.append_ns_from(s.items, s.bytelen, from)
565 end
566 end
567
568 # Returns a new `Bytes` instance with the digest as content
569 #
570 # assert "0B1F4D".hexdigest_to_bytes == [0x0Bu8, 0x1Fu8, 0x4Du8]
571 #
572 # REQUIRE: `self` is a valid hexdigest and hexdigest.length % 2 == 0
573 fun hexdigest_to_bytes: Bytes do
574 var b = bytes
575 var pos = 0
576 var max = bytelen
577 var ret = new Bytes.with_capacity(max / 2)
578 while pos < max do
579 ret.add((b[pos].hexdigit_to_byteval << 4) |
580 b[pos + 1].hexdigit_to_byteval)
581 pos += 2
582 end
583 return ret
584 end
585
586 # Gets the hexdigest of the bytes of `self`
587 #
588 # assert "&lt;STRING&#47;&rt;".hexdigest == "266C743B535452494E47262334373B2672743B"
589 fun hexdigest: String do
590 var ln = bytelen
591 var outns = new NativeString(ln * 2)
592 var oi = 0
593 for i in [0 .. ln[ do
594 bytes[i].add_digest_at(outns, oi)
595 oi += 2
596 end
597 return new FlatString.with_infos(outns, ln * 2, 0, ln * 2 - 1)
598 end
599 end
600
601 redef class FlatText
602 redef fun append_to_bytes(b) do
603 var from = if self isa FlatString then first_byte else 0
604 b.append_ns_from(items, bytelen, from)
605 end
606 end
607
608 redef class NativeString
609 # Creates a new `Bytes` object from `self` with `strlen` as length
610 fun to_bytes: Bytes do
611 var len = cstring_length
612 return new Bytes(self, len, len)
613 end
614 end