Created
December 3, 2012 16:49
-
-
Save dyba/4196228 to your computer and use it in GitHub Desktop.
Maintaining State in Clojure
This file contains hidden or 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 ^:private progress-input-stream | |
| [^java.io.InputStream input-stream size] | |
| (let [total-read (atom 0)] | |
| (proxy [java.io.InputStream] [] | |
| (available [] | |
| (.available input-stream)) | |
| (close [] | |
| (.close input-stream)) | |
| (read | |
| ([] | |
| (let [data (.read input-stream)] | |
| (when (> data -1) | |
| (reset! total-read (report-progress 1 @total-read size))) | |
| data)) | |
| ([b] | |
| (let [bytes-read (.read input-stream b)] | |
| (when (pos? bytes-read) | |
| (reset! total-read (report-progress bytes-read @total-read size))) | |
| bytes-read)) | |
| ([b off len] | |
| (let [bytes-read (.read input-stream b off len)] | |
| (when (pos? bytes-read) | |
| (reset! total-read (report-progress bytes-read @total-read size))) | |
| bytes-read))) | |
| (skip [n] | |
| (let [bytes-skipped (.skip input-stream n)] | |
| (when (pos? bytes-skipped) | |
| (reset! total-read (report-progress bytes-skipped @total-read size))) | |
| bytes-skipped))))) |
This file contains hidden or 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
| (def total-bytes-read (atom 0)) | |
| (defn- update-bytes-read | |
| [bytes-read-atom new-bytes-read] | |
| (swap! bytes-read-atom + new-bytes-read)) | |
| (defn- reset-bytes-read | |
| [bytes-read-atom] | |
| (reset! bytes-read-atom 0)) | |
| (defn- progress-input-stream | |
| [^java.io.InputStream input-stream] | |
| (proxy [java.io.InputStream] [] | |
| (available | |
| [] | |
| (.available input-stream)) | |
| (close | |
| [] | |
| (.close input-stream)) | |
| (read | |
| ([] | |
| (let [data (.read input-stream)] | |
| (when (> data -1) | |
| (update-bytes-read total-bytes-read 1)) | |
| data)) | |
| ([b] | |
| (let [bytes-read (.read input-stream b)] | |
| (when (pos? bytes-read) | |
| (update-bytes-read total-bytes-read bytes-read)) | |
| bytes-read)) | |
| ([b off len] | |
| (let [bytes-read (.read input-stream b off len)] | |
| (when (pos? bytes-read) | |
| (update-bytes-read total-bytes-read bytes-read)) | |
| bytes-read))) | |
| (skip | |
| [n] | |
| (let [bytes-skipped (.skip input-stream n)] | |
| (when (pos? bytes-skipped) | |
| (update-bytes-read total-bytes-read bytes-skipped)) | |
| bytes-skipped))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment