diff --git a/server/app/com/xsn/explorer/gcs/GolombEncoding.scala b/server/app/com/xsn/explorer/gcs/GolombEncoding.scala index 80ce1ba..670aa2f 100644 --- a/server/app/com/xsn/explorer/gcs/GolombEncoding.scala +++ b/server/app/com/xsn/explorer/gcs/GolombEncoding.scala @@ -17,9 +17,18 @@ class GolombEncoding(p: Int, m: Int, key: SipHashKey) { private val hasher = Hashing.sipHash24(key.k0, key.k1) /** - * Encodes the given word list. + * Encodes the given word set. */ - def encode(words: Set[String]): GolombCodedSet = { + def encode(words: Set[String]): Option[GolombCodedSet] = { + if (words.isEmpty) { + Option.empty + } else { + val gcs = encodeNonEmptySet(words) + Option(gcs) + } + } + + private def encodeNonEmptySet(words: Set[String]): GolombCodedSet = { val sortedHashes = hashes(words) val diffList = differences(sortedHashes) val encodedBits = diffList.flatMap(golombEncode) diff --git a/server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala b/server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala index 2aff439..619f367 100644 --- a/server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala +++ b/server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala @@ -1,11 +1,13 @@ package com.xsn.explorer.gcs import com.google.common.io.BaseEncoding -import org.scalatest.{MustMatchers, WordSpec} +import org.scalatest.MustMatchers._ +import org.scalatest.OptionValues._ +import org.scalatest.WordSpec -class GolombEncodingSpec extends WordSpec with MustMatchers { +class GolombEncodingSpec extends WordSpec { - val words = List( + val words = Set( "Alex", "Bob", "Charlie", @@ -32,10 +34,15 @@ class GolombEncodingSpec extends WordSpec with MustMatchers { val key = SipHashKey.fromBtcutil(keyBytes) val golomb = GolombEncoding.default(key) - val encoded = golomb.encode(words.toSet) + val encoded = golomb.encode(words).value + + "succeed on empty set" in { + val result = golomb.encode(Set.empty) + result must be(empty) + } "decode the same hashes" in { - val hashes = golomb.hashes(words.toSet) + val hashes = golomb.hashes(words) val bytes = BaseEncoding .base16() .decode(encoded.hex.string.toUpperCase)