;; -*- geiser-scheme-implementation: guile -*-

;; Copyright 2019 Christopher Howard

;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

(define-module (buffer tests))

(use-modules (buffer)
             (srfi srfi-64)
             (rnrs bytevectors))

;; Initialize and give a name to a simple testsuite.
(test-begin "circular-bytevector-copy-test")

(define bv1 #vu8(0 1 2 3 4 5))
(define bv2 (u8-list->bytevector (list 10 11 12 13 14 15 16)))

(circular-bytevector-copy! bv1 2 bv2 1 2)
(test-equal bv2 #vu8(10 2 3 13 14 15 16))

(define bv2 (u8-list->bytevector (list 10 11 12 13 14 15 16)))
(circular-bytevector-copy! bv1 4 bv2 1 4)
(test-equal bv2 #vu8(10 4 5 0 1 15 16))

(define bv2 (u8-list->bytevector (list 10 11 12 13 14 15 16)))
(circular-bytevector-copy! bv1 1 bv2 5 4)
(test-equal bv2 #vu8(3 4 12 13 14 1 2))

(define bv2 (u8-list->bytevector (list 10 11 12 13 14 15 16)))
(circular-bytevector-copy! bv1 4 bv2 5 4)
(test-equal bv2 #vu8(0 1 12 13 14 4 5))

(define bv2 (u8-list->bytevector (list 10 11 12 13 14 15 16)))
(circular-bytevector-copy! bv1 1 bv2 3 21)
(test-equal bv2 #vu8(1 2 3 3 4 5 0))

(test-end "circular-bytevector-copy-test")

(test-begin "consumable-buffer-test")

(define c (make-consumable-buffer 10 0))
(define b (u8-list->bytevector (list 0 1 2 3 4 5 6)))
(define b2 (make-bytevector 8 0))
(insert! b 0 5 c)
(consume! c b2 1 4)
(test-equal b2 #vu8(0 0 1 2 3 0 0 0))

(define c (make-consumable-buffer 10 0))
(define b (u8-list->bytevector (list 0 1 2 3 4 5 6 7 8 9)))
(define b2 (make-bytevector 8 0))
(define b3 (make-bytevector 8 0))
(insert! b 0 8 c)
(consume! c b2 0 8)
(test-equal b2 #vu8(0 1 2 3 4 5 6 7))
(insert! b 2 4 c)
(test-equal (edible-bytes c) 4)
(test-equal (bytes-free c) 6)
(test-equal (buffer-capacity c) 10)
(consume! c b3 0 4)
(test-equal b3 #vu8(2 3 4 5 0 0 0 0))

(define c (make-consumable-buffer 10 0))
(define b (u8-list->bytevector (list 0 1 2 3 4 5 6 7 8 9)))
(define b2 (make-bytevector 16 0))
(test-error 'insufficient-edible-bytes (consume! c b 0 1))
(test-error 'insufficient-free-bytes (insert! b2 0 11 c))

(test-end "consumable-buffer-test")