Skip to content

Instantly share code, notes, and snippets.

@angerman
Created December 4, 2009 14:02
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 angerman/249025 to your computer and use it in GitHub Desktop.
Save angerman/249025 to your computer and use it in GitHub Desktop.
(use 'clojure.contrib.duck-streams)
(in-ns 'clojure.contrib.duck-streams)
(import '(java.io File RandomAccessFile))
(import 'BufferedRandomAccessFile)
;; copied and adapted from c.c.ds
(defmulti #^{:arglist '([x])} random-access-reader class)
(defmethod random-access-reader File [#^File x]
(BufferedRandomAccessFile. x "r"))
(defmethod random-access-reader String [#^String x]
(random-access-reader (file-str x)))
(defmethod random-access-reader :default [x]
(throw (Exception. (str "Cannot open " (pr-str x) " as a reader."))))
(defn next-line [raf]
(.readLine2 raf))
(defn pos [raf]
(.getFilePointer raf))
(defn seek [raf pos]
(.seek raf pos))
(defn repeatedly-until-nil [f]
(when-let [v (f)]
(lazy-seq (cons v (repeatedly-until-nil f)))))
(defn lazy-rest [rar]
(repeatedly-until-nil #(next-line rar)))
(defmacro save-excursion [ raf & body]
`(let [pos# (pos raf)]
~@body
(seek raf pos#)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment