Last active
August 28, 2022 01:54
-
-
Save lvh/d925da1ca9035565a2e8b2ad29dfaf8a to your computer and use it in GitHub Desktop.
An automatic cached protocol impl I wrote but didn't end up using.
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
;; (:import | |
;; (java.nio.file Path FileSystems StandardWatchEventKinds)) | |
(def ^:private all-events | |
(object-array | |
[StandardWatchEventKinds/ENTRY_CREATE | |
StandardWatchEventKinds/ENTRY_DELETE | |
StandardWatchEventKinds/ENTRY_MODIFY])) | |
(defn ^:private watch! | |
[^Path path callback] | |
(let [svc (-> (FileSystems/getDefault) .newWatchService)] | |
(.register path svc all-events) | |
(future | |
(loop [] | |
(let [key (.take svc)] | |
(callback) | |
(.reset key)))))) | |
(defmacro ^:private cached-protocol-impl | |
[proto backing-store cache] | |
`(reify ~proto | |
~@(for [{:keys [name arglists]} (-> proto resolve deref :sigs vals) | |
arglist arglists | |
:let [cache-key (into [(keyword name)] (rest arglist))]] | |
`(~name [~@arglist] | |
(or (-> ~cache deref (get-in ~cache-key)) | |
(let [actual# (~name ~backing-store ~@(rest arglist))] | |
(swap! ~cache assoc-in ~cache-key actual#) | |
actual#)))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment