Skip to content

Instantly share code, notes, and snippets.

@helins
Created April 14, 2021 19:12
Show Gist options
  • Save helins/9da303f40281d08a60707f72682557e9 to your computer and use it in GitHub Desktop.
Save helins/9da303f40281d08a60707f72682557e9 to your computer and use it in GitHub Desktop.
BB 0.3.5-SNAPSHOT - Memory mapping
;; 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))))
@helins
Copy link
Author

helins commented Apr 14, 2021

Error:

Type:     java.lang.IllegalArgumentException
Message:  No matching method load found taking 0 args for class java.nio.DirectByteBufferR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment