├── .gitignore ├── CHANGELOG.md ├── LICENSE.md ├── README.md ├── boot.properties ├── build.boot ├── circle.yml ├── deps.edn ├── src ├── data_readers.clj └── linked │ ├── core.cljc │ ├── map.cljc │ └── set.cljc └── test └── linked ├── map_test.cljc └── set_test.cljc /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /classes 3 | /checkouts 4 | pom.xml 5 | pom.xml.asc 6 | *.jar 7 | *.class 8 | /.lein-* 9 | !/.lein-classpath 10 | /.nrepl-* 11 | *.DS_Store 12 | project.clj 13 | *.iml -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## 1.2.7 2 | - Correct CLJS implementation of IKVReduce 3 | Contributed by @KeeganMyers 4 | 5 | ## 1.2.6 6 | - Correct implementation of IHashEq 7 | 8 | ## 1.2.5 9 | - Move to boot and .cljc files 10 | 11 | ## 1.2.3 12 | - Equivalence checks for instance of Map first 13 | 14 | ## 1.2.2 15 | - Move map and set functions to linked.core 16 | 17 | ## 1.1.0 18 | - Remove cljx dependency 19 | 20 | ## 1.0.6 21 | - Add changelog 22 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Eclipse Public License -v 1.0 2 | ============================= 3 | 4 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE (“AGREEMENT”). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 5 | 6 | ### 1. Definitions 7 | 8 | “Contribution” means: 9 | * **a)** in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and 10 | * **b)** in the case of each subsequent Contributor: 11 | * **i)** changes to the Program, and 12 | * **ii)** additions to the Program; 13 | where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: **(i)** are separate modules of software distributed in conjunction with the Program under their own license agreement, and **(ii)** are not derivative works of the Program. 14 | 15 | “Contributor” means any person or entity that distributes the Program. 16 | 17 | “Licensed Patents ” mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. 18 | 19 | “Program” means the Contributions distributed in accordance with this Agreement. 20 | 21 | “Recipient” means anyone who receives the Program under this Agreement, including all Contributors. 22 | 23 | ### 2. Grant of Rights 24 | 25 | **a)** Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. 26 | 27 | **b)** Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. 28 | 29 | **c)** Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. 30 | 31 | **d)** Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 32 | 33 | ### 3. Requirements 34 | 35 | A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: 36 | * **a)** it complies with the terms and conditions of this Agreement; and 37 | * **b)** its license agreement: 38 | * **i)** effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; 39 | * **ii)** effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; 40 | * **iii)** states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and 41 | * **iv)** states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 42 | 43 | When the Program is made available in source code form: 44 | * **a)** it must be made available under this Agreement; and 45 | * **b)** a copy of this Agreement must be included with each copy of the Program. 46 | 47 | Contributors may not remove or alter any copyright notices contained within the Program. 48 | 49 | Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 50 | 51 | ### 4. Commercial Distribution 52 | 53 | Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor (“Commercial Contributor”) hereby agrees to defend and indemnify every other Contributor (“Indemnified Contributor”) against any losses, damages and costs (collectively “Losses”) arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: **a)** promptly notify the Commercial Contributor in writing of such claim, and **b)** allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. 54 | 55 | For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 56 | 57 | ### 5. No Warranty 58 | 59 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 60 | 61 | ### 6. Disclaimer of Liability 62 | 63 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 64 | 65 | ### 7. General 66 | 67 | If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 68 | 69 | If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. 70 | 71 | All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. 72 | 73 | Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. 74 | 75 | This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Linked 2 | 3 | [![Build status](https://circleci.com/gh/frankiesardo/linked.svg?style=shield)](https://circleci.com/gh/frankiesardo/linked) 4 | 5 | Map and Set structures that rememeber the insertion order of its elements, even after multiple assoc and dissoc. For Clojure and ClojureScript. 6 | 7 | ## Download 8 | 9 | [![Clojars Project](http://clojars.org/frankiesardo/linked/latest-version.svg)](http://clojars.org/frankiesardo/linked) 10 | 11 | ## Map 12 | 13 | ```clj 14 | (require '[linked.core :as linked]) 15 | 16 | (linked/map :b 2 :a 1 :d 4) 17 | ;=> #linked/map [[:b 2] [:a 1] [:d 4]] 18 | 19 | (assoc (linked/map :b 2 :a 1 :d 4) :c 3) 20 | ;=> #linked/map [[:b 2] [:a 1] [:d 4] [:c 3]] 21 | 22 | (into (linked/map) [[:c 3] [:a 1] [:d 4]]) 23 | ;=> #linked/map [[:c 3] [:a 1] [:d 4]] 24 | 25 | (dissoc (linked/map :c 3 :a 1 :d 4) :a) 26 | ;=> #linked/map [[:c 3] [:d 4]] 27 | ``` 28 | 29 | ## Set 30 | 31 | ```clj 32 | (require '[linked.core :as linked]) 33 | 34 | (linked/set 4 3 1 8 2) 35 | ;=> #linked/set [4 3 1 8 2] 36 | 37 | (conj (linked/set 9 10) 1 2 3) 38 | ;=> #linked/set [9 10 1 2 3] 39 | 40 | (into (linked/set) [7 6 1 5 6]) 41 | ;=> #linked/set [7 6 1 5] 42 | 43 | (disj (linked/set 8 1 7 2 6) 7) 44 | ;=> #linked/set [8 1 2 6] 45 | ``` 46 | 47 | ## Performance 48 | 49 | These data structures wrap a normal `hash-map` but instead of feeding it a normal `[key value]` pair their remeber a `[key value left-key right-key]` record. When an item is removed from the data structure it is sufficient to update the left and right node to reference each others keys while removing the chosen node. This implementation yields the same Big O time and space complexity of a standard `hash-map` (altought effective performance will be slower by a constant factor). 50 | 51 | ## Comparison with [ordered](https://github.com/amalloy/ordered) 52 | 53 | - Ordered will keep on allocating memory space until you explicitly call [compact](https://github.com/amalloy/ordered/blob/develop/src/flatland/ordered/common.clj#L7) to clean up the garbage. Linked doesn't keep a pointer to old elements 54 | - Ordered has transient support for faster allocation of a large number of items 55 | - Linked works with ClojureScript 56 | 57 | ## License 58 | 59 | Copyright © 2014 Frankie Sardo 60 | 61 | Distributed under the Eclipse Public License either version 1.0 or (at 62 | your option) any later version. 63 | -------------------------------------------------------------------------------- /boot.properties: -------------------------------------------------------------------------------- 1 | #https://github.com/boot-clj/boot 2 | #Thu Sep 10 15:11:07 BST 2015 3 | BOOT_CLOJURE_VERSION=1.8.0 4 | BOOT_VERSION=2.7.2 5 | -------------------------------------------------------------------------------- /build.boot: -------------------------------------------------------------------------------- 1 | (set-env! 2 | :resource-paths #{"src"} 3 | :source-paths #{"test"} 4 | :dependencies '[[adzerk/boot-cljs "2.1.4" :scope "test"] 5 | [adzerk/boot-cljs-repl "0.3.3" :scope "test"] 6 | [crisptrutski/boot-cljs-test "0.3.5-SNAPSHOT" :scope "test"] 7 | [org.clojure/clojurescript "1.10.238" :scope "test"] 8 | [doo "0.1.8" :scope "test"] 9 | [collection-check "0.1.7" :scope "test" 10 | :exclusions [org.clojure/clojure]]]) 11 | 12 | (require 13 | '[adzerk.boot-cljs :refer [cljs]] 14 | '[adzerk.boot-cljs-repl :refer [cljs-repl start-repl]] 15 | '[crisptrutski.boot-cljs-test :refer [test-cljs]]) 16 | 17 | (require '[clojure.java.shell :as shell] 18 | '[clojure.string :as str]) 19 | 20 | (defn- current-tag [] 21 | (let [{:keys [exit out]} (shell/sh "git" "describe" "--tags")] 22 | (when (zero? exit) 23 | (str/trim out)))) 24 | 25 | (def +version+ 26 | (if-let [tag (current-tag)] 27 | (cond-> (second (re-find #"v(.*)" tag)) 28 | (.contains tag "-") (str "-SNAPSHOT")) 29 | "0.1.0-SNAPSHOT")) 30 | 31 | (task-options! 32 | pom {:project 'frankiesardo/linked 33 | :version +version+ 34 | :description "Efficient ordered map and set." 35 | :url "https://github.com/frankiesardo/linked" 36 | :scm {:url "https://github.com/frankiesardo/linked"} 37 | :license {"Eclipse Public License" 38 | "http://www.eclipse.org/legal/epl-v10.html"}}) 39 | 40 | (deftask deploy [] 41 | (comp (pom) (jar) (install) 42 | (push :gpg-sign (not (.endsWith +version+ "-SNAPSHOT"))))) 43 | 44 | (ns-unmap 'boot.user 'test) 45 | 46 | (require '[boot.pod :as pod] 47 | '[boot.core :as core]) 48 | 49 | (def pod-deps 50 | '[[pjstadig/humane-test-output "0.6.0" :exclusions [org.clojure/clojure]]]) 51 | 52 | (defn init [fresh-pod] 53 | (doto fresh-pod 54 | (pod/with-eval-in 55 | (require '[clojure.test :as t] 56 | '[clojure.java.io :as io] 57 | '[pjstadig.humane-test-output :refer [activate!]]) 58 | (activate!) 59 | (defn test-ns* [ns] 60 | (binding [t/*report-counters* (ref t/*initial-report-counters*)] 61 | (let [ns-obj (the-ns ns)] 62 | (t/do-report {:type :begin-test-ns :ns ns-obj}) 63 | (t/test-vars (vals (ns-publics ns))) 64 | (t/do-report {:type :end-test-ns :ns ns-obj})) 65 | @t/*report-counters*))))) 66 | 67 | (deftask test-clj [] 68 | (let [worker-pods (pod/pod-pool (update-in (core/get-env) [:dependencies] into pod-deps) :init init)] 69 | (core/cleanup (worker-pods :shutdown)) 70 | (core/with-pre-wrap fileset 71 | (let [worker-pod (worker-pods :refresh) 72 | namespaces (core/fileset-namespaces fileset)] 73 | (if (seq namespaces) 74 | (let [summary (pod/with-eval-in worker-pod 75 | (doseq [ns '~namespaces] (require ns)) 76 | (let [ns-results (map test-ns* '~namespaces)] 77 | (-> (reduce (partial merge-with +) ns-results) 78 | (assoc :type :summary) 79 | (doto t/do-report))))] 80 | (when (> (apply + (map summary [:fail :error])) 0) 81 | (throw (ex-info "Some tests failed or errored" summary)))) 82 | (println "No namespaces were tested.")) 83 | fileset)))) 84 | 85 | (deftask test [] 86 | (comp (test-clj) 87 | (test-cljs :js-env :phantom 88 | :exit? true))) 89 | 90 | (deftask autotest [] 91 | (comp (watch) 92 | (test-clj) 93 | (test-cljs :js-env :phantom))) 94 | -------------------------------------------------------------------------------- /circle.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | jobs: 3 | test: 4 | working_directory: ~/work 5 | docker: 6 | - image: circleci/clojure:boot-2.7.2-browsers 7 | steps: 8 | - checkout 9 | - restore_cache: 10 | keys: 11 | - v1-{{ checksum "boot.properties" }}-{{ checksum "build.boot" }} 12 | - v1- 13 | - run: boot test 14 | - save_cache: 15 | paths: 16 | - ~/.m2 17 | - ~/.boot/cache/lib 18 | - ~/.boot/cache/bin 19 | key: v1-{{ checksum "boot.properties" }}-{{ checksum "build.boot" }} 20 | deploy: 21 | working_directory: ~/work 22 | docker: 23 | - image: circleci/clojure:boot-2.7.2 24 | steps: 25 | - checkout 26 | - add_ssh_keys 27 | - restore_cache: 28 | key: v1-{{ checksum "boot.properties" }}-{{ checksum "build.boot" }} 29 | - run: git clone $DOTFILES ~/dotfiles && . ~/dotfiles/init.sh 30 | - deploy: 31 | command: boot deploy 32 | workflows: 33 | version: 2 34 | test-and-deploy: 35 | jobs: 36 | - test: 37 | filters: 38 | tags: 39 | only: /v.*/ 40 | - deploy: 41 | requires: 42 | - test 43 | filters: 44 | branches: 45 | only: 46 | - master 47 | tags: 48 | only: /v.*/ 49 | -------------------------------------------------------------------------------- /deps.edn: -------------------------------------------------------------------------------- 1 | {:paths ["src"] :deps {}} 2 | -------------------------------------------------------------------------------- /src/data_readers.clj: -------------------------------------------------------------------------------- 1 | {linked/map linked.map/->linked-map 2 | linked/set linked.set/->linked-set} 3 | -------------------------------------------------------------------------------- /src/linked/core.cljc: -------------------------------------------------------------------------------- 1 | (ns linked.core 2 | (:refer-clojure :exclude [map set]) 3 | (:require [linked.map :as m] 4 | [linked.set :as s])) 5 | 6 | (defn map 7 | ([] m/empty-linked-map) 8 | ([& keyvals] (apply assoc m/empty-linked-map keyvals))) 9 | 10 | (defn set 11 | ([] s/empty-linked-set) 12 | ([& keys] (apply conj s/empty-linked-set keys))) 13 | -------------------------------------------------------------------------------- /src/linked/map.cljc: -------------------------------------------------------------------------------- 1 | (ns linked.map 2 | (:require [clojure.string :as string] 3 | #?(:cljs [cljs.reader :as reader])) 4 | #?(:clj 5 | (:import (clojure.lang Associative 6 | Counted 7 | IObj 8 | IFn 9 | IHashEq 10 | ILookup 11 | IPersistentCollection 12 | IPersistentVector 13 | IPersistentMap 14 | MapEntry 15 | MapEquivalence 16 | Reversible 17 | Seqable 18 | SeqIterator) 19 | (java.util Map 20 | Map$Entry 21 | LinkedHashSet) 22 | (java.lang Iterable)))) 23 | 24 | (declare empty-linked-map) 25 | 26 | (defrecord Node [value left right]) 27 | 28 | (declare assoc*) 29 | (declare dissoc*) 30 | (declare seq*) 31 | (declare rseq*) 32 | 33 | (deftype LinkedMap [head delegate-map] 34 | #?@(:clj 35 | [IPersistentMap 36 | (assoc [this k v] 37 | (assoc* this k v)) 38 | (assocEx [this k v] 39 | (if (.containsKey this k) 40 | (throw (RuntimeException. "Key already present")) 41 | (assoc this k v))) 42 | (without [this k] 43 | (dissoc* this k)) 44 | 45 | MapEquivalence 46 | 47 | Map 48 | (get [this k] 49 | (.valAt this k)) 50 | (isEmpty [this] 51 | (not (.seq this))) 52 | (entrySet [this] 53 | (LinkedHashSet. (or (.seq this) []))) 54 | (containsValue [this v] 55 | (boolean (seq (filter #(= % v) (.values this))))) 56 | (values [this] 57 | (map val (.seq this))) 58 | (size [_] 59 | (count delegate-map)) 60 | 61 | Counted 62 | 63 | IPersistentCollection 64 | (count [this] 65 | (.size this)) 66 | (cons [this o] 67 | (condp instance? o 68 | Map$Entry (let [^Map$Entry e o] 69 | (.assoc this (.getKey e) (.getValue e))) 70 | IPersistentVector (if (= 2 (count o)) 71 | (.assoc this (nth o 0) (nth o 1)) 72 | (throw (IllegalArgumentException. "Vector arg to map conj must be a pair"))) 73 | ;; TODO support for transient to speed up multiple assoc? 74 | (reduce (fn [^IPersistentMap m ^Map$Entry e] 75 | (.assoc m (.getKey e) (.getValue e))) 76 | this 77 | o))) 78 | (empty [_] 79 | (with-meta empty-linked-map (meta delegate-map))) 80 | (equiv [this o] 81 | (and (instance? Map o) 82 | (= (.count this) (count o)) 83 | (every? (fn [[k v :as kv]] 84 | (= kv (find o k))) 85 | (.seq this)))) 86 | 87 | Seqable 88 | (seq [this] 89 | (seq* this)) 90 | 91 | Reversible 92 | (rseq [this] 93 | (rseq* this)) 94 | 95 | Iterable 96 | (iterator [this] 97 | (SeqIterator. (.seq this))) 98 | 99 | Associative 100 | (containsKey [_ k] 101 | (contains? delegate-map k)) 102 | (entryAt [this k] 103 | (when (.containsKey this k) 104 | (MapEntry. k (.valAt this k)))) 105 | 106 | ILookup 107 | (valAt [this k] 108 | (.valAt this k nil)) 109 | (valAt [_ k not-found] 110 | (if-let [entry (find delegate-map k)] 111 | (-> entry val :value) 112 | not-found)) 113 | 114 | IFn 115 | (invoke [this k] 116 | (.valAt this k)) 117 | (invoke [this k not-found] 118 | (.valAt this k not-found)) 119 | 120 | IObj 121 | (meta [this] 122 | (.meta ^IObj delegate-map)) 123 | (withMeta [this m] 124 | (LinkedMap. head (.withMeta ^IObj delegate-map m))) 125 | 126 | ;; IEditableCollection 127 | 128 | IHashEq 129 | (hasheq [this] (.hasheq ^IHashEq (into {} this))) 130 | 131 | Object 132 | (toString [this] 133 | (str "{" (string/join ", " (for [[k v] this] (str k " " v))) "}")) 134 | (equals [this other] 135 | (.equiv this other)) 136 | (hashCode [this] 137 | (.hashCode ^Object (into {} this)))] 138 | :cljs 139 | [Object 140 | (toString [coll] 141 | (str "{" (string/join ", " (for [[k v] coll] (str k " " v))) "}")) 142 | (equiv [this other] 143 | (-equiv this other)) 144 | 145 | ICloneable 146 | (-clone [_] 147 | (LinkedMap. head delegate-map)) 148 | 149 | IWithMeta 150 | (-with-meta [coll meta] 151 | (LinkedMap. head (with-meta delegate-map meta))) 152 | 153 | IMeta 154 | (-meta [coll] (meta delegate-map)) 155 | 156 | ICollection 157 | (-conj [coll entry] 158 | (if (vector? entry) 159 | (-assoc coll (-nth entry 0) (-nth entry 1)) 160 | (loop [ret coll es (seq entry)] 161 | (if (nil? es) 162 | ret 163 | (let [e (first es)] 164 | (if (vector? e) 165 | (recur (-assoc ret (-nth e 0) (-nth e 1)) 166 | (next es)) 167 | (throw (js/Error. "conj on a map takes map entries or seqables of map entries")))))))) 168 | 169 | IEmptyableCollection 170 | (-empty [coll] (-with-meta empty-linked-map (meta delegate-map))) 171 | 172 | IEquiv 173 | (-equiv [coll other] (equiv-map coll other)) 174 | 175 | IHash 176 | (-hash [coll] (hash (into {} coll))) 177 | 178 | ISequential 179 | 180 | ISeqable 181 | (-seq [coll] (seq* coll)) 182 | 183 | IReversible 184 | (-rseq [coll] (rseq* coll)) 185 | 186 | ICounted 187 | (-count [coll] 188 | (count delegate-map)) 189 | 190 | ILookup 191 | (-lookup [coll k] 192 | (-lookup coll k nil)) 193 | 194 | (-lookup [coll k not-found] 195 | (if-let [entry (find delegate-map k)] 196 | (-> entry val :value) 197 | not-found)) 198 | 199 | IAssociative 200 | (-assoc [coll k v] 201 | (assoc* coll k v)) 202 | 203 | (-contains-key? [coll k] 204 | (contains? delegate-map k)) 205 | 206 | IMap 207 | (-dissoc [coll k] 208 | (dissoc* coll k)) 209 | 210 | IKVReduce 211 | (-kv-reduce [coll f init] 212 | (reduce #(apply (partial f %1) %2) init (seq coll))) 213 | 214 | IFn 215 | (-invoke [coll k] 216 | (-lookup coll k)) 217 | 218 | (-invoke [coll k not-found] 219 | (-lookup coll k not-found)) 220 | 221 | ;; IEditableCollection 222 | 223 | IPrintWithWriter 224 | (-pr-writer [coll writer opts] (-write writer (str "#linked/map " (into [] coll))))])) 225 | 226 | #?(:clj 227 | (defmethod print-method LinkedMap [o ^java.io.Writer w] 228 | (.write w "#linked/map ") 229 | (.write w (pr-str (into [] o))))) 230 | 231 | (defn- assoc* [^LinkedMap this k v] 232 | (let [head (.-head this) 233 | delegate-map (.-delegate-map this)] 234 | (if-let [entry (find delegate-map k)] 235 | (LinkedMap. head (assoc-in delegate-map [k :value] v)) 236 | (if (empty? delegate-map) 237 | (LinkedMap. k (assoc delegate-map k (Node. v k k))) 238 | (let [tail (get-in delegate-map [head :left])] 239 | (LinkedMap. head (-> delegate-map 240 | (assoc k (Node. v tail head)) 241 | (assoc-in [head :left] k) 242 | (assoc-in [tail :right] k)))))))) 243 | 244 | (defn- dissoc* [^LinkedMap this k] 245 | (let [head (.-head this) 246 | delegate-map (.-delegate-map this)] 247 | (if-let [entry (find delegate-map k)] 248 | (if (= 1 (count delegate-map)) 249 | (empty this) 250 | (let [rk (-> entry val :right) 251 | lk (-> entry val :left) 252 | head (if (= k head) rk head)] 253 | (LinkedMap. head (-> delegate-map 254 | (dissoc k) 255 | (assoc-in [rk :left] lk) 256 | (assoc-in [lk :right] rk))))) 257 | this))) 258 | 259 | 260 | ;;;; seq and rseq impl 261 | 262 | (defn- map-entry [k v] 263 | #?(:clj (MapEntry. k v) 264 | :cljs (MapEntry. k v nil))) 265 | 266 | (defn- visit-node [delegate-map current last direction] 267 | (let [[k node] (find delegate-map current) 268 | entry (map-entry k (:value node)) 269 | next (direction node)] 270 | (if (= current last) 271 | (list entry) 272 | (cons entry (lazy-seq (visit-node delegate-map next last direction)))))) 273 | 274 | (defn- seq* [^LinkedMap this] 275 | (let [delegate-map (.-delegate-map this) 276 | head (.-head this) 277 | tail (get-in delegate-map [head :left])] 278 | (when (seq delegate-map) 279 | (visit-node delegate-map head tail :right)))) 280 | 281 | (defn- rseq* [^LinkedMap this] 282 | (let [delegate-map (.-delegate-map this) 283 | head (.-head this) 284 | tail (get-in delegate-map [head :left])] 285 | (when (seq delegate-map) 286 | (visit-node delegate-map tail head :left)))) 287 | 288 | (def ^{:tag LinkedMap} empty-linked-map 289 | (LinkedMap. nil (hash-map))) 290 | 291 | (def ->linked-map (partial into empty-linked-map)) 292 | 293 | #?(:cljs (reader/register-tag-parser! 'linked/map ->linked-map)) 294 | -------------------------------------------------------------------------------- /src/linked/set.cljc: -------------------------------------------------------------------------------- 1 | (ns linked.set 2 | (:require [linked.map :refer [empty-linked-map]] 3 | [clojure.string :as string] 4 | #?(:cljs [cljs.reader :as reader])) 5 | #?(:clj 6 | (:import (clojure.lang Counted 7 | IObj 8 | IFn 9 | IHashEq 10 | ILookup 11 | IPersistentCollection 12 | IPersistentSet 13 | IPersistentVector 14 | Reversible 15 | Seqable 16 | Sequential 17 | SeqIterator) 18 | (java.util Set) 19 | (java.lang Iterable)))) 20 | 21 | (declare empty-linked-set) 22 | 23 | (deftype LinkedSet [linked-map] 24 | #?@(:clj 25 | [IPersistentSet 26 | (disjoin [_ k] 27 | (LinkedSet. (dissoc linked-map k))) 28 | (contains [_ k] 29 | (contains? linked-map k)) 30 | (get [this k] 31 | (when (.contains this k) k)) 32 | 33 | Set 34 | (size [this] 35 | (.count this)) 36 | 37 | Iterable 38 | (iterator [this] 39 | (SeqIterator. (.seq this))) 40 | 41 | Comparable 42 | (compareTo [_ o] 43 | (compare (vec _) (vec o))) 44 | 45 | Counted 46 | 47 | IPersistentCollection 48 | (count [_] 49 | (count linked-map)) 50 | (cons [this o] 51 | (if (contains? linked-map o) 52 | this 53 | (LinkedSet. (assoc linked-map o nil)))) 54 | (empty [_] 55 | empty-linked-set) 56 | (equiv [this other] 57 | (or (identical? this other) 58 | (and (instance? Set other) 59 | (let [^Set s other] 60 | (and (= (.size this) (.size s)) 61 | (every? #(.contains s %) (.seq this))))))) 62 | Sequential 63 | Seqable 64 | (seq [_] 65 | (when-let [s (seq linked-map)] (map key s))) 66 | 67 | Reversible 68 | (rseq [_] 69 | (when-let [s (rseq linked-map)] (map key s))) 70 | 71 | IFn 72 | (invoke [this k] 73 | (get this k)) 74 | 75 | IObj 76 | (meta [this] 77 | (.meta ^IObj linked-map)) 78 | (withMeta [this m] 79 | (LinkedSet. (.withMeta ^IObj linked-map m))) 80 | 81 | IHashEq 82 | (hasheq [this] (.hasheq ^IHashEq (into #{} this))) 83 | 84 | Object 85 | (toString [this] 86 | (str "[" (string/join " " (map str this)) "]")) 87 | (hashCode [this] 88 | (.hashCode ^Object (into #{} this))) 89 | (equals [this other] 90 | (.equiv this other))] 91 | :cljs 92 | [Object 93 | (toString [this] 94 | (str "[" (string/join " " (map str this)) "]")) 95 | (equiv [this other] 96 | (-equiv this other)) 97 | 98 | ICloneable 99 | (-clone [_] (LinkedSet. linked-map)) 100 | 101 | IWithMeta 102 | (-with-meta [coll meta] (LinkedSet. (with-meta linked-map meta))) 103 | 104 | IMeta 105 | (-meta [coll] (meta linked-map)) 106 | 107 | ICollection 108 | (-conj [coll o] 109 | (LinkedSet. (assoc linked-map o nil))) 110 | 111 | IEmptyableCollection 112 | (-empty [coll] (with-meta empty-linked-set meta)) 113 | 114 | IEquiv 115 | (-equiv [coll other] 116 | (and 117 | (set? other) 118 | (== (count coll) (count other)) 119 | (every? #(contains? coll %) 120 | other))) 121 | 122 | IHash 123 | (-hash [coll] (hash (into #{} coll))) 124 | 125 | ISequential 126 | ISeqable 127 | (-seq [coll] (when-let [s (seq linked-map)] (map key s))) 128 | 129 | IReversible 130 | (-rseq [coll] (when-let [s (rseq linked-map)] (map key s))) 131 | 132 | ICounted 133 | (-count [coll] (-count linked-map)) 134 | 135 | IComparable 136 | (-compare [_ o] 137 | (compare (vec _) (vec o))) 138 | 139 | ILookup 140 | (-lookup [coll v] 141 | (-lookup coll v nil)) 142 | (-lookup [coll v not-found] 143 | (if (-contains-key? linked-map v) 144 | v 145 | not-found)) 146 | 147 | ISet 148 | (-disjoin [coll v] 149 | (LinkedSet. (-dissoc linked-map v))) 150 | 151 | IFn 152 | (-invoke [coll k] 153 | (-lookup coll k)) 154 | (-invoke [coll k not-found] 155 | (-lookup coll k not-found)) 156 | 157 | ;; IEditableCollection 158 | 159 | IPrintWithWriter 160 | (-pr-writer [coll writer opts] 161 | (-write writer (str "#linked/set " (into [] coll))))])) 162 | 163 | #?(:clj 164 | (defmethod print-method LinkedSet [o ^java.io.Writer w] 165 | (.write w "#linked/set ") 166 | (print-method (into [] o) w))) 167 | 168 | (def ^{:tag LinkedSet} empty-linked-set 169 | (LinkedSet. empty-linked-map)) 170 | 171 | (def ->linked-set (partial into empty-linked-set)) 172 | 173 | #?(:cljs (reader/register-tag-parser! 'linked/set ->linked-set)) 174 | -------------------------------------------------------------------------------- /test/linked/map_test.cljc: -------------------------------------------------------------------------------- 1 | (ns linked.map-test 2 | (:require [linked.core :as linked] 3 | #?@(:clj [[clojure.test :refer :all] 4 | [collection-check.core :refer :all] 5 | [clojure.test.check.generators :as gen]] 6 | :cljs [[cljs.test :refer-macros [is are testing deftest run-tests]]]) 7 | #?(:cljs [cljs.reader :refer [read-string]]))) 8 | 9 | #?(:clj 10 | (deftest check 11 | (assert-map-like (linked/map) gen/int gen/int))) 12 | 13 | #?(:clj 14 | (deftest implementations 15 | (let [basic (linked/map)] 16 | (testing "Interfaces marked as implemented" 17 | (are [class] (instance? class basic) 18 | clojure.lang.IPersistentMap 19 | clojure.lang.IPersistentCollection 20 | clojure.lang.Counted 21 | clojure.lang.Associative 22 | java.util.Map)) 23 | (testing "Behavior smoke testing" 24 | (testing "Most operations don't change type" 25 | (are [object] (= (class object) (class basic)) 26 | (conj basic [1 2]) 27 | (assoc basic 1 2) 28 | (into basic {1 2}))) 29 | (testing "Seq-oriented operations return nil when empty" 30 | (are [object] (nil? object) 31 | (seq basic) 32 | (rseq basic))))))) 33 | 34 | (deftest equality 35 | (let [empty-map (linked/map) 36 | one-item (assoc empty-map 1 2)] 37 | (testing "Basic symmetric equality" 38 | (is (= {} empty-map)) 39 | (is (= empty-map {})) 40 | (is (= {1 2} one-item)) 41 | (is (= one-item {1 2}))) 42 | (testing "Order-insensitive comparisons" 43 | (let [one-way (into empty-map {1 2 3 4}) 44 | other-way (into empty-map {3 4 1 2}) 45 | unsorted {1 2 3 4}] 46 | (is (= one-way other-way)) 47 | (is (= one-way unsorted)) 48 | (is (= other-way unsorted)))) 49 | (testing "Hash code sanity" 50 | (is (integer? (hash one-item))) 51 | (is (= (hash {1 2}) (hash one-item)))) 52 | (testing "Does not blow up when give something different" 53 | (is (not= one-item 'baz)) 54 | (is (not= 'baz one-item))) 55 | (testing "nil values don't break .equiv" 56 | (is (not= (linked/map :x nil) {:y 0}))))) 57 | 58 | (deftest ordering 59 | (let [values [[:first 10] 60 | [:second 20] 61 | [:third 30]] 62 | m (into (linked/map) values)] 63 | (testing "Seq behaves like on a seq of vectors" 64 | (is (= (seq values) (seq m)))) 65 | (testing "New values get added at the end" 66 | (let [entry [:fourth 40]] 67 | (is (= (seq (conj values entry)) 68 | (seq (conj m entry)))))) 69 | (testing "Changing old mappings leaves them at the same location" 70 | (let [vec-index [1] 71 | vec-key (conj vec-index 1) 72 | map-key (get-in values (conj vec-index 0)) 73 | new-value 5] 74 | (is (= (seq (assoc-in values vec-key new-value)) 75 | (seq (assoc m map-key new-value)))))) 76 | (testing "Large number of keys still sorted" 77 | (let [kvs (for [n (range 5000)] 78 | [(str n) n]) 79 | ordered (into m kvs)] 80 | (= (seq kvs) (seq ordered)))))) 81 | 82 | (deftest reversing 83 | (let [source (vec (for [n (range 10)] 84 | [n n])) 85 | m (into (sorted-map) source)] 86 | (is (= (rseq m) (rseq source))))) 87 | 88 | (deftest map-features 89 | (let [m (linked/map :a 1 :b 2 :c 3)] 90 | (testing "Keyword lookup" 91 | (is (= 1 (:a m)))) 92 | (testing "Sequence views" 93 | (is (= [:a :b :c] (keys m))) 94 | (is (= [1 2 3] (vals m)))) 95 | (testing "IFn support" 96 | (is (= 2 (m :b))) 97 | (is (= 'not-here (m :nothing 'not-here))) 98 | (is (= nil ((linked/map :x nil) :x 'not-here)))) 99 | (testing "Get out Map.Entry" 100 | (is (= [:a 1] (find m :a)))) 101 | (testing "Get out Map.Entry with falsy value" 102 | (is (= [:a nil] (find (linked/map :a nil) :a)))) 103 | (testing "Ordered dissoc" 104 | (let [m (dissoc m :b)] 105 | (is (= [:a :c] (keys m))) 106 | (is (= [1 3] (vals m))))) 107 | (testing "Empty equality" 108 | (let [m (dissoc m :b :a :c)] 109 | (is (= (linked/map) m)))) 110 | (testing "Can conj a map" 111 | (is (= {:a 1 :b 2 :c 3 :d 4} (conj m {:d 4})))) 112 | (testing "(conj m nil) returns m" 113 | (are [x] (= m x) 114 | (conj m nil) 115 | (merge m ()) 116 | (into m ()))) 117 | (testing "meta support" 118 | (is (= {'a 'b} (meta (with-meta m {'a 'b}))))))) 119 | 120 | (deftest object-features 121 | (let [m (linked/map 'a 1 :b 2)] 122 | (is (= "{a 1, :b 2}" (str m))))) 123 | 124 | (deftest print-and-read-ordered 125 | (let [s (linked/map 1 2, 3 4, 5 6, 1 9, 7 8)] 126 | (is (= "#linked/map [[1 9] [3 4] [5 6] [7 8]]" 127 | (pr-str s))) 128 | (let [o (read-string (pr-str s))] 129 | #?(:clj (is (= linked.map.LinkedMap (type o)))) 130 | (is (= '([1 9] [3 4] [5 6] [7 8]) 131 | (seq o)))))) 132 | 133 | (deftest map-entry-test 134 | (is (map-entry? (first (linked/map 1 2))))) 135 | 136 | #?(:clj 137 | (deftest java-interop 138 | (is (.isEmpty ^java.util.Map (linked/map))) 139 | (is (not (.isEmpty ^java.util.Map (linked/map 1 2)))) 140 | (is (= [] (vec (.entrySet ^java.util.Map (linked/map))))) 141 | (is (= (partition 2 (range 100)) (vec (.entrySet ^java.util.Map (apply linked/map (range 100)))))))) 142 | -------------------------------------------------------------------------------- /test/linked/set_test.cljc: -------------------------------------------------------------------------------- 1 | (ns linked.set-test 2 | (:require [linked.core :as linked] 3 | #?@(:clj [[clojure.test :refer :all] 4 | [collection-check.core :refer :all] 5 | [clojure.test.check.generators :as gen]] 6 | :cljs [[cljs.test :refer-macros [is are testing deftest run-tests]]]) 7 | #?(:cljs [cljs.reader :refer [read-string]]))) 8 | 9 | 10 | #?(:clj 11 | (deftest check 12 | (assert-set-like (linked/set) gen/int))) 13 | 14 | #?(:clj 15 | (deftest implementations 16 | (let [s (linked/set)] 17 | (testing "Interfaces marked as implemented" 18 | (are [class] (instance? class s) 19 | clojure.lang.IPersistentSet 20 | clojure.lang.IPersistentCollection 21 | clojure.lang.Counted 22 | java.util.Set)) 23 | (testing "Behavior smoke testing" 24 | (testing "Most operations don't change type" 25 | (are [object] (= (class object) (class s)) 26 | (conj s 1 2) 27 | (disj s 1) 28 | (into s #{1 2}))) 29 | (testing "Seq-oriented operations return nil when empty" 30 | (are [object] (nil? object) 31 | (seq s) 32 | (rseq s))))))) 33 | 34 | (deftest equality 35 | (let [empty (linked/set) 36 | one-item (conj empty 1)] 37 | (testing "Basic symmetric equality" 38 | (is (= #{} empty)) 39 | (is (= empty #{})) 40 | (is (= #{1} one-item)) 41 | (is (= one-item #{1}))) 42 | (testing "Order-insensitive comparisons" 43 | (let [one-way (into empty [1 2 3 4]) 44 | other-way (into empty [3 4 1 2]) 45 | unsorted #{1 2 3 4}] 46 | (is (= one-way other-way)) 47 | (is (= one-way unsorted)) 48 | (is (= other-way unsorted)))) 49 | (testing "Does not blow up when given something random" 50 | (is (not= one-item 'baz)) 51 | (is (not= 'baz one-item))))) 52 | 53 | (deftest ordering 54 | (let [values [[:first 10] 55 | [:second 20] 56 | [:third 30]] 57 | s (into (linked/set) values)] 58 | (testing "Seq behaves like seq of a vector" 59 | (is (= (seq values) (seq s)))) 60 | (testing "New values get added at the end" 61 | (let [entry [:fourth 40]] 62 | (is (= (seq (conj values entry)) 63 | (seq (conj s entry)))))) 64 | (testing "Re-adding keys leaves them in the same place" 65 | (is (= (seq s) 66 | (seq (conj s [:second 20]))))) 67 | (testing "Large number of keys still sorted" 68 | (let [ints (range 5000) 69 | ordered (into s ints)] 70 | (= (seq ints) (seq ordered)))))) 71 | 72 | (deftest reversing 73 | (let [source (vec (range 1000)) 74 | s (into (linked/set) source)] 75 | (is (= (rseq s) (rseq source))))) 76 | 77 | (deftest set-features 78 | (let [s (linked/set :a 1 :b 2 :c 3)] 79 | (testing "Keyword lookup" 80 | (is (= :a (:a s)))) 81 | (testing "IFn support" 82 | (is (= :b (s :b)))) 83 | (testing "Falsy lookup support" 84 | (is (= false ((linked/set false 1) false)))) 85 | (testing "Ordered disj" 86 | (is (= #{:a 1 2 3} (disj s :b :c)))) 87 | (testing "meta support" 88 | (is (= {'a 'b} (meta (with-meta s {'a 'b}))))) 89 | (testing "cons yields a list with element prepended" 90 | (is (= '(:a :a 1 :b 2 :c 3) (cons :a s)))))) 91 | 92 | (deftest object-features 93 | (let [s (linked/set 'a 1 :b 2)] 94 | (is (= "[a 1 :b 2]" (str s))))) 95 | 96 | (deftest print-and-read-ordered 97 | (let [s (linked/set 1 2 9 8 7 5)] 98 | (is (= "#linked/set [1 2 9 8 7 5]" 99 | (pr-str s))) 100 | (let [o (read-string (pr-str s))] 101 | #?(:clj (is (= linked.set.LinkedSet (type o)))) 102 | (is (= '(1 2 9 8 7 5) 103 | (seq o)))))) 104 | 105 | (deftest comparing 106 | (let [s1 (linked/set 1 2 3) 107 | s2 (linked/set 1 2 4)] 108 | (testing "Comparable support" 109 | (is (= -1 (compare s1 s2))) 110 | (is (= 1 (compare s2 s1))) 111 | (is (= 0 (compare s1 s1)))))) 112 | 113 | (deftest flattening 114 | (let [s (linked/set 1 2 3)] 115 | (testing "flatten support" 116 | (is (= '(1 2 3 4 5 6) 117 | (flatten [s 4 5 6])))))) 118 | --------------------------------------------------------------------------------