|
| 1 | +; Copyright (c) Rich Hickey. All rights reserved. |
| 2 | +; The use and distribution terms for this software are covered by the |
| 3 | +; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php) |
| 4 | +; which can be found in the file epl-v10.html at the root of this distribution. |
| 5 | +; By using this software in any fashion, you are agreeing to be bound by |
| 6 | +; the terms of this license. |
| 7 | +; You must not remove this notice, or any other, from this software. |
| 8 | + |
| 9 | +(ns |
| 10 | + ^{:doc "Functions to turn objects into data. Alpha, subject to change"} |
| 11 | + clojure.datafy) |
| 12 | + |
| 13 | +(defn datafy |
| 14 | + "Attempts to return x as data. If :clojure.datafy/datafy is present |
| 15 | + as metadata of x, it will be called with x as an argument, else |
| 16 | + datafy will return the value of clojure.protocols/datafy. If the |
| 17 | + value has been transformed and the result supports |
| 18 | + metadata, :clojure.datafy/obj will be set on the metadata to the |
| 19 | + original value of x." |
| 20 | + [x] |
| 21 | + (let [v ((or (-> x meta ::datafy) -datafy) x)] |
| 22 | + (if (identical? v x) |
| 23 | + v |
| 24 | + (if (object? v) |
| 25 | + (vary-meta v assoc ::obj x) |
| 26 | + v)))) |
| 27 | + |
| 28 | +(defn nav |
| 29 | + "Returns (possibly transformed) v in the context of coll and k (a |
| 30 | + key/index or nil). Callers should attempt to provide the key/index |
| 31 | + context k for Indexed/Associative/ILookup colls if possible, but not |
| 32 | + to fabricate one e.g. for sequences (pass nil). If :clojure.datafy/nav is |
| 33 | + present as metadata on coll, it will be called with coll, k and v as |
| 34 | + arguments, else nav will call :clojure.protocols/nav." |
| 35 | + [coll k v] |
| 36 | + ((or (-> coll meta ::nav) -nav) coll k v)) |
| 37 | + |
| 38 | +(defn- datify-ref [r] |
| 39 | + (with-meta [(deref r)] (meta r))) |
| 40 | + |
| 41 | +(extend-protocol IDatafiable |
| 42 | + Var |
| 43 | + (-datafy [r] (datify-ref r)) |
| 44 | + |
| 45 | + Reduced |
| 46 | + (-datafy [r] (datify-ref r)) |
| 47 | + |
| 48 | + Atom |
| 49 | + (-datafy [r] (datify-ref r)) |
| 50 | + |
| 51 | + Volatile |
| 52 | + (-datafy [r] (datify-ref r)) |
| 53 | + |
| 54 | + Delay |
| 55 | + (-datafy [r] (datify-ref r))) |
0 commit comments