Last active
July 17, 2019 21:44
-
-
Save mangosmoothie/eefc6a77228a943b80e85c19852df1b2 to your computer and use it in GitHub Desktop.
clojure gzip compress-decompress
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
(: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