Created
August 21, 2012 19:00
-
-
Save mattmoss/3418356 to your computer and use it in GitHub Desktop.
Data and methods to generate unique numeric ids/handles upon request, reusing released handles.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(defn inc-wrap | |
"increment with wraparound to 0; limit should be positive" | |
[x limit] | |
(if (< x limit) (inc x) 0)) | |
(defn handle-pool | |
[limit] | |
(ref {:next 0 :limit limit :in-use #{}})) | |
(defn- unique-handle | |
[pool] | |
(loop [h (:next pool)] | |
(if (contains? (:in-use pool) h) | |
(recur (inc-wrap h (:limit pool))) | |
h))) | |
(defn request-handle | |
[pool] | |
(dosync | |
(let [h (unique-handle @pool)] | |
(alter pool update-in [:next] inc-wrap (:limit @pool)) | |
(alter pool update-in [:in-use] conj h) | |
h))) | |
(defn release-handle | |
[pool h] | |
(dosync | |
(alter pool update-in [:in-use] disj h))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment