~theothornhill/cl-bare

a2a343e6c9fa2888b71f1526ab0791ef7ade5940 — Theodor Thornhill 3 years ago eb0f11d
Add arbitrary length array
3 files changed, 44 insertions(+), 7 deletions(-)

M src/bare.lisp
M src/package.lisp
M tests/bare-tests.lisp
M src/bare.lisp => src/bare.lisp +20 -2
@@ 160,12 160,30 @@ Set this dynamically in the function calling the DATA defbinary.")
        (write-byte 1 stream)
        (write-binary object stream))))

(defun read-array (type length stream)
(defun read-array (type stream)
  (let ((size (read-binary 'uint stream))
        res)
    (with-slots (value) size
      (dotimes (i value)
        (push (read-binary type stream) res)))
    (nreverse res)))

(defun write-array (objects stream)
  (let ((size (length objects)))
    (write-binary (read-binary
                   'uint
                   (flex:make-in-memory-input-stream
                    (vector size)))
                  stream)
    (dotimes (i size)
      (write-binary (nth i objects) stream))))

(defun read-array-fixed (type length stream)
  (let (res)
    (dotimes (i length)
      (push (read-binary type stream) res))
    (nreverse res)))

(defun write-array (objects stream)
(defun write-array-fixed (objects stream)
  (dolist (object objects)
    (write-binary object stream)))

M src/package.lisp => src/package.lisp +2 -0
@@ 24,4 24,6 @@
   :write-optional-type
   :read-array
   :write-array
   :read-array-fixed
   :write-array-fixed
   :value))

M tests/bare-tests.lisp => tests/bare-tests.lisp +22 -5
@@ 190,15 190,32 @@
        (with-slots (value) object
          (ok (equalp value 112)))))))

(deftest array-type-test
  (testing "reading and writing array type when not set"
(deftest array-test
  (testing "reading and writing array"
    (with-input-from-sequence
        (in
         (with-output-to-sequence (out)
           (write-array
            (read-array 'u8 4 (buf #(#x11 #x22 #x33 #x44)))
           (write-array (read-array 'u8 (buf #(#x04 #x11 #x22 #x33 #x44)))
            out)))
      (let ((objects (read-array 'u8 4 in)))
      (let ((objects (read-array 'u8 in)))
        (with-slots (value) (first objects)
          (ok (= value 17)))
        (with-slots (value) (second objects)
          (ok (= value 34)))
        (with-slots (value) (third objects)
          (ok (= value 51)))
        (with-slots (value) (fourth objects)
          (ok (= value 68)))))))

(deftest array-fixed-test
  (testing "reading and writing array-fixed"
    (with-input-from-sequence
        (in
         (with-output-to-sequence (out)
           (write-array-fixed
            (read-array-fixed 'u8 4 (buf #(#x11 #x22 #x33 #x44)))
            out)))
      (let ((objects (read-array-fixed 'u8 4 in)))
        (with-slots (value) (first objects)
          (ok (= value 17)))
        (with-slots (value) (second objects)