Allow freeze, thaw opts to override bindings

This commit is contained in:
Peter Taoussanis 2020-07-24 15:49:20 +02:00
parent 57eae96c7b
commit b6c1c09419

View file

@ -994,14 +994,46 @@
(with-cache (-freeze-with-meta! x dos))
(.toByteArray baos)))
(defn- call-with-bindings
"Allow opts to override config bindings. Undocumented."
[opts f]
(let [opt->bindings
(fn [bindings id var]
(if-let [o (find opts id)]
(assoc bindings var (val o))
(do bindings)))
bindings
(-> nil
(opt->bindings :freeze-fallback #'*freeze-fallback*)
(opt->bindings :auto-freeze-compressor #'*auto-freeze-compressor*)
(opt->bindings :custom-readers #'*custom-readers*))]
(if-not bindings
(f) ; Common case
(try
(push-thread-bindings bindings)
(f)
(finally
(pop-thread-bindings))))))
(comment
(enc/qb 1e4
(call-with-bindings {} (fn [] *freeze-fallback*))
(call-with-bindings {:freeze-fallback "foo"} (fn [] *freeze-fallback*))))
(defn freeze
"Serializes arg (any Clojure data type) to a byte array. To freeze custom
types, extend the Clojure reader or see `extend-freeze`."
([x] (freeze x nil))
([x {:keys [compressor encryptor password]
([x {:as opts
:keys [compressor encryptor password]
:or {compressor :auto
encryptor aes128-gcm-encryptor}
:as opts}]
encryptor aes128-gcm-encryptor}}]
(call-with-bindings opts
(fn []
(let [;; Intentionally undocumented:
no-header? (or (get opts :no-header?)
(get opts :skip-header?))
@ -1052,7 +1084,7 @@
(when-let [e encryptor]
(or (encryption/standard-header-ids
(encryption/header-id e))
:else))}))))))))
:else))}))))))))))
;;;; Thawing
@ -1388,14 +1420,17 @@
([ba] (thaw ba nil))
([^bytes ba
{:keys [v1-compatibility? compressor encryptor password]
{:as opts
:keys [v1-compatibility? compressor encryptor password]
:or {compressor :auto
encryptor :auto}
:as opts}]
encryptor :auto}}]
(assert (not (get opts :headerless-meta))
":headerless-meta `thaw` opt removed in Nippy v2.7+")
(call-with-bindings opts
(fn []
(let [v2+? (not v1-compatibility?)
no-header? (get opts :no-header?) ; Intentionally undocumented
ex (fn ex
@ -1461,7 +1496,7 @@
;; Well-formed header definitely not present
(if v2+?
(ex err-msg-unknown-thaw-failure)
(thaw-v1-data ba (fn [_] (ex err-msg-unknown-thaw-failure)))))))))
(thaw-v1-data ba (fn [_] (ex err-msg-unknown-thaw-failure)))))))))))
(comment
(thaw (freeze "hello"))