Adding blender exporter
[lodematron.git] / lodematron-binary.lisp
blobbde0a2deaa046a2b8de74c7d93efd4d438af18a7
2 (in-package :lodematron)
5 ;; buffering binary files --------------------
7 ;; read and write an entire file to memory in one go
8 (defun read-file-to-usb8-array (filepath)
9 "Opens a reads a file. Returns the contents as single unsigned-byte array"
10 (with-open-file (in filepath :direction :input :element-type '(unsigned-byte 8))
11 (let* ((file-len (file-length in))
12 (usb8 (make-array file-len :element-type '(unsigned-byte 8)))
13 (pos (read-sequence usb8 in)))
14 (unless (= file-len pos)
15 (error "Length read (~D) doesn't match file length (~D)~%" pos file-len))
16 usb8)))
18 (defun write-usb8-array-to-file (usb8 file)
19 "Opens a reads a file. Returns the contents as single unsigned-byte array"
20 (with-open-file (out file :direction :output
21 :if-exists :supersede
22 :if-does-not-exist :create
23 :element-type '(unsigned-byte 8))
24 (let* ((pos (length (write-sequence usb8 out)))
25 (file-len (file-length out)))
26 (unless (= file-len pos)
27 (error "Length written (~D) doesn't match file length (~D)~%" pos file-len))
28 usb8)))
30 ;; class to hold file data in memory
31 (defclass binary-file-data ()
32 ((buffered-data :accessor buffered-data-of)
33 (buffer-pos :accessor buffer-pos-of :initform 0))
34 ( :documentation "Binary file held in memory with accompanying seek position"))
36 ;; initalise buffer via reading a file
37 (defmethod initialize-instance :after ((self binary-file-data) &key filepath)
38 "Initalise a buffered via reading the lot into memory."
39 (when filepath (setf (buffered-data-of self)
40 (read-file-to-usb8-array filepath))))
42 ;; writing entire files
43 (defgeneric write-binary-file (binary-file-data file)
44 (:documentation "Write the buffered data to the binary file"))
46 (defmethod write-binary-file ((self binary-file-data) file)
47 "Write the buffered data to the binary file"
48 (write-usb8-array-to-file
49 (buffered-data-of self)
50 file))