/
Decoder.scala
1571 lines (1408 loc) · 53.7 KB
/
Decoder.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2024 circe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.circe
import cats.ApplicativeError
import cats.Eval
import cats.MonadError
import cats.SemigroupK
import cats.data.Chain
import cats.data.Kleisli
import cats.data.NonEmptyChain
import cats.data.NonEmptyList
import cats.data.NonEmptyMap
import cats.data.NonEmptySet
import cats.data.NonEmptySeq
import cats.data.NonEmptyVector
import cats.data.StateT
import cats.data.Validated
import cats.data.Validated.Invalid
import cats.data.Validated.Valid
import cats.data.ValidatedNel
import cats.instances.either.catsStdInstancesForEither
import cats.instances.either.catsStdSemigroupKForEither
import cats.kernel.Order
import cats.syntax.either._
import io.circe.DecodingFailure.Reason.MissingField
import io.circe.DecodingFailure.Reason.WrongTypeExpectation
import io.circe.`export`.Exported
import java.io.Serializable
import java.net.URI
import java.net.URISyntaxException
import java.time.DateTimeException
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.Currency
import java.util.UUID
import scala.annotation.tailrec
import scala.collection.immutable.Set
import scala.collection.immutable.SortedMap
import scala.collection.immutable.SortedSet
import scala.collection.immutable.{ Map => ImmutableMap }
import scala.collection.mutable.Builder
import scala.util.Failure
import scala.util.Success
import scala.util.Try
/**
* A type class that provides a way to produce a value of type `A` from a [[Json]] value.
*/
trait Decoder[A] extends Serializable { self =>
/**
* Decode the given [[HCursor]].
*/
def apply(c: HCursor): Decoder.Result[A]
def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = apply(c) match {
case Right(a) => Validated.valid(a)
case Left(e) => Validated.invalidNel(e)
}
private[this] def cursorToDecodingFailure(cursor: ACursor): DecodingFailure = {
val reason: Eval[DecodingFailure.Reason] =
Eval.later(
cursor match {
case cursor: FailedCursor if cursor.missingField =>
DecodingFailure.Reason.MissingField
case _ =>
val field: String = cursor.pathString.replaceFirst("^\\.", "")
DecodingFailure.Reason.CustomReason(s"Couldn't decode $field")
}
)
DecodingFailure(reason, Some(cursor.pathToRoot), Eval.later(cursor.history))
}
/**
* Decode the given [[ACursor]].
*
* Note that if you override the default implementation, you should also be
* sure to override `tryDecodeAccumulating` in order for fail-fast and
* accumulating decoding to be consistent.
*/
def tryDecode(c: ACursor): Decoder.Result[A] = c match {
case hc: HCursor => apply(hc)
case _ =>
Left(cursorToDecodingFailure(c))
}
def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[A] = c match {
case hc: HCursor => decodeAccumulating(hc)
case _ =>
Validated.invalidNel(
cursorToDecodingFailure(c)
)
}
/**
* Decode the given [[Json]] value.
*/
final def decodeJson(j: Json): Decoder.Result[A] = apply(HCursor.fromJson(j))
/**
* Map a function over this [[Decoder]].
*/
final def map[B](f: A => B): Decoder[B] = new Decoder[B] {
final def apply(c: HCursor): Decoder.Result[B] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[B] = self.tryDecode(c) match {
case Right(a) => Right(f(a))
case l @ Left(_) => l.asInstanceOf[Decoder.Result[B]]
}
override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[B] =
tryDecodeAccumulating(c)
override final def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[B] =
self.tryDecodeAccumulating(c).map(f)
}
/**
* Monadically bind a function over this [[Decoder]].
*/
final def flatMap[B](f: A => Decoder[B]): Decoder[B] = new Decoder[B] {
final def apply(c: HCursor): Decoder.Result[B] = self(c) match {
case Right(a) => f(a)(c)
case l @ Left(_) => l.asInstanceOf[Decoder.Result[B]]
}
override def tryDecode(c: ACursor): Decoder.Result[B] = self.tryDecode(c) match {
case Right(a) => f(a).tryDecode(c)
case l @ Left(_) => l.asInstanceOf[Decoder.Result[B]]
}
override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[B] =
self.decodeAccumulating(c).andThen(result => f(result).decodeAccumulating(c))
override final def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[B] =
self.tryDecodeAccumulating(c).andThen(result => f(result).tryDecodeAccumulating(c))
}
/**
* Create a new instance that handles any of this instance's errors with the
* given function.
*
* Note that in the case of accumulating decoding, only the first error will
* be used in recovery.
*/
final def handleErrorWith(f: DecodingFailure => Decoder[A]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] = tryDecode(c)
override final def tryDecode(c: ACursor): Decoder.Result[A] =
Decoder.resultInstance.handleErrorWith(self.tryDecode(c))(failure => f(failure).tryDecode(c))
override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] =
tryDecodeAccumulating(c)
override final def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[A] =
Decoder.accumulatingResultInstance.handleErrorWith(self.tryDecodeAccumulating(c))(failures =>
f(failures.head).tryDecodeAccumulating(c)
)
}
/**
* Build a new instance with the specified error message.
*/
final def withErrorMessage(message: String): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] = self(c) match {
case r @ Right(_) => r
case Left(e) => Left(e.withMessage(message))
}
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] =
self.decodeAccumulating(c).leftMap(_.map(_.withMessage(message)))
}
/**
* Build a new instance that fails if the condition does not hold for the
* result.
*
* Note that in the case of chained calls to this method, only the first
* failure will be returned.
*/
final def ensure(pred: A => Boolean, message: => String): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] = self(c) match {
case r @ Right(a) => if (pred(a)) r else Left(DecodingFailure(message, c.history))
case l @ Left(_) => l
}
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = self.decodeAccumulating(c) match {
case v @ Valid(a) => if (pred(a)) v else Validated.invalidNel(DecodingFailure(message, c.history))
case i @ Invalid(_) => i
}
}
/**
* Build a new instance that fails with one or more errors if the condition
* does not hold for the result.
*
* If the result of the function applied to the decoded value is the empty
* list, the new decoder will succeed with that value.
*/
final def ensure(errors: A => List[String]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] = self(c) match {
case r @ Right(a) =>
errors(a) match {
case Nil => r
case message :: _ => Left(DecodingFailure(message, c.history))
}
case l @ Left(_) => l
}
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = self.decodeAccumulating(c) match {
case v @ Valid(a) =>
errors(a).map(DecodingFailure(_, c.history)) match {
case Nil => v
case h :: t => Validated.invalid(NonEmptyList(h, t))
}
case i @ Invalid(_) => i
}
}
/**
* Build a new instance that fails if the condition does not hold for the
* input.
*/
final def validate(errors: HCursor => List[String]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] =
errors(c).headOption.map { message =>
Left(DecodingFailure(message, c.history))
}.getOrElse(self(c))
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] = {
val underlyingResult = self.decodeAccumulating(c)
errors(c).map(DecodingFailure(_, c.history)) match {
case Nil =>
underlyingResult
case h :: t =>
val errorsNel = NonEmptyList(h, t)
Validated.invalid(underlyingResult.fold(errorsNel ::: _, _ => errorsNel))
}
}
}
/**
* Build a new instance that fails if the condition does not hold for the
* input.
*/
final def validate(pred: HCursor => Boolean, message: => String): Decoder[A] = validate { c =>
if (pred(c)) Nil
else message :: Nil
}
/**
* Convert to a Kleisli arrow.
*/
final def kleisli: Kleisli[Decoder.Result, HCursor, A] =
Kleisli[Decoder.Result, HCursor, A](apply(_))
/**
* Run two decoders and return their results as a pair.
*/
final def product[B](fb: Decoder[B]): Decoder[(A, B)] = new Decoder[(A, B)] {
final def apply(c: HCursor): Decoder.Result[(A, B)] = Decoder.resultInstance.product(self(c), fb(c))
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[(A, B)] =
Decoder.accumulatingResultInstance.product(self.decodeAccumulating(c), fb.decodeAccumulating(c))
}
/**
* Choose the first succeeding decoder.
*/
final def or[AA >: A](d: => Decoder[AA]): Decoder[AA] = new Decoder[AA] {
final def apply(c: HCursor): Decoder.Result[AA] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[AA] = self.tryDecode(c) match {
case r @ Right(_) => r
case Left(_) => d.tryDecode(c)
}
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[AA] =
tryDecodeAccumulating(c)
override def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[AA] =
self.tryDecodeAccumulating(c) match {
case r @ Valid(_) => r
case Invalid(_) => d.tryDecodeAccumulating(c)
}
}
/**
* Choose the first succeeding decoder, wrapping the result in a disjunction.
*/
final def either[B](decodeB: Decoder[B]): Decoder[Either[A, B]] = new Decoder[Either[A, B]] {
final def apply(c: HCursor): Decoder.Result[Either[A, B]] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[Either[A, B]] = self.tryDecode(c) match {
case Right(v) => Right(Left(v))
case Left(_) =>
decodeB.tryDecode(c) match {
case Right(v) => Right(Right(v))
case l @ Left(_) => l.asInstanceOf[Decoder.Result[Either[A, B]]]
}
}
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[Either[A, B]] = tryDecodeAccumulating(c)
override def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[Either[A, B]] =
self.tryDecodeAccumulating(c) match {
case Valid(v) => Valid(Left(v))
case Invalid(_) =>
decodeB.tryDecodeAccumulating(c) match {
case Valid(v) => Valid(Right(v))
case l @ Invalid(_) => l.asInstanceOf[Decoder.AccumulatingResult[Either[A, B]]]
}
}
}
/**
* Create a new decoder that performs some operation on the incoming JSON before decoding.
*/
final def prepare(f: ACursor => ACursor): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Decoder.Result[A] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[A] = self.tryDecode(f(c))
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] =
tryDecodeAccumulating(c)
override def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[A] =
self.tryDecodeAccumulating(f(c))
}
/**
* Create a new decoder that attempts to navigate to the specified field
* before decoding.
*/
final def at(field: String): Decoder[A] = new Decoder[A] {
private[this] val f: String = field
final def apply(c: HCursor): Decoder.Result[A] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[A] = self.tryDecode(c.downField(f))
override def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[A] =
tryDecodeAccumulating(c)
override def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[A] =
self.tryDecodeAccumulating(c.downField(f))
}
/**
* Create a new decoder that performs some operation on the result if this one succeeds.
*
* @param f a function returning either a value or an error message
*/
final def emap[B](f: A => Either[String, B]): Decoder[B] = new Decoder[B] {
final def apply(c: HCursor): Decoder.Result[B] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[B] =
self.tryDecode(c) match {
case Right(a) =>
f(a) match {
case r @ Right(_) => r.asInstanceOf[Decoder.Result[B]]
case Left(message) => Left(DecodingFailure(message, c.history))
}
case l @ Left(_) => l.asInstanceOf[Decoder.Result[B]]
}
override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[B] =
tryDecodeAccumulating(c)
override final def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[B] =
self.tryDecodeAccumulating(c) match {
case Valid(a) =>
f(a) match {
case Right(b) => Validated.valid(b)
case Left(message) => Validated.invalidNel(DecodingFailure(message, c.history))
}
case l @ Invalid(_) => l.asInstanceOf[Decoder.AccumulatingResult[B]]
}
}
/**
* Create a new decoder that performs some operation on the result if this one succeeds.
*
* @param f a function returning either a value or an error message
*/
final def emapTry[B](f: A => Try[B]): Decoder[B] = new Decoder[B] {
final def apply(c: HCursor): Decoder.Result[B] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[B] =
self.tryDecode(c) match {
case Right(a) =>
f(a) match {
case Success(b) => Right(b)
case Failure(t) => Left(DecodingFailure.fromThrowable(t, c.history))
}
case l @ Left(_) => l.asInstanceOf[Decoder.Result[B]]
}
override final def decodeAccumulating(c: HCursor): Decoder.AccumulatingResult[B] =
tryDecodeAccumulating(c)
override final def tryDecodeAccumulating(c: ACursor): Decoder.AccumulatingResult[B] =
self.tryDecodeAccumulating(c) match {
case Valid(a) =>
f(a) match {
case Success(b) => Validated.valid(b)
case Failure(t) => Validated.invalidNel(DecodingFailure.fromThrowable(t, c.history))
}
case l @ Invalid(_) => l.asInstanceOf[Decoder.AccumulatingResult[B]]
}
}
}
/**
* Utilities and instances for [[Decoder]].
*
* @groupname Aliases Type aliases
* @groupprio Aliases 0
*
* @groupname Utilities Defining decoders
* @groupprio Utilities 1
*
* @groupname Decoding General decoder instances
* @groupprio Decoding 2
*
* @groupname Collection Collection instances
* @groupprio Collection 3
*
* @groupname Disjunction Disjunction instances
* @groupdesc Disjunction Instance creation methods for disjunction-like types. Note that these
* instances are not implicit, since they require non-obvious decisions about the names of the
* discriminators. If you want instances for these types you can include the following import in
* your program:
* {{{
* import io.circe.disjunctionCodecs._
* }}}
* @groupprio Disjunction 4
*
* @groupname Instances Type class instances
* @groupprio Instances 5
*
* @groupname Tuple Tuple instances
* @groupprio Tuple 6
*
* @groupname Product Case class and other product instances
* @groupprio Product 7
*
* @groupname Time Java date and time instances
* @groupprio Time 8
*
* @groupname Literal Literal type instances
* @groupprio Literal 9
*
* @groupname Prioritization Instance prioritization
* @groupprio Prioritization 10
*
* @author Travis Brown
*/
object Decoder
extends DecoderDerivation
with CollectionDecoders
with TupleDecoders
with ProductDecoders
with LiteralDecoders
with EnumerationDecoders
with LowPriorityDecoders {
/**
* @group Aliases
*/
final type Result[A] = Either[DecodingFailure, A]
/**
* @group Aliases
*/
final type AccumulatingResult[A] = ValidatedNel[DecodingFailure, A]
/**
* @group Instances
*/
final val resultInstance: MonadError[Result, DecodingFailure] = catsStdInstancesForEither[DecodingFailure]
/**
* @group Instances
*/
final val accumulatingResultInstance: ApplicativeError[AccumulatingResult, NonEmptyList[DecodingFailure]] =
Validated.catsDataApplicativeErrorForValidated[NonEmptyList[DecodingFailure]](
NonEmptyList.catsDataSemigroupForNonEmptyList[DecodingFailure]
)
private[circe] val resultSemigroupK: SemigroupK[Result] = catsStdSemigroupKForEither[DecodingFailure]
private[this] abstract class DecoderWithFailure[A](name: String) extends Decoder[A] {
final def fail(c: HCursor): Result[A] = Left(DecodingFailure(name, c.history))
}
/**
* Return an instance for a given type.
*
* @group Utilities
*/
final def apply[A](implicit instance: Decoder[A]): Decoder[A] = instance
/**
* Create a decoder that always returns a single value, useful with some `flatMap` situations.
*
* @group Utilities
*/
final def const[A](a: A): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = Right(a)
final override def decodeAccumulating(c: HCursor): AccumulatingResult[A] =
Validated.valid(a)
}
/**
* Construct an instance from a function.
*
* @group Utilities
*/
final def instance[A](f: HCursor => Result[A]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = f(c)
}
/**
* Construct an instance from a [[cats.data.StateT]] value.
*
* @group Utilities
*/
def fromState[A](s: StateT[Result, ACursor, A]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = s.runA(c)
}
/**
* This is for easier interop with code that already returns [[scala.util.Try]]. You should
* prefer `instance` for any new code.
*
* @group Utilities
*/
final def instanceTry[A](f: HCursor => Try[A]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = f(c) match {
case Success(a) => Right(a)
case Failure(t) => Left(DecodingFailure.fromThrowable(t, c.history))
}
}
/**
* Construct an instance from a function that may reattempt on failure.
*
* @group Utilities
*/
final def withReattempt[A](f: ACursor => Result[A]): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = tryDecode(c)
override def tryDecode(c: ACursor): Decoder.Result[A] = f(c)
override def decodeAccumulating(c: HCursor): AccumulatingResult[A] = tryDecodeAccumulating(c)
override def tryDecodeAccumulating(c: ACursor): AccumulatingResult[A] = f(c) match {
case Right(v) => Validated.valid(v)
case Left(e) => Validated.invalidNel(e)
}
}
/**
* Construct an instance that always fails with the given [[DecodingFailure]].
*
* @group Utilities
*/
final def failed[A](failure: DecodingFailure): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = Left(failure)
override final def decodeAccumulating(c: HCursor): AccumulatingResult[A] =
Validated.invalidNel(failure)
}
/**
* Construct an instance that always fails with the given error message.
*
* @group Utilities
*/
final def failedWithMessage[A](message: String): Decoder[A] = new Decoder[A] {
final def apply(c: HCursor): Result[A] = Left(DecodingFailure(message, c.history))
override final def decodeAccumulating(c: HCursor): AccumulatingResult[A] =
Validated.invalidNel(DecodingFailure(message, c.history))
}
/**
* @group Decoding
*/
implicit final val decodeHCursor: Decoder[HCursor] = new Decoder[HCursor] {
final def apply(c: HCursor): Result[HCursor] = Right(c)
}
/**
* @group Decoding
*/
implicit final val decodeJson: Decoder[Json] = new Decoder[Json] {
final def apply(c: HCursor): Result[Json] = Right(c.value)
}
/**
* @group Decoding
*/
implicit final val decodeJsonObject: Decoder[JsonObject] = new Decoder[JsonObject] {
final def apply(c: HCursor): Result[JsonObject] = c.value.asObject match {
case Some(v) => Right(v)
case None => Left(DecodingFailure(WrongTypeExpectation("object", c.value), c.history))
}
}
/**
* @group Decoding
*/
implicit final val decodeJsonNumber: Decoder[JsonNumber] = new Decoder[JsonNumber] {
final def apply(c: HCursor): Result[JsonNumber] = c.value.asNumber match {
case Some(v) => Right(v)
case None => Left(DecodingFailure(WrongTypeExpectation("number", c.value), c.history))
}
}
/**
* @group Decoding
*/
implicit final val decodeString: Decoder[String] = new Decoder[String] {
final def apply(c: HCursor): Result[String] = c.value match {
case Json.JString(string) => Right(string)
case json => Left(DecodingFailure(WrongTypeExpectation("string", json), c.history))
}
}
/**
* @group Decoding
*/
implicit final val decodeUnit: Decoder[Unit] = new Decoder[Unit] {
final def apply(c: HCursor): Result[Unit] = c.value match {
case Json.JObject(obj) if obj.isEmpty => Right(())
case Json.JArray(arr) if arr.isEmpty => Right(())
case other if other.isNull => Right(())
case json =>
Left(DecodingFailure(WrongTypeExpectation("'null' or '[]' or '{}'", json), c.history))
}
}
/**
* @group Decoding
*/
implicit final val decodeBoolean: Decoder[Boolean] = new Decoder[Boolean] {
final def apply(c: HCursor): Result[Boolean] = c.value match {
case Json.JBoolean(b) => Right(b)
case json =>
Left(DecodingFailure(WrongTypeExpectation("'true' or 'false'", json), c.history))
}
}
/**
* Decode a JSON value into a `java.lang.Boolean`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaBoolean: Decoder[java.lang.Boolean] = decodeBoolean.map(java.lang.Boolean.valueOf)
/**
* @group Decoding
*/
implicit final val decodeChar: Decoder[Char] = new Decoder[Char] {
final def apply(c: HCursor): Result[Char] = c.value match {
case Json.JString(string) if string.length == 1 => Right(string.charAt(0))
case json =>
Left(DecodingFailure(WrongTypeExpectation("character", json), c.history))
}
}
/**
* Decode a JSON value into a `java.lang.Character`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaCharacter: Decoder[java.lang.Character] =
decodeChar.map(java.lang.Character.valueOf)
/**
* Decode a JSON value into a [[scala.Float]].
*
* See [[decodeDouble]] for discussion of the approach taken for floating-point decoding.
*
* @group Decoding
*/
implicit final val decodeFloat: Decoder[Float] = new DecoderWithFailure[Float]("Float") {
final def apply(c: HCursor): Result[Float] = c.value match {
case Json.JNumber(number) => Right(number.toFloat)
case Json.JString(string) =>
JsonNumber.fromString(string).map(_.toFloat) match {
case Some(v) => Right(v)
case None => fail(c)
}
case other if other.isNull => Right(Float.NaN)
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Float`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaFloat: Decoder[java.lang.Float] = decodeFloat.map(java.lang.Float.valueOf)
/**
* Decode a JSON value into a [[scala.Double]].
*
* Unlike the integral decoders provided here, this decoder will accept values that are too large
* to be represented and will return them as `PositiveInfinity` or `NegativeInfinity`, and it may
* lose precision.
*
* @group Decoding
*/
implicit final val decodeDouble: Decoder[Double] = new DecoderWithFailure[Double]("Double") {
final def apply(c: HCursor): Result[Double] = c.value match {
case Json.JNumber(number) => Right(number.toDouble)
case Json.JString(string) =>
JsonNumber.fromString(string).map(_.toDouble) match {
case Some(v) => Right(v)
case None => fail(c)
}
case other if other.isNull => Right(Double.NaN)
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Double`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaDouble: Decoder[java.lang.Double] = decodeDouble.map(java.lang.Double.valueOf)
/**
* Decode a JSON value into a [[scala.Byte]].
*
* See [[decodeLong]] for discussion of the approach taken for integral decoding.
*
* @group Decoding
*/
implicit final val decodeByte: Decoder[Byte] = new DecoderWithFailure[Byte]("Byte") {
final def apply(c: HCursor): Result[Byte] = c.value match {
case Json.JNumber(number) =>
number.toByte match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toByte) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Byte`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaByte: Decoder[java.lang.Byte] = decodeByte.map(java.lang.Byte.valueOf)
/**
* Decode a JSON value into a [[scala.Short]].
*
* See [[decodeLong]] for discussion of the approach taken for integral decoding.
*
* @group Decoding
*/
implicit final val decodeShort: Decoder[Short] = new DecoderWithFailure[Short]("Short") {
final def apply(c: HCursor): Result[Short] = c.value match {
case Json.JNumber(number) =>
number.toShort match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toShort) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Short`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaShort: Decoder[java.lang.Short] = decodeShort.map(java.lang.Short.valueOf)
/**
* Decode a JSON value into a [[scala.Int]].
*
* See [[decodeLong]] for discussion of the approach taken for integral decoding.
*
* @group Decoding
*/
implicit final val decodeInt: Decoder[Int] = new DecoderWithFailure[Int]("Int") {
final def apply(c: HCursor): Result[Int] = c.value match {
case Json.JNumber(number) =>
number.toInt match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toInt) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Integer`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaInteger: Decoder[java.lang.Integer] = decodeInt.map(java.lang.Integer.valueOf)
/**
* Decode a JSON value into a [[scala.Long]].
*
* Decoding will fail if the value doesn't represent a whole number within the range of the target
* type (although it can have a decimal part: e.g. `10.0` will be successfully decoded, but
* `10.01` will not). If the value is a JSON string, the decoder will attempt to parse it as a
* number.
*
* @group Decoding
*/
implicit final val decodeLong: Decoder[Long] = new DecoderWithFailure[Long]("Long") {
final def apply(c: HCursor): Result[Long] = c.value match {
case Json.JNumber(number) =>
number.toLong match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toLong) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.lang.Long`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaLong: Decoder[java.lang.Long] = decodeLong.map(java.lang.Long.valueOf)
/**
* Decode a JSON value into a [[scala.math.BigInt]].
*
* Note that decoding will fail if the number has a large number of digits (the limit is currently
* `1 << 18`, or around a quarter million). Larger numbers can be decoded by mapping over a
* [[scala.math.BigDecimal]], but be aware that the conversion to the integral form can be
* computationally expensive.
*
* @group Decoding
*/
implicit final val decodeBigInt: Decoder[BigInt] = new DecoderWithFailure[BigInt]("BigInt") {
final def apply(c: HCursor): Result[BigInt] = c.value match {
case Json.JNumber(number) =>
number.toBigInt match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toBigInt) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.math.BigInteger`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaBigInteger: Decoder[java.math.BigInteger] = decodeBigInt.map(_.bigInteger)
/**
* Decode a JSON value into a [[scala.math.BigDecimal]].
*
* Note that decoding will fail on some very large values that could in principle be represented
* as `BigDecimal`s (specifically if the `scale` is out of the range of `scala.Int` when the
* `unscaledValue` is adjusted to have no trailing zeros). These large values can, however, be
* round-tripped through `JsonNumber`, so you may wish to use [[decodeJsonNumber]] in these cases.
*
* Also note that because `scala.scalajs.js.JSON` parses JSON numbers into a floating point
* representation, decoding a JSON number into a `BigDecimal` on Scala.js may lose precision.
*
* @group Decoding
*/
implicit final val decodeBigDecimal: Decoder[BigDecimal] = new DecoderWithFailure[BigDecimal]("BigDecimal") {
final def apply(c: HCursor): Result[BigDecimal] = c.value match {
case Json.JNumber(number) =>
number.toBigDecimal match {
case Some(v) => Right(v)
case None => fail(c)
}
case Json.JString(string) =>
JsonNumber.fromString(string).flatMap(_.toBigDecimal) match {
case Some(value) => Right(value)
case None => fail(c)
}
case _ => fail(c)
}
}
/**
* Decode a JSON value into a `java.math.BigDecimal`.
*
* @group Decoding
*/
implicit final lazy val decodeJavaBigDecimal: Decoder[java.math.BigDecimal] = decodeBigDecimal.map(_.bigDecimal)
/**
* @group Decoding
*/
implicit final lazy val decodeUUID: Decoder[UUID] = new Decoder[UUID] {
final def apply(c: HCursor): Result[UUID] = c.value match {
case Json.JString(string) if string.length == 36 =>
try Right(UUID.fromString(string))
catch {
case _: IllegalArgumentException =>
Left(DecodingFailure("Couldn't decode a valid UUID", c.history))
}
case json => Left(DecodingFailure(WrongTypeExpectation("string", json), c.history))
}
}
/**
* @group Decoding
*/
implicit final lazy val decodeURI: Decoder[URI] = new Decoder[URI] {
final def apply(c: HCursor): Result[URI] = c.value match {
case Json.JString(string) =>
try Right(new URI(string))
catch {
case _: URISyntaxException =>
Left(DecodingFailure("String could not be parsed as a URI reference, it violates RFC 2396.", c.history))
case _: NullPointerException =>
Left(DecodingFailure("String is null.", c.history))
}
case json => Left(DecodingFailure(WrongTypeExpectation("string", json), c.history))
}
}
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[None.type] = Right(None)
private[circe] final val keyMissingNoneAccumulating: AccumulatingResult[None.type] =
Validated.valid(None)
/**
* A decoder for `Option[A]`.
*
* This is modeled as a separate, named, subtype because Option decoders
* often have special semantics around the handling of `JNull`. By having
* this as a named subtype, we premit certain optimizations that would
* otherwise not be possible. See `circe-generic-extras` for some examples.
*/
final class OptionDecoder[A](implicit A: Decoder[A]) extends Decoder[Option[A]] {
final override def apply(c: HCursor): Result[Option[A]] = tryDecode(c)
final override def tryDecode(c: ACursor): Decoder.Result[Option[A]] = c match {
case c: HCursor =>
if (c.value.isNull) rightNone
else
A(c) match {
case Right(a) => Right(Some(a))
case Left(df) => Left(df)
}