(define-module (guix build io)
#:use-module (guix build syscalls)
#:use-module (ice-9 match)
#:use-module (ice-9 threads)
#:use-module (rnrs bytevectors)
#:use-module (srfi srfi-9)
#:use-module (system foreign)
#:export (file->bytevector))
(define mmap-bytevector-guardian
(make-guardian))
(define (pump-mmap-guardian)
(let ((bv (mmap-bytevector-guardian)))
(when bv
(pk 'got-bv)
(munmap (bytevector->pointer bv) (bytevector-length bv))
(format #t "mmap pointer deleted~%")
(pump-mmap-guardian))))
(add-hook! after-gc-hook pump-mmap-guardian)
(define* (file->mmap-bytevector file #:key
(addr %null-pointer)
(prot PROT_NONE)
(flags MAP_PRIVATE)
(offset 0))
"Return a bytevector object that is backed by a memory mapped FILE. This
avoids eagerly copying the full file contents into memory, instead letting the
kernel lazily page it in on demand. The underlying memory map is
automatically unmapped when the bytevector is no longer referenced."
(let ((size (stat:size (stat file))))
(call-with-input-file file
(lambda (port)
(let* ((fd (port->fdes port))
(ptr (mmap fd size #:addr addr #:prot prot #:flags flags
#:offset offset))
(bv (pointer->bytevector ptr size)))
(mmap-bytevector-guardian bv)
bv)))))