Книга: Practical Common Lisp
Writing Binary Objects
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 function.
(defgeneric write-value (type stream value &key)
(:documentation "Write a value as the given type to the stream."))
Then you 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 slot->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-value ',type ,stream ,name ,@args)))
Now you can add a write-value
template to the define-binary-class
macro.
(defmacro define-binary-class (name slots)
(with-gensyms (typevar objectvar streamvar)
`(progn
(defclass ,name ()
,(mapcar #'slot->defclass-slot slots))
(defmethod read-value ((,typevar (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 slots) ,objectvar
,@(mapcar #'(lambda (x) (slot->write-value x streamvar)) slots))))))
- Binary Files
- Binary Format Basics
- Strings in Binary Files
- Composite Structures
- Designing the Macros
- Making the Dream a Reality
- Reading Binary Objects
- Writing Binary Objects
- Adding Inheritance and Tagged Structures
- Keeping Track of Inherited Slots
- Tagged Structures
- Primitive Binary Types
- The Current Object Stack
- 24. Practical: Parsing Binary Files
- Strings in Binary Files
- Binary Files
- Binary Format Basics
- Binary Serialization
- Creating and Deleting Device Objects
- 2. Binary – the way micros count
- CHAPTER 27 Writing PHP Scripts
- CHAPTER 33 Writing and Executing a Shell Script
- 5.1.2. Architecture Objects
- 13.5. Binary Utilities
- 13.6. Miscellaneous Binary Utilities