Skip to content

Instantly share code, notes, and snippets.

@lvh
Last active August 28, 2022 01:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lvh/d925da1ca9035565a2e8b2ad29dfaf8a to your computer and use it in GitHub Desktop.
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.
;; (: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