Skip to content

Instantly share code, notes, and snippets.

@mattmoss
Created August 21, 2012 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattmoss/3418356 to your computer and use it in GitHub Desktop.
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.
(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