Created
April 14, 2021 19:12
-
-
Save helins/9da303f40281d08a60707f72682557e9 to your computer and use it in GitHub Desktop.
BB 0.3.5-SNAPSHOT - Memory mapping
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Test should fail because it requires `java.nio.DirectByteBufferR` | |
(require '[babashka.deps :as deps]) | |
(deps/add-deps '{:deps {io.helins/binf {:mvn/version "1.0.0-beta1"}}}) | |
(ns helins.binf.example.mmap-file | |
"Using BinF for writing and reading to a memory-mapped file on the JVM. | |
BinF protocols are implemented for ByteBuffer, parent of MappedByteBuffer." | |
;; We shall reuse our functions for writing and reading a date. | |
;; | |
(:require [helins.binf :as binf]) | |
(:import java.io.RandomAccessFile | |
java.nio.channels.FileChannel$MapMode)) | |
(defn rr-date | |
[view] | |
[(binf/rr-u16 view) | |
(binf/rr-u8 view) | |
(binf/rr-u8 view)]) | |
(defn wr-date | |
[view year month day] | |
(-> view | |
(binf/wr-b16 year) | |
(binf/wr-b8 month) | |
(binf/wr-b8 day))) | |
(= [2021 3 16] | |
(with-open [file (RandomAccessFile. "/tmp/binf-example.dat" | |
"rw")] | |
(let [view (-> file | |
.getChannel | |
(.map FileChannel$MapMode/READ_WRITE | |
;; From byte 0 in the file | |
0 | |
;; A size in bytes, we know a date is 4 bytes | |
4) | |
.load)] | |
(-> view | |
;; Writing date | |
(wr-date 2021 | |
3 | |
16) | |
;; Ensuring changes are persisted on disk | |
.force | |
;; Reading it back from the start of the file | |
(binf/seek 0) | |
rr-date)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Error: