Skip to content

Commit

Permalink
Load the pathname directly to the output buffer for reducing the memo…
Browse files Browse the repository at this point in the history
…ry usage.
  • Loading branch information
fukamachi committed Aug 12, 2024
1 parent 64d81cd commit a1b4680
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 5 deletions.
2 changes: 2 additions & 0 deletions src/ev.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
:close-socket
:write-socket-data
:write-socket-byte
:write-socket-stream
:flush-buffer
:with-async-writing)
(:import-from :woo.ev.event-loop
Expand All @@ -35,6 +36,7 @@
:close-tcp-server
:write-socket-data
:write-socket-byte
:write-socket-stream
:with-async-writing
:socket-data
:close-socket
Expand Down
30 changes: 30 additions & 0 deletions src/ev/socket.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@

:write-socket-data
:write-socket-byte
:write-socket-stream
:flush-buffer
:with-async-writing
:send-static-file
Expand Down Expand Up @@ -166,6 +167,35 @@
(setf (socket-write-cb socket) write-cb))
(fast-write-byte byte (socket-buffer socket))))

(defun write-socket-stream (socket stream &key (write-cb nil write-cb-specified-p))
(declare (optimize speed)
(type file-stream stream))
(when (socket-open-p socket)
(when write-cb-specified-p
(setf (socket-write-cb socket) write-cb))
(let ((file-size (file-length stream))
(buffer (socket-buffer socket)))
;; Fill the last vector of fast-io's buffer
(let* ((start (fast-io::output-buffer-fill buffer))
(end
(read-sequence (fast-io::output-buffer-vector buffer)
stream
:start start)))
(setf (fast-io::output-buffer-fill buffer) end)
(incf (fast-io::output-buffer-len buffer)
(- end start)))
(unless (= (file-position stream) file-size)
;; Load the rest of file contents directly into the fast-io's buffer
(loop
(fast-io::extend buffer)
(let ((n
(read-sequence (fast-io::output-buffer-vector buffer)
stream)))
(setf (fast-io::output-buffer-fill buffer) n)
(incf (fast-io::output-buffer-len buffer) n))
(when (= (file-position stream) file-size)
(return)))))))

(declaim (inline reset-buffer))
(defun reset-buffer (socket)
(let ((buffer (socket-buffer socket)))
Expand Down
6 changes: 1 addition & 5 deletions src/woo.lisp
Original file line number Diff line number Diff line change
Expand Up @@ -388,11 +388,7 @@
(wev:close-socket socket))))
(write-response-headers socket status headers (not close))
;; Future task: Use OpenSSL's SSL_sendfile which uses Kernel TLS.
;; TODO: Stop allocating an input buffer every time
(loop with buffer = (make-array 4096 :element-type '(unsigned-byte 8))
for n = (read-sequence buffer in)
do (wev:write-socket-data socket buffer :end n)
while (= n 4096))))))
(wev:write-socket-stream socket in)))))
(t
(let* ((fd (wsys:open body))
(size #+lispworks (sys:file-size body)
Expand Down

0 comments on commit a1b4680

Please sign in to comment.