Skip to content

Commit

Permalink
Avoid needless allocation in read-bytevector!
Browse files Browse the repository at this point in the history
This change switches the implementation strategy to basing
read-bytevector on top of read-bytevector! rather than the other way
around.
  • Loading branch information
wasamasa committed Mar 18, 2024
1 parent b303bf3 commit d0e6dc7
Showing 1 changed file with 13 additions and 20 deletions.
33 changes: 13 additions & 20 deletions lib/scheme/extras.scm
Original file line number Diff line number Diff line change
Expand Up @@ -136,35 +136,28 @@
#u8()
(let ((in (if (pair? o) (car o) (current-input-port)))
(res (make-bytevector n)))
(let lp ((i 0))
(if (>= i n)
res
(let ((x (read-u8 in)))
(cond ((eof-object? x)
(if (zero? i) x (subbytes res 0 i)))
(else
(bytevector-u8-set! res i x)
(lp (+ i 1))))))))))
(read-bytevector! res in)
res)))

(define (read-bytevector! vec . o)
(let* ((in (if (pair? o) (car o) (current-input-port)))
(o (if (pair? o) (cdr o) o))
(start (if (pair? o) (car o) 0))
(end (if (and (pair? o) (pair? (cdr o)))
(cadr o)
(bytevector-length vec))))
(bytevector-length vec)))
(n (- end start)))
(if (>= start end)
0
(let ((res (read-bytevector (- end start) in)))
(cond
((eof-object? res)
res)
(else
(let ((len (bytevector-length res)))
(do ((i 0 (+ i 1)))
((>= i len) len)
(bytevector-u8-set! vec (+ i start) (bytevector-u8-ref res i))
))))))))
(let lp ((i 0))
(if (>= i n)
i
(let ((x (read-u8 in)))
(cond ((eof-object? x)
(if (zero? i) x i))
(else
(bytevector-u8-set! vec (+ i start) x)
(lp (+ i 1))))))))))

(define (write-bytevector vec . o)
(let* ((out (if (pair? o) (car o) (current-output-port)))
Expand Down

0 comments on commit d0e6dc7

Please sign in to comment.