Skip to content

Instantly share code, notes, and snippets.

@djspiewak
Created August 13, 2014 16:02
Show Gist options
  • Save djspiewak/12af1a535d2a2c3bc722 to your computer and use it in GitHub Desktop.
Save djspiewak/12af1a535d2a2c3bc722 to your computer and use it in GitHub Desktop.
def optional[A](guard: Codec[Boolean], target: Codec[A]): Codec[Option[A]] =
either(guard, provide(()), target).xmap[Option[A]]({ _.toOption }, { _ map { \/-(_) } getOrElse -\/(()) })
def withDefault[A](opt: Codec[Option[A]], default: Codec[A]): Codec[A] = {
val paired = opt flatZip {
case Some(a) => provide(a)
case None => default
}
paired.xmap[A]({ _._2 }, { a => (Some(a), a) })
}
def recover(codec: Codec[Unit]): Codec[Boolean] = new Codec[Boolean] {
def encode(a: Boolean): String \/ BitVector = codec.encode(())
def decode(buffer: BitVector): String \/ (BitVector, Boolean) = {
codec.decode(buffer).toOption map {
case (rest, _) => \/-(rest, true)
} getOrElse \/-(buffer, false) // backtrack on failure
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment