Skip to content

Commit

Permalink
ConfCodec: implement as a pair, a-la ConfCodecExT
Browse files Browse the repository at this point in the history
  • Loading branch information
kitbellew committed Dec 9, 2024
1 parent b85f3f7 commit 186be3e
Showing 1 changed file with 16 additions and 8 deletions.
24 changes: 16 additions & 8 deletions metaconfig-core/shared/src/main/scala/metaconfig/ConfCodec.scala
Original file line number Diff line number Diff line change
@@ -1,21 +1,29 @@
package metaconfig

trait ConfCodec[A] extends ConfDecoder[A] with ConfEncoder[A] { self =>
def bimap[B](in: B => A, out: A => B): ConfCodec[B] = new ConfCodec[B] {
override def write(value: B): Conf = self.write(in(value))
override def read(conf: Conf): Configured[B] = self.read(conf).map(out)
}
def bimap[B](in: B => A, out: A => B): ConfCodec[B] =
new ConfCodec.Pair[B](encoder.contramap(in), decoder.map(out))

private[metaconfig] def decoder: ConfDecoder[A]
private[metaconfig] def encoder: ConfEncoder[A]

}

object ConfCodec {
def apply[A](implicit ev: ConfCodec[A]): ConfCodec[A] = ev

private[metaconfig] class Pair[A](
private[metaconfig] val encoder: ConfEncoder[A],
private[metaconfig] val decoder: ConfDecoder[A],
) extends ConfCodec[A] {
override def write(value: A): Conf = encoder.write(value)
override def read(conf: Conf): Configured[A] = decoder.read(conf)
}

implicit def EncoderDecoderToCodec[A](implicit
encode: ConfEncoder[A],
decode: ConfDecoder[A],
): ConfCodec[A] = new ConfCodec[A] {
override def write(value: A): Conf = encode.write(value)
override def read(conf: Conf): Configured[A] = decode.read(conf)
}
): ConfCodec[A] = new Pair(encode, decode)

val IntCodec: ConfCodec[Int] = ConfCodec[Int]
val StringCodec: ConfCodec[String] = ConfCodec[String]
Expand Down

0 comments on commit 186be3e

Please sign in to comment.