Merge: Stringify Bytes
authorJean Privat <jean@pryen.org>
Thu, 3 Dec 2015 20:59:29 +0000 (15:59 -0500)
committerJean Privat <jean@pryen.org>
Thu, 3 Dec 2015 20:59:29 +0000 (15:59 -0500)
This PR adds some String-like functions to Bytes, along with an abstraction for Byte-based patterns.

Also, a bug was found within `Bytes::is_empty` and `FlatText` is now public since there was no real rationale to keep it private

Pull-Request: #1860
Reviewed-by: Jean Privat <jean@pryen.org>
Reviewed-by: Alexis Laferrière <alexis.laf@xymus.net>

1  2 
lib/core/bytes.nit
lib/core/text/abstract_text.nit

@@@ -379,21 -606,26 +672,38 @@@ redef class FlatTex
  end
  
  redef class NativeString
 -      # Creates a new `Bytes` object from `self` with `strlen` as length
 -      fun to_bytes: Bytes do
 -              var len = cstring_length
 +      # Creates a new `Bytes` object from `self` with `len` as length
 +      #
 +      # If `len` is null, strlen will determine the length of the Bytes
 +      fun to_bytes(len: nullable Int): Bytes do
 +              if len == null then len = cstring_length
                return new Bytes(self, len, len)
        end
 +
 +      # Creates a new `Bytes` object from a copy of `self` with `len` as length
 +      #
 +      # If `len` is null, strlen will determine the length of the Bytes
 +      fun to_bytes_with_copy(len: nullable Int): Bytes do
 +              if len == null then len = cstring_length
 +              var nns = new NativeString(len)
 +              copy_to(nns, len, 0, 0)
 +              return new Bytes(nns, len, len)
 +      end
  end
+ # Joins an array of bytes `arr` separated by `sep`
+ #
+ #     assert join_bytes(["String".to_bytes, "is".to_bytes, "string".to_bytes], ' '.ascii).hexdigest == "537472696E6720697320737472696E67"
+ fun join_bytes(arr: Array[Bytes], sep: nullable BytePattern): Bytes do
+       if arr.is_empty then return new Bytes.empty
+       sep = sep or else new Bytes.empty
+       var endln = sep.pattern_length * (arr.length - 1)
+       for i in arr do endln += i.length
+       var ret = new Bytes.with_capacity(endln)
+       ret.append(arr.first)
+       for i in  [1 .. arr.length[ do
+               sep.append_to(ret)
+               ret.append arr[i]
+       end
+       return ret
+ end
Simple merge