Skip to content

Commit

Permalink
Add lightweight keyset wrapper
Browse files Browse the repository at this point in the history
Saves on allocation and provides an immutable facade to underlying
regular set
  • Loading branch information
bsless committed Aug 24, 2021
1 parent e5b0b14 commit bed82e1
Showing 1 changed file with 42 additions and 7 deletions.
49 changes: 42 additions & 7 deletions src/malli/core.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -278,14 +278,49 @@
(-arange [^objects arr to]
#?(:clj (let [-arr (object-array to)] (System/arraycopy arr 0 -arr 0 to) -arr)
:cljs (.slice arr 0 to)))
#?(:clj
(-set-wrapper
[^java.util.Set s]
(reify
Collection
(size [_] (.size s))
(containsAll [_ c] (.containsAll s c))
clojure.lang.IPersistentSet
(disjoin [_ key] (disj (set s) key))
(contains [_ key] (.contains s key))
(get [_ key] (when (.contains s key) key))
clojure.lang.Counted
(count [_] (.size s))
clojure.lang.IPersistentCollection
(cons [_ o] (.cons (set s) o))
(empty [_] #{})
(equiv [_ o]
(if (instance? java.util.Set o)
(if (== (.size s) (.size ^Collection o))
(.containsAll s o)
false)
false))
clojure.lang.Seqable
(seq [_] (seq s))
clojure.lang.IFn
(invoke [_ o] (when (.contains s o) o))
Iterable
(iterator [_] (.iterator s)))))
(-keyset []
(let [data (volatile! #{})]
(fn
([] @data)
([k] (let [old @data]
(vswap! data conj k)
(when (= old @data)
(-fail! ::non-distinct-entry-keys {:keys old, :key k})))))))]
#?(:clj
(let [data (java.util.HashSet.)]
(fn
([] (-set-wrapper data))
([k] (when-not (.add data k)
(-fail! ::non-distinct-entry-keys {:keys (seq data), :key k})))))
:cljs
(let [data (volatile! #{})]
(fn
([] @data)
([k] (let [old @data]
(vswap! data conj k)
(when (= old @data)
(-fail! ::non-distinct-entry-keys {:keys old, :key k}))))))))]
(let [n (count children)
-children (object-array n)
-entries (object-array n)
Expand Down

0 comments on commit bed82e1

Please sign in to comment.