-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add circe enumeration convenience methods
- Loading branch information
Showing
2 changed files
with
53 additions
and
5 deletions.
There are no files selected for viewing
20 changes: 18 additions & 2 deletions
20
modules/circe/src/main/scala/io/taig/enumeration/ext/circe.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,17 +1,33 @@ | ||
package io.taig.enumeration.ext | ||
|
||
import cats.Show | ||
import cats.{Hash, Show} | ||
import cats.syntax.all.* | ||
import io.circe.{Decoder, Encoder} | ||
import io.circe.{Codec, Decoder, Encoder} | ||
|
||
trait circe: | ||
|
||
implicit def decodeMapping[A, B](using mapping: Mapping[A, B], decoder: Decoder[B])(using Show[B]): Decoder[A] = | ||
decoder.emap: b => | ||
mapping | ||
.prj(b) | ||
.toRight(s"Couldn't decode value '$b.' Allowed values: '${mapping.values.map(mapping.inj).mkString(",")}'") | ||
|
||
def decoderEnumeration[A, B: Show: Hash]( | ||
f: A => B | ||
)(using EnumerationValues.Aux[A, A])(using decoder: Decoder[B]): Decoder[A] = | ||
decodeMapping(using Mapping.enumeration(f), decoder) | ||
|
||
implicit def encodeMapping[A, B](using mapping: Mapping[A, B], encoder: Encoder[B]): Encoder[A] = | ||
encoder.contramap(mapping.inj) | ||
|
||
def encoderEnumeration[A, B: Hash]( | ||
f: A => B | ||
)(using EnumerationValues.Aux[A, A])(using encoder: Encoder[B]): Encoder[A] = | ||
encodeMapping(using Mapping.enumeration(f), encoder) | ||
|
||
def codecEnumeration[A, B: Show: Hash]( | ||
f: A => B | ||
)(using EnumerationValues.Aux[A, A], Decoder[B], Encoder[B]): Codec[A] = | ||
Codec.from(decoderEnumeration(f), encoderEnumeration(f)) | ||
|
||
object circe extends circe |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters