;;; Given a byte vector VEC and an index variable INDEX, read a
;;; variable length integer and advance index.
-;;;
-;;; FIXME: This is called O(20) times. It should be reimplemented
-;;; with much of its logic in a single service function which can
-;;; be called by the macro expansion:
-;;; `(SETF ,INDEX (%READ-VAR-INTEGER ,VEC ,INDEX)).
+(defun %read-var-integer (vec index)
+ (let ((val (aref vec index)))
+ (cond ((<= val 253)
+ (values val (1+ index)))
+ ((= val 254)
+ (values
+ (logior (aref vec (+ index 1))
+ (ash (aref vec (+ index 2)) 8))
+ (+ index 3)))
+ (t
+ (values
+ (logior (aref vec (+ index 1))
+ (ash (aref vec (+ index 2)) 8)
+ (ash (aref vec (+ index 3)) 16)
+ (ash (aref vec (+ index 4)) 24))
+ (+ index 5))))))
+
(defmacro read-var-integer (vec index)
- (once-only ((val `(aref ,vec ,index)))
- `(cond ((<= ,val 253)
- (incf ,index)
- ,val)
- ((= ,val 254)
- (prog1
- (logior (aref ,vec (+ ,index 1))
- (ash (aref ,vec (+ ,index 2)) 8))
- (incf ,index 3)))
- (t
- (prog1
- (logior (aref ,vec (+ ,index 1))
- (ash (aref ,vec (+ ,index 2)) 8)
- (ash (aref ,vec (+ ,index 3)) 16)
- (ash (aref ,vec (+ ,index 4)) 24))
- (incf ,index 5))))))
+ (once-only ((vec vec))
+ `(multiple-value-bind (value new-index)
+ (%read-var-integer ,vec ,index)
+ (setf ,index new-index)
+ value)))
;;; Take an adjustable vector VEC with a fill pointer and push the
;;; variable length representation of INT on the end.
(once-only ((len `(read-var-integer ,vec ,index)))
(once-only ((res `(make-string ,len)))
`(progn
- (%byte-blt ,vec ,index ,res 0 ,len)
- (incf ,index ,len)
+ (loop for i from 0 below ,len
+ do (setf (aref ,res i)
+ (code-char (read-var-integer ,vec ,index))))
,res))))
;;; Write STRING into VEC (adjustable, with fill-pointer) represented
(let ((len (length string)))
(write-var-integer len vec)
(dotimes (i len)
- (vector-push-extend (char-code (schar string i)) vec)))
+ (write-var-integer (char-code (schar string i)) vec)))
(values))
\f
;;;; packed bit vectors