Skip to content

Commit

Permalink
Fix Decoder[None.type] (#1726)
Browse files Browse the repository at this point in the history
  • Loading branch information
nigredo-tori committed Apr 20, 2021
1 parent 1ae596b commit c8e7733
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
24 changes: 20 additions & 4 deletions modules/core/shared/src/main/scala/io/circe/Decoder.scala
Expand Up @@ -910,11 +910,11 @@ object Decoder
}
}

private[this] final val rightNone: Either[DecodingFailure, Option[Nothing]] = Right(None)
private[this] final val validNone: ValidatedNel[DecodingFailure, Option[Nothing]] = Validated.valid(None)
private[this] final val rightNone: Either[DecodingFailure, None.type] = Right(None)
private[this] final val validNone: ValidatedNel[DecodingFailure, None.type] = Validated.valid(None)

private[circe] final val keyMissingNone: Decoder.Result[Option[Nothing]] = Right(None)
private[circe] final val keyMissingNoneAccumulating: AccumulatingResult[Option[Nothing]] =
private[circe] final val keyMissingNone: Decoder.Result[None.type] = Right(None)
private[circe] final val keyMissingNoneAccumulating: AccumulatingResult[None.type] =
Validated.valid(None)

/**
Expand Down Expand Up @@ -964,6 +964,22 @@ object Decoder
else {
Left(DecodingFailure("None", c.history))
}
final override def tryDecode(c: ACursor): Decoder.Result[None.type] = c match {
case c: HCursor =>
if (c.value.isNull) rightNone
else Left(DecodingFailure("None", c.history))
case c: FailedCursor =>
if (!c.incorrectFocus) keyMissingNone else Left(DecodingFailure("None", c.history))
}

final override def tryDecodeAccumulating(c: ACursor): AccumulatingResult[None.type] = c match {
case c: HCursor =>
if (c.value.isNull) validNone
else Validated.invalidNel(DecodingFailure("None", c.history))
case c: FailedCursor =>
if (!c.incorrectFocus) keyMissingNoneAccumulating
else Validated.invalidNel(DecodingFailure("None", c.history))
}
}

/**
Expand Down
10 changes: 10 additions & 0 deletions modules/tests/shared/src/test/scala/io/circe/CodecSuites.scala
Expand Up @@ -157,6 +157,16 @@ class StdLibCodecSuite extends CirceMunitSuite with ArrayFactoryInstance {

assert(result.isLeft)
}

test("None.type decoder should succeed for missing fields") {
val n = Json.obj()
val decoder = Decoder[None.type].at("foo")

val result1 = decoder.decodeJson(n)
assert(result1.isRight)
val result2 = decoder.decodeAccumulating(HCursor.fromJson(n))
assert(result2.isValid)
}
}

class CatsCodecSuite extends CirceMunitSuite with StreamFactoryInstance {
Expand Down

0 comments on commit c8e7733

Please sign in to comment.