Skip to content

Instantly share code, notes, and snippets.

@mangosmoothie
Last active July 17, 2019 21:44
Show Gist options
  • Save mangosmoothie/eefc6a77228a943b80e85c19852df1b2 to your computer and use it in GitHub Desktop.
Save mangosmoothie/eefc6a77228a943b80e85c19852df1b2 to your computer and use it in GitHub Desktop.
clojure gzip compress-decompress
(:import java.io.ByteArrayInputStream
java.io.ByteArrayOutputStream
java.io.OutputStream
java.util.zip.GZIPInputStream
java.util.zip.GZIPOutputStream
java.nio.charset.Charset)
(defn compress ^bytes [^String s]
(.toByteArray
(with-open [*output (ByteArrayOutputStream.)
*gzip (GZIPOutputStream. *output)]
(.write *gzip (.getBytes s (Charset/forName "UTF-8")))
*output)))
(defn decompress ^String [^bytes input]
(let [*buffer (byte-array 4096)]
(with-open [*reader (-> input ByteArrayInputStream. GZIPInputStream.)
*output (ByteArrayOutputStream.)]
(loop [len (.read *reader *buffer)]
(if (> len -1)
(do (.write *output *buffer 0 len)
(recur (.read *reader *buffer)))
(.toString *output "UTF-8"))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment