Skip to content

Instantly share code, notes, and snippets.

@owainlewis
Last active June 21, 2023 05:30
Show Gist options
  • Select an option

  • Save owainlewis/1e7d1e68a6818ee4d50e to your computer and use it in GitHub Desktop.

Select an option

Save owainlewis/1e7d1e68a6818ee4d50e to your computer and use it in GitHub Desktop.

Revisions

  1. owainlewis revised this gist Mar 16, 2016. 2 changed files with 10 additions and 0 deletions.
    File renamed without changes.
    10 changes: 10 additions & 0 deletions GzipSpec.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    class GzipSpec extends WordSpecLike with Matchers {

    "The GZIP object" should {

    "decompress a compressed string" in {
    val input = Gzip.compress("Hello World".getBytes("UTF-8"))
    Gzip.decompress(input) shouldBe Some("Hello World")
    }
    }
    }
  2. owainlewis created this gist Mar 16, 2016.
    23 changes: 23 additions & 0 deletions GZIP.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import java.io.{ByteArrayOutputStream, ByteArrayInputStream}
    import java.util.zip.{GZIPOutputStream, GZIPInputStream}

    import scala.util.Try

    object Gzip {

    def compress(input: Array[Byte]): Array[Byte] = {
    val bos = new ByteArrayOutputStream(input.length)
    val gzip = new GZIPOutputStream(bos)
    gzip.write(input)
    gzip.close()
    val compressed = bos.toByteArray
    bos.close()
    compressed
    }

    def decompress(compressed: Array[Byte]): Option[String] =
    Try {
    val inputStream = new GZIPInputStream(new ByteArrayInputStream(compressed))
    scala.io.Source.fromInputStream(inputStream).mkString
    }.toOption
    }