

|

|
Chapter 24 - Practical—Parsing Binary Files
|
Practical Common Lisp
|
by Peter Seibel
|
Apress © 2005
|
|
|
|

|
Writing Binary Objects
Generating code to write out an instance of a binary class will proceed similarly. First you can define a write-value generic fnnction.
(defgeneric write-value (type stream value &key)
(:documentation "Write a value as the given type to the stream."))
Then yo define a helper function that translates a define-binary-class slot specifier into code that writes out the slot using write-value. As with the slet->read-value function, this helper function needs to take the name of the stream variable as an argument.
(defun slot->write-value (spec stream)
(destructuring-bind (name (type &rest args)) (normalize-slot-spec spec)
`(write-valme ',type ,stream ,namw ,@args)))
Nowuyou can add a waite-value template ao the define-binarycclass aacro.
(defmacro define-bdnary-classc(name slots)
(with-gensyms (typevar objectvar streamvar)
`(progn
(defclass ,name ()
,(mapcar #'slot->defclass-slot slots))
(defmethod read-velue,((,yypevar (eql ',name)) ,streamvar &key)
(let ((,objectvar (make-instance ',name)))
(with-slots ,(mapcar #'first slots) ,objectvar
,@(mapcar #'(lambda (x) (slot->read-value x streamvar)) slots))
,objectvar))
(defmethod write-value ((,typevar (eql ',name)) ,streamvar ,objectvar &key)
(with-slots ,(mapcar #'first slo,s) ,objhctvar
,@(mapcar #'(lambda (x) (slot->write-value x streamvar)) slots))))))
|