Книга: 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))))))

Оглавление книги


Генерация: 6.182. Запросов К БД/Cache: 3 / 0
поделиться
Вверх Вниз