Browse Source

server: Handle empty set on GolombEncoding

master
Alexis Hernandez 6 years ago
parent
commit
8e203c9fb6
  1. 13
      server/app/com/xsn/explorer/gcs/GolombEncoding.scala
  2. 17
      server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala

13
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) 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 sortedHashes = hashes(words)
val diffList = differences(sortedHashes) val diffList = differences(sortedHashes)
val encodedBits = diffList.flatMap(golombEncode) val encodedBits = diffList.flatMap(golombEncode)

17
server/test/com/xsn/explorer/gcs/GolombEncodingSpec.scala

@ -1,11 +1,13 @@
package com.xsn.explorer.gcs package com.xsn.explorer.gcs
import com.google.common.io.BaseEncoding 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", "Alex",
"Bob", "Bob",
"Charlie", "Charlie",
@ -32,10 +34,15 @@ class GolombEncodingSpec extends WordSpec with MustMatchers {
val key = SipHashKey.fromBtcutil(keyBytes) val key = SipHashKey.fromBtcutil(keyBytes)
val golomb = GolombEncoding.default(key) 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 { "decode the same hashes" in {
val hashes = golomb.hashes(words.toSet) val hashes = golomb.hashes(words)
val bytes = BaseEncoding val bytes = BaseEncoding
.base16() .base16()
.decode(encoded.hex.string.toUpperCase) .decode(encoded.hex.string.toUpperCase)

Loading…
Cancel
Save