├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── project.clj ├── src └── com │ └── rpl │ └── vector_backed_sorted_map.clj └── test └── com └── rpl └── vector_backed_sorted_map_test.clj /.gitignore: -------------------------------------------------------------------------------- 1 | pom.xml 2 | pom.xml.asc 3 | *.jar 4 | *.class 5 | /lib/ 6 | /classes/ 7 | /target/ 8 | /checkouts/ 9 | .lein-deps-sum 10 | .lein-repl-history 11 | .lein-plugins/ 12 | .lein-failures 13 | .nrepl-port 14 | .cpcache/ 15 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 | # 0.1.0 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | We welcome external contributions to this project. For ideas for new functionality, we recommend first opening an issue so we can discuss whether it makes sense for the project. 4 | 5 | ## Contribution process 6 | 7 | 1. Open a pull request. If possible, please include thorough tests of the new code. 8 | 2. If you have not already signed a contributor agreement, we will request that you sign one. We use Adobe Sign for this so it's very quick and easy. Note that we cannot look at your pull request until a contributor agreement is signed. 9 | 3. We will then review your pull request and possibly ask for changes. 10 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # vector-backed-sorted-map 2 | [![Clojars Project](https://img.shields.io/clojars/v/com.rpl/vector-backed-sorted-map.svg)](https://clojars.org/com.rpl/vector-backed-sorted-map) 3 | 4 | A sorted map implementation designed for ultra-fast initialization and merge operations. 5 | 6 | Maps returned by this library behave like those returned by Clojure `sorted-map` (PersistentTreeMap), but they have O(1) instantiation time instead of O(N log N). Instantiating a vector-backed sorted map (VBSM) will be dramatically faster than `sorted-map` for more than a small number of elements. The only catch is that your k/v pairs must already be sorted. It's not hard to structure your application such that the data will always be sorted in a previous step or read from disk in sorted order. 7 | 8 | ## Why do I want this? 9 | 10 | The whole point is to be able to provide `sorted-map`-like access pattern over data that isn't currently in a `sorted-map`. 11 | 12 | Let's say you're writing a flat-file database of sorted k/v pairs (something like RocksDB). The files are already sorted in the regular course of operation, but when you load a "file" or a "block" from disk to service a read, that data isn't currently in a `sorted-map`. If you put it into one, you'll pay O(N log N) to do so, which is a pretty bad deal if you're only going to look up a single k/v pair. Even if you'll do something smart like cache the resulting `sorted-map` for future read operations, you had a pay a greater-than-linear cost to get that map into your cache! 13 | 14 | There are a number of existing sorted map libraries that support faster initialization when the input is explicitly sorted, but sadly Clojure doesn't have one, and none of the exiting data structures are compatible with external options like Java's TreeMap. 15 | 16 | ## Usage 17 | 18 | Add a dependency on the [Clojars package](https://clojars.org/com.rpl/vector-backed-sorted-map) 19 | 20 | In your code: 21 | 22 | `(require 'com.rpl.vector-backed-sorted-map :as vbsm)` 23 | 24 | To use, provide a vector of k/v tuples, and optionally a key comparator: 25 | 26 | `(let [m (vbsm/vector-backed-sorted-map [[0 0] [1 1] [2 2]])])` 27 | 28 | The vector tuples will never be mutated or modified in any way and can safely be reused elsewhere. 29 | 30 | The tuples *must* be in already-sorted order! VBSM makes no effort to sort your input, but if assertions are enabled, it will verify that they're in sorted order. This verification behavior is really handy when you're just setting up a system that uses VBSMs, but it is also very, very expensive, so it's a good idea to disable assertions if you're aiming for high performance. 31 | 32 | ## Backing vector access 33 | 34 | If you are using VBSMs explicitly in performance-critical code, it's often handy to be able to set aside the map wrapper all together and just access the backing vector. `vec` and similar core library fns would end up making a copy of the backing vector, and that's no good; so we provide a special helper fn called `vectorize`. `vectorize` exposes the direct backing vector in O(1) time, unless you call it on a VBSM that has overlaid modifications, in which case it will be O(N). (See read-only discussion below for more information). 35 | 36 | ## Fast merge support 37 | 38 | Because of their flat structure, VBSMs are very amenable to high-performance merge operations. The library provides a handy `merge-sorted-optimal` function that implements a size-aware merging strategy, swapping between "one by one" and "bulk" modes based on relative sizes of the VBSMs being merged. Using this function tends to beat Clojure `merge` very handily. 39 | 40 | ## Read-only vs "updatable" VBSMs 41 | 42 | When you instantiate a VBSM via `vector-backed-sorted-map`, you get back an "updatable" VBSM, that is, one that can be modified normally by `assoc`, `dissoc`, etc. This updatability is provided via an internal hidden overlay map, which is just a regular Clojure sorted-map. This approach avoids uncesssary vector surgery and makes random updates fairly cheap, particularly when the total number of updates is relatively small. However, there is an added cost at iteration or `vectorize` time, as the overlay has to be flattened into the backing vector to produce a new backing vector, making the operation take O(N). 43 | 44 | It can be difficult to reason about whether a given map ever gets updated, so we provide the option to get a "read-only" VBSM by calling `read-only-vector-backed-sorted-map`. `assoc`, `dissoc`, etc will throw exceptions when invoked on a read-only VBSM. Using a read-only VBSM allows you to ensure that merge and `vectorize` operations down the road will always be consistently O(1), which can be important for performance-critical code. 45 | 46 | ## License 47 | 48 | Copyright © 2019 - 2020 Red Planet Labs Inc. 49 | 50 | Distributed under the Apache Software License version 2.0 51 | -------------------------------------------------------------------------------- /project.clj: -------------------------------------------------------------------------------- 1 | (defproject com.rpl/vector-backed-sorted-map "0.1.0" 2 | :description "A sorted map implementation designed for ultra-fast initialization and merge operations." 3 | :url "https://github.com/redplanetlabs/vector-backed-sorted-map" 4 | :dependencies [[org.clojure/clojure "1.10.0"] 5 | [potemkin "0.4.5"]] 6 | :test-paths ["test"] 7 | :plugins [[lein-exec "0.3.7"]] 8 | :profiles {:dev {:dependencies 9 | [[org.clojure/test.check "0.9.0"] 10 | [org.clojure/spec.alpha "0.2.176"]]} 11 | :check {:warn-on-reflection true} 12 | :nrepl {:lein-tools-deps/config {:resolve-aliases [:nrepl]}} 13 | :aot {:aot :all} 14 | } 15 | ) 16 | -------------------------------------------------------------------------------- /src/com/rpl/vector_backed_sorted_map.clj: -------------------------------------------------------------------------------- 1 | (ns com.rpl.vector-backed-sorted-map 2 | (:use [potemkin]) 3 | ) 4 | 5 | (assert (do (println "Warning: Assertions are enabled while loading VectorBackedSortedMap. This has a gigantic performance impact and should only be allowed in testing!") 6 | true)) 7 | 8 | (defn apv-fast-nth [^clojure.lang.APersistentVector v ^long idx] 9 | (.nth v idx nil)) 10 | 11 | (declare vector-backed-sorted-map) 12 | (declare read-only-vector-backed-sorted-map) 13 | 14 | (declare check-integrity!) 15 | 16 | (defprotocol VectorizableMap 17 | (get-comparator [this]) 18 | (vectorize [this]) 19 | (vectorize-from [this k]) 20 | ) 21 | 22 | (extend-protocol VectorizableMap 23 | clojure.lang.PersistentTreeMap 24 | (vectorize [this] (vec this)) 25 | (get-comparator [this] 26 | (let [c (.comparator this)] 27 | (if (identical? c clojure.lang.RT/DEFAULT_COMPARATOR) 28 | compare 29 | c))) 30 | ) 31 | 32 | (defn- binary-search [^clojure.lang.APersistentVector kv-vec comparator k] 33 | (loop [lower-idx 0 34 | upper-idx (unchecked-dec (.length kv-vec))] 35 | (if (= lower-idx upper-idx) 36 | (let [[mid-key mid-val] (.nth kv-vec lower-idx)] 37 | ;; either this is it, or this is where it would be if present. 38 | ;; return it all and let the caller decide. 39 | [mid-key mid-val lower-idx]) 40 | (let [mid-idx (unchecked-add lower-idx ^long (bit-shift-right (unchecked-subtract upper-idx lower-idx) 1)) 41 | mid-elt (.nth kv-vec mid-idx) 42 | mid-key (apv-fast-nth mid-elt 0) 43 | comparison (comparator k mid-key)] 44 | (if (> ^long comparison 0) 45 | (recur (unchecked-inc mid-idx) upper-idx) 46 | (recur lower-idx mid-idx))))) 47 | ) 48 | 49 | (def-map-type EmptyVectorBackedSortedMap [comparator meta-map] 50 | (get [_ k default-value] 51 | default-value) 52 | 53 | (assoc [_ k v] 54 | (throw (ex-info "EmptyVBSM doesn't support assoc!" {}))) 55 | 56 | (dissoc [this k] 57 | (throw (ex-info "EmptyVBSM doesn't support dissoc!" {}))) 58 | 59 | (keys [_] []) 60 | 61 | (with-meta [_ mta] 62 | (EmptyVectorBackedSortedMap. comparator mta)) 63 | 64 | clojure.lang.Sorted 65 | (entryKey [this entry] 66 | (first entry)) 67 | (comparator [this] comparator) 68 | 69 | (seq [this ascending] 70 | (seq [])) 71 | 72 | (seqFrom [this k ascending] 73 | (seq this)) 74 | 75 | clojure.lang.Associative 76 | (containsKey [this k] false) 77 | 78 | VectorizableMap 79 | (get-comparator [_] comparator) 80 | (vectorize [_] []) 81 | (vectorize-from [_ _] []) 82 | ) 83 | 84 | (def-map-type VectorBackedSortedMap 85 | [kv-vec 86 | comparator 87 | meta-map 88 | ^:volatile-mutable last-get-info] 89 | (get [_ k default-value] 90 | (let [[last-key last-val] last-get-info] 91 | (if (and (some? last-key) (= last-key k)) 92 | (if (identical? ::not-found last-val) 93 | default-value 94 | last-val) 95 | (let [[found-key val _] (binary-search kv-vec comparator k)] 96 | (if (= found-key k) 97 | (do 98 | (set! last-get-info [k val]) 99 | val) 100 | (do 101 | (set! last-get-info [k ::not-found]) 102 | default-value)))))) 103 | 104 | (assoc [_ k v] 105 | (throw (ex-info "Regular VBSM doesn't support assoc!" {}))) 106 | 107 | (dissoc [this k] 108 | (throw (ex-info "Regular VBSM doesn't support dissoc!" {}))) 109 | 110 | (keys [_] 111 | (map first kv-vec)) 112 | 113 | (with-meta [_ mta] 114 | (VectorBackedSortedMap. kv-vec comparator mta last-get-info)) 115 | 116 | ;; this is non-standard potemkin usage. if we use the provided seqable impl, 117 | ;; iterating the map ends up taking O (n log n)! 118 | clojure.lang.Seqable 119 | (seq [this] 120 | (seq (map (fn [[k v]] (clojure.lang.MapEntry. k v)) kv-vec))) 121 | 122 | clojure.lang.Counted 123 | (count [_] 124 | (count kv-vec)) 125 | 126 | clojure.lang.Sorted 127 | (entryKey [this entry] 128 | (first entry)) 129 | 130 | (comparator [this] comparator) 131 | 132 | (seq [this ascending] 133 | (if ascending 134 | (seq this) 135 | (reverse (seq this)))) 136 | 137 | (seqFrom [this k ascending] 138 | (let [trimmed-vec (vectorize-from this k) 139 | entryized (map (fn [[k v]] (clojure.lang.MapEntry. k v)) trimmed-vec)] 140 | (if ascending 141 | entryized 142 | (reverse entryized)))) 143 | 144 | clojure.lang.Associative 145 | (containsKey [this k] 146 | (not= ::not-found (get this k ::not-found))) 147 | 148 | VectorizableMap 149 | (get-comparator [_] comparator) 150 | (vectorize [_] kv-vec) 151 | (vectorize-from [_ k] 152 | ;; TODO: could this be off by one if there's not an exact match? 153 | (let [[_ _ found-idx] (binary-search kv-vec comparator k)] 154 | (subvec kv-vec found-idx))) 155 | ) 156 | 157 | (defn- linear-merge-overlay [start-key regular-vbsm overlay-map] 158 | (let [a-vec (if start-key 159 | (vectorize-from regular-vbsm start-key) 160 | (vectorize regular-vbsm)) 161 | b-vec (if start-key 162 | (vec (.seqFrom ^clojure.lang.PersistentTreeMap overlay-map start-key true)) 163 | (vec overlay-map)) 164 | comparator (get-comparator regular-vbsm)] 165 | (loop [results (transient []) 166 | a-idx 0 167 | b-idx 0] 168 | (let [ 169 | a-elt (apv-fast-nth a-vec a-idx) 170 | a-key (if a-elt (apv-fast-nth a-elt 0)) 171 | b-elt (apv-fast-nth b-vec b-idx) 172 | b-key (if b-elt (apv-fast-nth b-elt 0)) b-val (if b-elt (apv-fast-nth b-elt 1)) 173 | ] 174 | (cond 175 | (nil? a-key) 176 | (persistent! (reduce conj! results (subvec b-vec b-idx))) 177 | 178 | (nil? b-key) 179 | (persistent! (reduce conj! results (subvec a-vec a-idx))) 180 | 181 | :else 182 | (let [comparison (comparator a-key b-key)] 183 | (cond 184 | (< ^long comparison 0) 185 | ;; consume a (no match) 186 | (recur 187 | (conj! results a-elt) 188 | (unchecked-inc a-idx) 189 | b-idx) 190 | 191 | (> ^long comparison 0) 192 | ;; consume b (no match) 193 | (recur 194 | (conj! results b-elt) 195 | a-idx 196 | (unchecked-inc b-idx)) 197 | 198 | (identical? ::tombstone b-val) 199 | ;; keys match, and the b-val is a tombstone, so don't add anything to results 200 | (recur 201 | results 202 | (unchecked-inc a-idx) 203 | (unchecked-inc b-idx)) 204 | 205 | :else 206 | ;; keys match, not a tombstone, take later value 207 | (recur 208 | (conj! results [a-key b-val]) 209 | (unchecked-inc a-idx) 210 | (unchecked-inc b-idx)))))))) 211 | ) 212 | 213 | (def-map-type OverlayVectorBackedSortedMap [regular-vbsm overlay-map comparator cached-count meta-map] 214 | (get [_ k default-value] 215 | (let [overlay-value (get overlay-map k ::not-found)] 216 | (if-not (identical? ::not-found overlay-value) 217 | overlay-value 218 | (if-not (identical? ::tombstone overlay-value) 219 | (get regular-vbsm k default-value) 220 | default-value)))) 221 | 222 | (assoc [_ k v] 223 | (let [overlay-value (get overlay-map k ::not-found) 224 | new-count 225 | (if (contains? regular-vbsm k) 226 | (if (identical? ::tombstone overlay-value) 227 | (unchecked-inc ^long cached-count) 228 | cached-count) 229 | (if (identical? ::not-found overlay-value) 230 | (unchecked-inc ^long cached-count) 231 | cached-count)) 232 | new-overlay (assoc overlay-map k v)] 233 | (OverlayVectorBackedSortedMap. regular-vbsm 234 | new-overlay 235 | comparator 236 | new-count 237 | meta-map))) 238 | 239 | (dissoc [this k] 240 | (let [overlay-value (get overlay-map k ::not-found) 241 | vbsm-value (get regular-vbsm k ::not-found)] 242 | (cond 243 | (= ::tombstone overlay-value) 244 | ;; already deleted this key. no-op. 245 | this 246 | 247 | (and (= ::not-found overlay-value) 248 | (= ::not-found vbsm-value)) 249 | ;; the key isn't present in the map at either level. no-op. 250 | this 251 | 252 | (and (not= ::not-found overlay-value) 253 | (= ::not-found vbsm-value)) 254 | ;; overlay has an actual value for k, but regular vbsm doesn't, 255 | ;; which means this key was added only to overlay. 256 | ;; we can just delete the tombstone itself in the overlay. 257 | (OverlayVectorBackedSortedMap. regular-vbsm 258 | (dissoc overlay-map k) 259 | comparator 260 | (unchecked-dec ^long cached-count) 261 | meta-map) 262 | 263 | :else 264 | ;; vbsm has a value, and overlay may or may not have a value. 265 | ;; either way, set a tombstone. 266 | (OverlayVectorBackedSortedMap. regular-vbsm 267 | (assoc overlay-map k ::tombstone) 268 | comparator 269 | (unchecked-dec ^long cached-count) 270 | meta-map) 271 | ))) 272 | (keys [this] (map first (seq this))) 273 | 274 | (with-meta [_ mta] 275 | (OverlayVectorBackedSortedMap. regular-vbsm 276 | overlay-map 277 | comparator 278 | cached-count 279 | meta-map)) 280 | 281 | clojure.lang.Seqable 282 | (seq [this] 283 | (seq (map (fn [[k v]] 284 | (clojure.lang.MapEntry. k v)) 285 | (vectorize this)))) 286 | 287 | clojure.lang.Counted 288 | (count [_] 289 | cached-count) 290 | 291 | clojure.lang.Sorted 292 | (entryKey [this entry] 293 | (first entry)) 294 | 295 | (comparator [this] comparator) 296 | 297 | (seq [this ascending] 298 | (if ascending 299 | (seq this) 300 | (reverse (seq this)))) 301 | 302 | (seqFrom [this k ascending] 303 | (let [merged-entryized (map (fn [[k v]] (clojure.lang.MapEntry. k v)) 304 | (linear-merge-overlay k regular-vbsm overlay-map))] 305 | (if ascending 306 | merged-entryized 307 | (reverse merged-entryized)))) 308 | 309 | clojure.lang.Associative 310 | (containsKey [this k] 311 | (not= ::not-found (get this k ::not-found))) 312 | 313 | VectorizableMap 314 | (get-comparator [_] comparator) 315 | (vectorize [_] 316 | (if (empty? overlay-map) 317 | (vectorize regular-vbsm) 318 | (linear-merge-overlay nil regular-vbsm overlay-map))) 319 | (vectorize-from [_ k] 320 | (if (empty? overlay-map) 321 | (vectorize-from regular-vbsm k) 322 | (linear-merge-overlay k regular-vbsm overlay-map))) 323 | ) 324 | 325 | (defn read-only-vector-backed-sorted-map 326 | "Create a SortedMap implementation backed by a vector of K-V pairs. Creation 327 | of this map from an already-sorted vector of pairs is O(1). Lookups are 328 | O(log n). assoc / dissoc are not allowed." 329 | ([kv-pairs-vec] 330 | (read-only-vector-backed-sorted-map compare kv-pairs-vec)) 331 | ([comparator kv-pairs-vec] 332 | (if (empty? kv-pairs-vec) 333 | (EmptyVectorBackedSortedMap. comparator {}) 334 | (check-integrity! (VectorBackedSortedMap. kv-pairs-vec comparator {} nil))))) 335 | 336 | (defn vector-backed-sorted-map 337 | "Create a SortedMap implementation backed by a vector of K-V pairs. Creation 338 | of this map from an already-sorted vector of pairs is O(1). Lookups are 339 | O(log n) if the map is never modified; assoc / dissoc calls modify a standard 340 | (sorted-map) overlay which is queried first. " 341 | ([kv-pairs-vec] 342 | (vector-backed-sorted-map compare kv-pairs-vec)) 343 | ([comparator kv-pairs-vec] 344 | (OverlayVectorBackedSortedMap. (read-only-vector-backed-sorted-map comparator kv-pairs-vec) 345 | (sorted-map-by comparator) 346 | comparator 347 | (count kv-pairs-vec) 348 | {}))) 349 | 350 | (defn check-integrity! 351 | "Make sure the vbsm is actually in sorted order. Throws an exception if it's not." 352 | [vbsm] 353 | (assert (let [backing-v (vectorize vbsm) 354 | tuple-sizes (group-by count backing-v)] 355 | (= (keys tuple-sizes) [2])) 356 | "There were some weird sized tuples in the backing vector!!!") 357 | (assert (let [backing-v (vectorize vbsm) 358 | comparator (or (get-comparator vbsm) compare) 359 | sorted-keys (->> backing-v 360 | (into (sorted-map-by comparator)) 361 | (mapv first))] 362 | (= (map first backing-v) sorted-keys)) 363 | (str "Backing vector keys were not in sorted order!" (map first vbsm))) 364 | vbsm) 365 | 366 | (defn ensure-vbsm 367 | ([maybe-vbsm] 368 | (if (instance? VectorBackedSortedMap maybe-vbsm) 369 | maybe-vbsm 370 | (vector-backed-sorted-map (get-comparator maybe-vbsm) (vectorize maybe-vbsm)))) 371 | ([maybe-vbsm comparator] 372 | (if (and (instance? VectorBackedSortedMap maybe-vbsm) 373 | (identical? comparator (get-comparator maybe-vbsm))) 374 | maybe-vbsm 375 | (vector-backed-sorted-map comparator (vectorize maybe-vbsm))))) 376 | 377 | (defn- latest [a b] b) 378 | 379 | (defn merge-sorted-large 380 | ([vbsm1 vbsm2] (merge-sorted-large vbsm1 vbsm2 latest)) 381 | ([vbsm1 vbsm2 f] 382 | (let [a-vec (vectorize vbsm1) 383 | b-vec (vectorize vbsm2) 384 | comparator (get-comparator vbsm1)] 385 | (loop [results (transient []) 386 | a-idx 0 387 | b-idx 0] 388 | (let [ 389 | a-elt (apv-fast-nth a-vec a-idx) 390 | a-key (if a-elt (apv-fast-nth a-elt 0)) 391 | b-elt (apv-fast-nth b-vec b-idx) 392 | b-key (if b-elt (apv-fast-nth b-elt 0)) 393 | ] 394 | (cond 395 | (nil? a-key) 396 | (vector-backed-sorted-map comparator 397 | (persistent! (reduce conj! results (subvec b-vec b-idx)))) 398 | 399 | (nil? b-key) 400 | (vector-backed-sorted-map comparator 401 | (persistent! (reduce conj! results (subvec a-vec a-idx)))) 402 | 403 | :else 404 | (let [comparison (comparator a-key b-key)] 405 | (cond 406 | (< ^long comparison 0) 407 | ;; consume a (no match) 408 | (recur 409 | (conj! results a-elt) 410 | (unchecked-inc a-idx) 411 | b-idx) 412 | 413 | (> ^long comparison 0) 414 | ;; consume b (no match) 415 | (recur 416 | (conj! results b-elt) 417 | a-idx 418 | (unchecked-inc b-idx)) 419 | 420 | :else 421 | ;; it's a match! consume both and merge with the provided fn 422 | (recur 423 | (conj! results [a-key (f (apv-fast-nth a-elt 1) (apv-fast-nth b-elt 1))]) 424 | (unchecked-inc a-idx) 425 | (unchecked-inc b-idx))))))))) 426 | ) 427 | 428 | (defn merge-sorted-small 429 | ([vbsm1 vbsm2] (merge-sorted-small vbsm1 vbsm2 latest)) 430 | ([vbsm1 vbsm2 f] 431 | (merge-with f vbsm1 vbsm2)) 432 | ) 433 | 434 | (defn merge-sorted-optimal 435 | ([vbsm1 vbsm2] (merge-sorted-optimal vbsm1 vbsm2 latest)) 436 | ([vbsm1 vbsm2 f] 437 | (cond 438 | (empty? vbsm1) 439 | vbsm2 440 | 441 | (empty? vbsm2) 442 | vbsm1 443 | 444 | (< (count vbsm2) (* 0.10 (count vbsm1))) 445 | (merge-sorted-small vbsm1 vbsm2 f) 446 | 447 | :else 448 | (merge-sorted-large vbsm1 vbsm2 f))) 449 | ) 450 | -------------------------------------------------------------------------------- /test/com/rpl/vector_backed_sorted_map_test.clj: -------------------------------------------------------------------------------- 1 | (ns com.rpl.vector-backed-sorted-map-test 2 | (:use [clojure test] 3 | [clojure.test.check.clojure-test]) 4 | (:require [com.rpl.vector-backed-sorted-map :as vbsm] 5 | [clojure.test.check 6 | [generators :as gen] 7 | [properties :as prop]]) 8 | ) 9 | 10 | 11 | (deftest vbsm-basic-test 12 | (let [m (vbsm/read-only-vector-backed-sorted-map [[1 1] [2 2] [3 3]])] 13 | (is (= 1 (get m 1))) 14 | (is (= 2 (get m 2))) 15 | (is (= 3 (get m 3))) 16 | (is (nil? (get m 4))) 17 | (is (= :default (get m 4 :default))) 18 | (is (= [1 2 3] (keys m))) 19 | )) 20 | 21 | (deftest updatable-vbsm-basic-test 22 | (let [m (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]])] 23 | (is (= 1 (get m 1))) 24 | (is (= 2 (get m 2))) 25 | (is (= 3 (get m 3))) 26 | (is (nil? (get m 4))) 27 | (is (= 3 (count m))) 28 | (is (= :default (get m 4 :default))) 29 | (is (= [1 2 3] (keys m))) 30 | 31 | (let [m (assoc m 2 5)] 32 | (is (= 3 (count m))) 33 | (is (= 1 (get m 1))) 34 | (is (= 5 (get m 2))) 35 | (is (= 3 (get m 3))) 36 | (is (nil? (get m 4))) 37 | (is (= [1 2 3] (keys m))) 38 | 39 | (let [ m (assoc m 4 4)] 40 | (is (= 4 (count m))) 41 | (is (= 1 (get m 1))) 42 | (is (= 5 (get m 2))) 43 | (is (= 3 (get m 3))) 44 | (is (= 4 (get m 4))) 45 | (is (= [1 2 3 4] (keys m))) 46 | 47 | (let [m (assoc m 0 0 -1 -1)] 48 | (is (= 6 (count m))) 49 | (is (= 0 (get m 0))) 50 | (is (= -1 (get m -1))) 51 | (is (= 1 (get m 1))) 52 | (is (= 5 (get m 2))) 53 | (is (= 3 (get m 3))) 54 | (is (= 4 (get m 4))) 55 | (is (= [-1 0 1 2 3 4] (keys m))) 56 | 57 | (let [ m1 (dissoc m 10)] 58 | (is (identical? m m1))) 59 | 60 | (let [ m (dissoc m 0)] 61 | (is (= 5 (count m))) 62 | (is (nil? (get m 0))) 63 | (is (= -1 (get m -1))) 64 | (is (= 1 (get m 1))) 65 | (is (= 5 (get m 2))) 66 | (is (= 3 (get m 3))) 67 | (is (= 4 (get m 4))) 68 | (is (= [-1 1 2 3 4] (keys m))) 69 | 70 | (let [ m (dissoc m -1 4)] 71 | (is (= 3 (count m))) 72 | (is (nil? (get m 0))) 73 | (is (nil? (get m -1))) 74 | (is (= 1 (get m 1))) 75 | (is (= 5 (get m 2))) 76 | (is (= 3 (get m 3))) 77 | (is (nil? (get m 4))) 78 | (is (= [1 2 3] (keys m)))))))) 79 | )) 80 | 81 | (deftest empty-vec-test 82 | (let [ m (vbsm/vector-backed-sorted-map [])] 83 | (is (nil? (get m 1))) 84 | (is (nil? (keys m)))) 85 | 86 | (let [m (vbsm/vector-backed-sorted-map [])] 87 | (is (nil? (get m 1))) 88 | (is (nil? (keys m))) 89 | (let [ m (assoc m 1 1)] 90 | (is (= [1] (keys m))))) 91 | 92 | (let [m (vbsm/vector-backed-sorted-map [])] 93 | (is (nil? (keys m))) 94 | (let [m (dissoc m 1)] 95 | (is (nil? (keys m))))) 96 | ) 97 | 98 | (defspec regular-map-equivalence-test 99 | 1000 100 | (prop/for-all [init-state (gen/vector 101 | (gen/tuple 102 | gen/int 103 | gen/int) 104 | 0 25) 105 | actions (gen/vector 106 | (gen/tuple 107 | (gen/elements #{:assoc :dissoc}) 108 | gen/int 109 | gen/int) 110 | 1 1000)] 111 | (let [regular-map (into (sorted-map) init-state) 112 | vbsm (vbsm/vector-backed-sorted-map (vec (into (sorted-map) init-state))) 113 | [final-regular-map final-vbsm] 114 | (reduce 115 | (fn [[r-map vb-map] [action-typ k v]] 116 | (if (= action-typ :assoc) 117 | [(assoc r-map k v) (assoc vb-map k v)] 118 | [(dissoc r-map k) (dissoc vb-map k)])) 119 | [regular-map vbsm] 120 | actions)] 121 | (if (= final-regular-map final-vbsm) 122 | true 123 | (do 124 | (println "regular:" final-regular-map) 125 | (println "vbsm: " final-vbsm) 126 | (println "count regular:" (count final-regular-map)) 127 | (println "count vbsm: " (count final-vbsm)) 128 | (println "keys regular:" (keys final-regular-map)) 129 | (println "keys vbsm:" (keys final-vbsm)) 130 | false))))) 131 | 132 | (deftest vbsm-sorted-test 133 | (let [ m (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]])] 134 | (is (= [1 2 3] (keys m))) 135 | (let [ headmap (subseq m <= 2)] 136 | (is (= [1 2] (keys headmap)))) 137 | 138 | (let [tailmap (subseq m >= 2)] 139 | (is (= [2 3] (keys tailmap))))) 140 | ) 141 | 142 | (deftest updatable-sorted-test 143 | (let [ m (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]])] 144 | (is (= [1 2 3] (keys m))) 145 | (let [headmap (subseq m <= 2)] 146 | (is (= [1 2] (keys headmap)))) 147 | 148 | (let [tailmap (subseq m >= 2)] 149 | (is (= [2 3] (keys tailmap))))) 150 | 151 | 152 | (deftest check-integrity-test 153 | (is (thrown? Error (vbsm/vector-backed-sorted-map [[3 1] [2 2] [1 3]]))) 154 | )) 155 | 156 | (deftest merge-sorted-basic-test 157 | (let [vbsm1 (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]]) 158 | vbsm2 (vbsm/vector-backed-sorted-map [[4 4] [5 5] [6 6]]) 159 | merged-vbsm (vbsm/merge-sorted-optimal vbsm1 vbsm2)] 160 | (is (= merged-vbsm (sorted-map 1 1 2 2 3 3 4 4 5 5 6 6)))) 161 | 162 | (let [vbsm1 (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]]) 163 | vbsm2 (vbsm/vector-backed-sorted-map [[1 2] [2 1] [6 6]]) 164 | merged-vbsm (vbsm/merge-sorted-optimal vbsm1 vbsm2)] 165 | (is (= merged-vbsm (sorted-map 1 2 2 1 3 3 6 6)))) 166 | 167 | (let [vbsm1 (vbsm/vector-backed-sorted-map [[1 1] [2 2] [3 3]]) 168 | vbsm2 (vbsm/vector-backed-sorted-map [[1 2] [2 1] [6 6]]) 169 | merged-vbsm (vbsm/merge-sorted-optimal vbsm1 vbsm2 +)] 170 | (is (= merged-vbsm (sorted-map 1 3 2 3 3 3 6 6)))) 171 | ) 172 | 173 | (defn- mk-vbsm [kvs] 174 | (vbsm/vector-backed-sorted-map (vec (into (sorted-map) kvs)))) 175 | 176 | (defspec merge-sorted-generative-test 177 | 1000 178 | (prop/for-all [a-vals (gen/vector 179 | (gen/tuple 180 | gen/int 181 | gen/int) 182 | 0 2000) 183 | b-vals (gen/vector 184 | (gen/tuple 185 | gen/int 186 | gen/int) 187 | 0 2000)] 188 | (let [vbsm-a (mk-vbsm a-vals) 189 | vbsm-b (mk-vbsm b-vals) 190 | merge-sorted-result (vbsm/merge-sorted-optimal vbsm-a vbsm-b) 191 | standard-merge-result (merge vbsm-a vbsm-b)] 192 | (if (= merge-sorted-result standard-merge-result) 193 | true 194 | (do 195 | (println "merge-sorted:" merge-sorted-result) 196 | (println "clj merge: " standard-merge-result) 197 | false))))) 198 | --------------------------------------------------------------------------------