Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid needless allocation in read-bytevector! #950

Merged
merged 4 commits into from
Mar 18, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 16 additions & 21 deletions lib/scheme/extras.scm
Original file line number Diff line number Diff line change
Expand Up @@ -135,36 +135,31 @@
(if (zero? n)
#u8()
(let ((in (if (pair? o) (car o) (current-input-port)))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

let*

(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))))))))))
(vec (make-bytevector n))
(res (read-bytevector! vec in)))
(cond ((eof-object? res) res)
((< res n) (subbytes vec 0 i))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
((< res n) (subbytes vec 0 i))
((< res n) (subbytes vec 0 res))

(else res)))))
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
(else res)))))
(else vec)))))


(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
Loading