/
dynamic.gleam
1289 lines (1213 loc) Β· 30.6 KB
/
dynamic.gleam
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
import gleam/bit_string
import gleam/list
import gleam/map
import gleam/int
import gleam/option
import gleam/result
import gleam/string_builder
import gleam/map.{Map}
import gleam/option.{Option}
/// `Dynamic` data is data that we don't know the type of yet.
/// We likely get data like this from interop with Erlang, or from
/// IO with the outside world.
pub external type Dynamic
/// Error returned when unexpected data is encountered
pub type DecodeError {
DecodeError(expected: String, found: String, path: List(String))
}
pub type DecodeErrors =
List(DecodeError)
pub type Decoder(t) =
fn(Dynamic) -> Result(t, DecodeErrors)
/// Converts any Gleam data into `Dynamic` data.
///
pub fn from(a) -> Dynamic {
do_from(a)
}
if erlang {
external fn do_from(anything) -> Dynamic =
"gleam_stdlib" "identity"
}
if javascript {
external fn do_from(anything) -> Dynamic =
"../gleam_stdlib.mjs" "identity"
}
/// Unsafely casts a Dynamic value into any other type.
///
/// This is an escape hatch for the type system that may be useful when wrapping
/// native Erlang APIs. It is to be used as a last measure only!
///
/// If you can avoid using this function, do!
///
pub fn unsafe_coerce(a: Dynamic) -> anything {
do_unsafe_coerce(a)
}
if erlang {
external fn do_unsafe_coerce(Dynamic) -> a =
"gleam_stdlib" "identity"
}
if javascript {
external fn do_unsafe_coerce(Dynamic) -> a =
"../gleam_stdlib.mjs" "identity"
}
/// Decodes a `Dynamic` value from a `Dynamic` value.
///
/// This function doesn't seem very useful at first, but it can be convenient
/// when you need to give a decoder function but you don't actually care what
/// the to-decode value is.
///
pub fn dynamic() -> Decoder(Dynamic) {
Ok
}
/// Checks to see whether a `Dynamic` value is a bit_string, and returns that bit string if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// > bit_string(from("Hello")) == bit_string.from_string("Hello")
/// True
///
/// > bit_string(from(123))
/// Error([DecodeError(expected: "BitString", found: "Int", path: [])])
/// ```
///
pub fn bit_string(from data: Dynamic) -> Result(BitString, DecodeErrors) {
decode_bit_string(data)
}
if erlang {
external fn decode_bit_string(Dynamic) -> Result(BitString, DecodeErrors) =
"gleam_stdlib" "decode_bit_string"
}
if javascript {
external fn decode_bit_string(Dynamic) -> Result(BitString, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_bit_string"
}
/// Checks to see whether a `Dynamic` value is a string, and returns that string if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// > string(from("Hello"))
/// Ok("Hello")
///
/// > string(from(123))
/// Error([DecodeError(expected: "String", found: "Int", path: [])])
/// ```
///
pub fn string(from data: Dynamic) -> Result(String, DecodeErrors) {
decode_string(data)
}
fn map_errors(
result: Result(t, DecodeErrors),
f: fn(DecodeError) -> DecodeError,
) -> Result(t, DecodeErrors) {
result.map_error(result, list.map(_, f))
}
if erlang {
fn decode_string(data: Dynamic) -> Result(String, DecodeErrors) {
bit_string(data)
|> map_errors(put_expected(_, "String"))
|> result.then(fn(raw) {
case bit_string.to_string(raw) {
Ok(string) -> Ok(string)
Error(Nil) ->
Error([DecodeError(expected: "String", found: "BitString", path: [])])
}
})
}
}
if javascript {
external fn decode_string(Dynamic) -> Result(String, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_string"
}
/// Return a string indicating the type of the dynamic value.
///
/// ```gleam
/// > classify(from("Hello"))
/// "String"
/// ```
///
pub fn classify(data: Dynamic) -> String {
do_classify(data)
}
if erlang {
external fn do_classify(Dynamic) -> String =
"gleam_stdlib" "classify_dynamic"
}
if javascript {
external fn do_classify(Dynamic) -> String =
"../gleam_stdlib.mjs" "classify_dynamic"
}
/// Checks to see whether a `Dynamic` value is an int, and returns that int if it
/// is.
///
/// ## Examples
///
/// ```gleam
/// > int(from(123))
/// Ok(123)
///
/// > int(from("Hello"))
/// Error([DecodeError(expected: "Int", found: "String", path: [])])
/// ```
///
pub fn int(from data: Dynamic) -> Result(Int, DecodeErrors) {
decode_int(data)
}
if erlang {
external fn decode_int(Dynamic) -> Result(Int, DecodeErrors) =
"gleam_stdlib" "decode_int"
}
if javascript {
external fn decode_int(Dynamic) -> Result(Int, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_int"
}
/// Checks to see whether a `Dynamic` value is a float, and returns that float if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// > float(from(2.0))
/// Ok(2.0)
///
/// > float(from(123))
/// Error([DecodeError(expected: "Float", found: "Int", path: [])])
/// ```
///
pub fn float(from data: Dynamic) -> Result(Float, DecodeErrors) {
decode_float(data)
}
if erlang {
external fn decode_float(Dynamic) -> Result(Float, DecodeErrors) =
"gleam_stdlib" "decode_float"
}
if javascript {
external fn decode_float(Dynamic) -> Result(Float, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_float"
}
/// Checks to see whether a `Dynamic` value is a bool, and returns that bool if
/// it is.
///
/// ## Examples
///
/// ```gleam
/// > bool(from(True))
/// Ok(True)
///
/// > bool(from(123))
/// Error([DecodeError(expected: "bool", found: "Int", path: [])])
/// ```
///
pub fn bool(from data: Dynamic) -> Result(Bool, DecodeErrors) {
decode_bool(data)
}
if erlang {
external fn decode_bool(Dynamic) -> Result(Bool, DecodeErrors) =
"gleam_stdlib" "decode_bool"
}
if javascript {
external fn decode_bool(Dynamic) -> Result(Bool, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_bool"
}
/// Checks to see whether a `Dynamic` value is a list, and returns that list if it
/// is. The types of the elements are not checked.
///
/// If you wish to decode all the elements in the list use the `list`
/// instead.
///
/// ## Examples
///
/// ```gleam
/// > shallow_list(from(["a", "b", "c"]))
/// Ok([from("a"), from("b"), from("c")])
///
/// > shallow_list(1)
/// Error([DecodeError(expected: "Int", found: "Int", path: [])])
/// ```
///
pub fn shallow_list(from value: Dynamic) -> Result(List(Dynamic), DecodeErrors) {
decode_list(value)
}
if erlang {
external fn decode_list(Dynamic) -> Result(List(Dynamic), DecodeErrors) =
"gleam_stdlib" "decode_list"
}
if javascript {
external fn decode_list(Dynamic) -> Result(List(Dynamic), DecodeErrors) =
"../gleam_stdlib.mjs" "decode_list"
}
if erlang {
external fn decode_result(Dynamic) -> Result(Result(a, e), DecodeErrors) =
"gleam_stdlib" "decode_result"
}
if javascript {
external fn decode_result(Dynamic) -> Result(Result(a, e), DecodeErrors) =
"../gleam_stdlib.mjs" "decode_result"
}
/// Checks to see whether a `Dynamic` value is a result of a particular type, and
/// returns that result if it is.
///
/// The `ok` and `error` arguments are decoders for decoding the `Ok` and
/// `Error` values of the result.
///
/// ## Examples
///
/// ```gleam
/// > from(Ok(1))
/// > |> result(ok: int, error: string)
/// Ok(Ok(1))
///
/// > from(Error("boom"))
/// > |> result(ok: int, error: string)
/// Ok(Error("boom"))
///
/// > from(123)
/// > |> result(ok: int, error: string)
/// Error([DecodeError(expected: "2 element tuple", found: "Int", path: [])])
/// ```
///
pub fn result(
ok decode_ok: Decoder(a),
error decode_error: Decoder(e),
) -> Decoder(Result(a, e)) {
fn(value) {
try inner_result = decode_result(value)
case inner_result {
Ok(raw) -> {
try value =
decode_ok(raw)
|> map_errors(push_path(_, "ok"))
Ok(Ok(value))
}
Error(raw) -> {
try value =
decode_error(raw)
|> map_errors(push_path(_, "error"))
Ok(Error(value))
}
}
}
}
/// Checks to see whether a `Dynamic` value is a list of a particular type, and
/// returns that list if it is.
///
/// The second argument is a decoder function used to decode the elements of
/// the list. The list is only decoded if all elements in the list can be
/// successfully decoded using this function.
///
/// If you do not wish to decode all the elements in the list use the `list`
/// function instead.
///
/// ## Examples
///
/// ```gleam
/// > from(["a", "b", "c"])
/// > |> list(of: string)
/// Ok(["a", "b", "c"])
///
/// > from([1, 2, 3])
/// > |> list(of: string)
/// Error([DecodeError(expected: "String", found: "Int", path: [])])
///
/// > from("ok")
/// > |> list(of: string)
/// Error([DecodeError(expected: "List", found: "String", path: [])])
/// ```
///
pub fn list(
of decoder_type: fn(Dynamic) -> Result(inner, DecodeErrors),
) -> Decoder(List(inner)) {
fn(dynamic) {
try list = shallow_list(dynamic)
list
|> list.try_map(decoder_type)
|> map_errors(push_path(_, "*"))
}
}
/// Checks to see if a `Dynamic` value is a nullable version of a particular
/// type, and returns a corresponding `Option` if it is.
///
/// ## Examples
///
/// ```gleam
/// > from("Hello")
/// > |> option(string)
/// Ok(Some("Hello"))
///
/// > from("Hello")
/// > |> option(string)
/// Ok(Some("Hello"))
///
/// > from(atom.from_string("null"))
/// > |> option(string)
/// Ok(None)
///
/// > from(atom.from_string("nil"))
/// > |> option(string)
/// Ok(None)
///
/// > from(atom.from_string("undefined"))
/// > |> option(string)
/// Ok(None)
///
/// > from(123)
/// > |> option(string)
/// Error([DecodeError(expected: "BitString", found: "Int", path: [])])
/// ```gleam
///
pub fn optional(of decode: Decoder(inner)) -> Decoder(Option(inner)) {
fn(value) { decode_optional(value, decode) }
}
if erlang {
external fn decode_optional(
Dynamic,
Decoder(a),
) -> Result(Option(a), DecodeErrors) =
"gleam_stdlib" "decode_option"
}
if javascript {
external fn decode_optional(
Dynamic,
Decoder(a),
) -> Result(Option(a), DecodeErrors) =
"../gleam_stdlib.mjs" "decode_option"
}
/// Checks to see if a `Dynamic` value is a map with a specific field, and returns
/// the value of that field if it is.
///
/// This will not succeed on a record.
///
/// ## Examples
///
/// ```gleam
/// > import gleam/map
/// > from(map.new("Hello", "World"))
/// > |> field(named: "Hello", of: string)
/// Ok("World")
///
/// > from(123)
/// > |> field("Hello", string)
/// Error([DecodeError(expected: "Map", found: "Int", path: [])])
/// ```
///
pub fn field(named name: a, of inner_type: Decoder(t)) -> Decoder(t) {
fn(value) {
try value = decode_field(value, name)
inner_type(value)
|> map_errors(push_path(_, name))
}
}
if erlang {
external fn decode_field(Dynamic, name) -> Result(Dynamic, DecodeErrors) =
"gleam_stdlib" "decode_field"
}
if javascript {
external fn decode_field(Dynamic, name) -> Result(Dynamic, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_field"
}
/// Checks to see if a `Dynamic` value is a tuple large enough to have a certain
/// index, and returns the value of that index if it is.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2))
/// > |> element(0, int)
/// Ok(from(1))
/// ```
///
/// ```gleam
/// > from(#(1, 2))
/// > |> element(2, int)
/// Error([
/// DecodeError(
/// expected: "Tuple of at least 3 elements",
/// found: "Tuple of 2 elements",
/// path: [],
/// ),
/// ])
/// ```
///
pub fn element(at index: Int, of inner_type: Decoder(t)) -> Decoder(t) {
fn(data: Dynamic) {
try tuple = decode_tuple(data)
let size = tuple_size(tuple)
try data = case index >= 0 {
True ->
case index < size {
True -> tuple_get(tuple, index)
False -> at_least_decode_tuple_error(index + 1, data)
}
False ->
case int.absolute_value(index) <= size {
True -> tuple_get(tuple, size + index)
False -> at_least_decode_tuple_error(int.absolute_value(index), data)
}
}
inner_type(data)
|> map_errors(push_path(_, index))
}
}
fn exact_decode_tuple_error(size: Int, data: Dynamic) -> Result(a, DecodeErrors) {
let s = case size {
0 -> ""
_ -> "s"
}
let error =
["Tuple of ", int.to_string(size), " element", s]
|> string_builder.from_strings
|> string_builder.to_string
|> DecodeError(found: classify(data), path: [])
Error([error])
}
fn at_least_decode_tuple_error(
size: Int,
data: Dynamic,
) -> Result(a, DecodeErrors) {
let s = case size {
0 -> ""
_ -> "s"
}
let error =
["Tuple of at least ", int.to_string(size), " element", s]
|> string_builder.from_strings
|> string_builder.to_string
|> DecodeError(found: classify(data), path: [])
Error([error])
}
// A tuple of unknown size
external type UnknownTuple
if erlang {
external fn decode_tuple(Dynamic) -> Result(UnknownTuple, DecodeErrors) =
"gleam_stdlib" "decode_tuple"
external fn tuple_get(UnknownTuple, Int) -> Result(Dynamic, DecodeErrors) =
"gleam_stdlib" "tuple_get"
external fn tuple_size(UnknownTuple) -> Int =
"gleam_stdlib" "size_of_tuple"
}
if javascript {
external fn decode_tuple(Dynamic) -> Result(UnknownTuple, DecodeErrors) =
"../gleam_stdlib.mjs" "decode_tuple"
external fn tuple_get(UnknownTuple, Int) -> Result(Dynamic, DecodeErrors) =
"../gleam_stdlib.mjs" "tuple_get"
external fn tuple_size(UnknownTuple) -> Int =
"../gleam_stdlib.mjs" "length"
}
fn tuple_errors(
result: Result(a, List(DecodeError)),
name: String,
) -> List(DecodeError) {
case result {
Ok(_) -> []
Error(errors) -> list.map(errors, push_path(_, name))
}
}
fn assert_is_tuple(
value: Dynamic,
desired_size: Int,
) -> Result(Nil, DecodeErrors) {
let expected =
string_builder.to_string(string_builder.from_strings([
"Tuple of ",
int.to_string(desired_size),
" elements",
]))
try tuple = map_errors(decode_tuple(value), put_expected(_, expected))
case tuple_size(tuple) {
size if size == desired_size -> Ok(Nil)
_ -> exact_decode_tuple_error(desired_size, value)
}
}
fn put_expected(error: DecodeError, expected: String) -> DecodeError {
DecodeError(..error, expected: expected)
}
fn push_path(error: DecodeError, name: t) -> DecodeError {
let name = from(name)
let decoder = any([string, fn(x) { result.map(int(x), int.to_string) }])
let name = case decoder(name) {
Ok(name) -> name
Error(_) ->
["<", classify(name), ">"]
|> string_builder.from_strings
|> string_builder.to_string
}
DecodeError(..error, path: [name, ..error.path])
}
/// Checks to see if a `Dynamic` value is a 2 element tuple containing
/// specifically typed elements.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2))
/// > |> tuple2(int, int)
/// Ok(#(1, 2))
///
/// > from(#(1, 2.0))
/// > |> tuple2(int, float)
/// Ok(#(1, 2.0))
///
/// > from(#(1, 2, 3))
/// > |> tuple2(int, float)
/// Error([
/// DecodeError(expected: "2 element tuple", found: "3 element tuple", path: []),
/// ])
///
/// > from("")
/// > |> tuple2(int, float)
/// Error([DecodeError(expected: "2 element tuple", found: "String", path: [])])
/// ```
///
pub fn tuple2(
first decode1: Decoder(a),
second decode2: Decoder(b),
) -> Decoder(#(a, b)) {
fn(value) {
try _ = assert_is_tuple(value, 2)
let #(a, b) = unsafe_coerce(value)
case decode1(a), decode2(b) {
Ok(a), Ok(b) -> Ok(#(a, b))
a, b ->
tuple_errors(a, "0")
|> list.append(tuple_errors(b, "1"))
|> Error
}
}
}
/// Checks to see if a `Dynamic` value is a 3-element tuple containing
/// specifically typed elements.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2, 3))
/// > |> tuple3(int, int, int)
/// Ok(#(1, 2, 3))
///
/// > from(#(1, 2.0, "3"))
/// > |> tuple3(int, float, string)
/// Ok(#(1, 2.0, "3"))
///
/// > from(#(1, 2))
/// > |> tuple3(int, float, string)
/// Error([
/// DecodeError(expected: "3 element tuple", found: "2 element tuple", path: [])),
/// ])
///
/// > from("")
/// > |> tuple3(int, float, string)
/// Error([
/// DecodeError(expected: "3 element tuple", found: "String", path: []),
/// ])
/// ```
///
pub fn tuple3(
first decode1: Decoder(a),
second decode2: Decoder(b),
third decode3: Decoder(c),
) -> Decoder(#(a, b, c)) {
fn(value) {
try _ = assert_is_tuple(value, 3)
let #(a, b, c) = unsafe_coerce(value)
case decode1(a), decode2(b), decode3(c) {
Ok(a), Ok(b), Ok(c) -> Ok(#(a, b, c))
a, b, c ->
tuple_errors(a, "0")
|> list.append(tuple_errors(b, "1"))
|> list.append(tuple_errors(c, "2"))
|> Error
}
}
}
/// Checks to see if a `Dynamic` value is a 4 element tuple containing
/// specifically typed elements.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2, 3, 4))
/// > |> tuple4(int, int, int, int)
/// Ok(#(1, 2, 3, 4))
///
/// > from(#(1, 2.0, "3", 4))
/// > |> tuple4(int, float, string, int)
/// Ok(#(1, 2.0, "3", 4))
///
/// > from(#(1, 2))
/// > |> tuple4(int, float, string, int)
/// Error([
/// DecodeError(expected: "4 element tuple", found: "2 element tuple", path: []),
/// ])
///
/// > from("")
/// > |> tuple4(int, float, string, int)
/// Error([
/// DecodeError(expected: "4 element tuple", found: "String", path: []),
/// ])
/// ```
///
pub fn tuple4(
first decode1: Decoder(a),
second decode2: Decoder(b),
third decode3: Decoder(c),
fourth decode4: Decoder(d),
) -> Decoder(#(a, b, c, d)) {
fn(value) {
try _ = assert_is_tuple(value, 4)
let #(a, b, c, d) = unsafe_coerce(value)
case decode1(a), decode2(b), decode3(c), decode4(d) {
Ok(a), Ok(b), Ok(c), Ok(d) -> Ok(#(a, b, c, d))
a, b, c, d ->
tuple_errors(a, "0")
|> list.append(tuple_errors(b, "1"))
|> list.append(tuple_errors(c, "2"))
|> list.append(tuple_errors(d, "3"))
|> Error
}
}
}
/// Checks to see if a `Dynamic` value is a 5-element tuple containing
/// specifically typed elements.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2, 3, 4, 5))
/// > |> tuple5(int, int, int, int, int)
/// Ok(#(1, 2, 3, 4, 5))
///
/// > from(#(1, 2.0, "3", 4, 5))
/// > |> tuple5(int, float, string, int, int)
/// Ok(#(1, 2.0, "3", 4, 5))
///
/// > from(#(1, 2))
/// > |> tuple5(int, float, string, int, int)
/// Error([
/// DecodeError(expected: "5 element tuple", found: "2 element tuple", path: [])),
/// ])
///
/// > from("")
/// > |> tuple5(int, float, string, int, int)
/// Error([DecodeError(expected: "5 element tuple", found: "String", path: [])])
/// ```
///
pub fn tuple5(
first decode1: Decoder(a),
second decode2: Decoder(b),
third decode3: Decoder(c),
fourth decode4: Decoder(d),
fifth decode5: Decoder(e),
) -> Decoder(#(a, b, c, d, e)) {
fn(value) {
try _ = assert_is_tuple(value, 5)
let #(a, b, c, d, e) = unsafe_coerce(value)
case decode1(a), decode2(b), decode3(c), decode4(d), decode5(e) {
Ok(a), Ok(b), Ok(c), Ok(d), Ok(e) -> Ok(#(a, b, c, d, e))
a, b, c, d, e ->
tuple_errors(a, "0")
|> list.append(tuple_errors(b, "1"))
|> list.append(tuple_errors(c, "2"))
|> list.append(tuple_errors(d, "3"))
|> list.append(tuple_errors(e, "4"))
|> Error
}
}
}
/// Checks to see if a `Dynamic` value is a 6-element tuple containing
/// specifically typed elements.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2, 3, 4, 5, 6))
/// > |> tuple6(int, int, int, int, int, int)
/// Ok(#(1, 2, 3, 4, 5, 6))
///
/// > from(#(1, 2.0, "3", 4, 5, 6))
/// > |> tuple6(int, float, string, int, int)
/// Ok(#(1, 2.0, "3", 4, 5, 6))
///
/// > from(#(1, 2))
/// > |> tuple6(int, float, string, int, int, int)
/// Error([
/// DecodeError(expected: "6 element tuple", found: "2 element tuple", path: []),
/// ])
/// ```
///
pub fn tuple6(
first decode1: Decoder(a),
second decode2: Decoder(b),
third decode3: Decoder(c),
fourth decode4: Decoder(d),
fifth decode5: Decoder(e),
sixth decode6: Decoder(f),
) -> Decoder(#(a, b, c, d, e, f)) {
fn(value) {
try _ = assert_is_tuple(value, 6)
let #(a, b, c, d, e, f) = unsafe_coerce(value)
case decode1(a), decode2(b), decode3(c), decode4(d), decode5(e), decode6(f) {
Ok(a), Ok(b), Ok(c), Ok(d), Ok(e), Ok(f) -> Ok(#(a, b, c, d, e, f))
a, b, c, d, e, f ->
tuple_errors(a, "0")
|> list.append(tuple_errors(b, "1"))
|> list.append(tuple_errors(c, "2"))
|> list.append(tuple_errors(d, "3"))
|> list.append(tuple_errors(e, "4"))
|> list.append(tuple_errors(f, "5"))
|> Error
}
}
}
/// Checks to see if a `Dynamic` value is a map.
///
/// ## Examples
///
/// ```gleam
/// > import gleam/map
/// > map(from(map.new()))
/// Ok(map.new())
///
/// > map(from(1))
/// Error(DecodeError(expected: "Map", found: "Int", path: []))
///
/// > map(from(""))
/// Error(DecodeError(expected: "Map", found: "String", path: []))
/// ```
///
pub fn map(
of key_type: Decoder(k),
to value_type: Decoder(v),
) -> Decoder(Map(k, v)) {
fn(value) {
try map = decode_map(value)
try pairs =
map
|> map.to_list
|> list.try_map(fn(pair) {
let #(k, v) = pair
try k =
key_type(k)
|> map_errors(push_path(_, "keys"))
try v =
value_type(v)
|> map_errors(push_path(_, "values"))
Ok(#(k, v))
})
Ok(map.from_list(pairs))
}
}
if erlang {
external fn decode_map(Dynamic) -> Result(Map(Dynamic, Dynamic), DecodeErrors) =
"gleam_stdlib" "decode_map"
}
if javascript {
external fn decode_map(Dynamic) -> Result(Map(Dynamic, Dynamic), DecodeErrors) =
"../gleam_stdlib.mjs" "decode_map"
}
/// Joins multiple decoders into one. When run they will each be tried in turn
/// until one succeeds, or they all fail.
///
/// ## Examples
///
/// ```gleam
/// > import gleam/result
/// > let bool_or_string = any(of: [
/// > string,
/// > fn(x) { result.map(bool(x), fn(_) { "a bool" }) }
/// > ])
/// > bool_or_string(from("ok"))
/// Ok("ok")
///
/// > bool_or_string(from(True))
/// Ok("a bool")
///
/// > bool_or_string(from(1))
/// Error(DecodeError(expected: "unknown", found: "unknown", path: []))
/// ```
///
pub fn any(of decoders: List(Decoder(t))) -> Decoder(t) {
fn(data) {
case decoders {
[] ->
Error([
DecodeError(found: classify(data), expected: "another type", path: []),
])
[decoder, ..decoders] ->
case decoder(data) {
Ok(decoded) -> Ok(decoded)
Error(_) -> any(decoders)(data)
}
}
}
}
/// Decode 2 values from a `Dynamic` value.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2.0, "3"))
/// > |> decode2(MyRecord, element(0, int), element(1, float))
/// Ok(MyRecord(1, 2.0))
/// ```
///
/// ```gleam
/// > from(#("", "", ""))
/// > |> decode2(MyRecord, element(0, int), element(1, float))
/// Error([
/// DecodeError(expected: "Int", found: "String", path: ["0"]),
/// DecodeError(expected: "Float", found: "String", path: ["1"]),
/// ])
/// ```
///
pub fn decode2(
constructor: fn(t1, t2) -> t,
t1: Decoder(t1),
t2: Decoder(t2),
) -> Decoder(t) {
fn(value) {
case t1(value), t2(value) {
Ok(a), Ok(b) -> Ok(constructor(a, b))
a, b -> Error(list.flatten([all_errors(a), all_errors(b)]))
}
}
}
/// Decode 3 values from a `Dynamic` value.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2.0, "3"))
/// > |> decode3(MyRecord, element(0, int), element(1, float), element(2, string))
/// Ok(MyRecord(1, 2.0, "3"))
/// ```
///
/// ```gleam
/// > from(#("", "", ""))
/// > |> decode3(MyRecord, element(0, int), element(1, float), element(2, string))
/// Error([
/// DecodeError(expected: "Int", found: "String", path: ["0"]),
/// DecodeError(expected: "Float", found: "String", path: ["1"]),
/// ])
/// ```
///
pub fn decode3(
constructor: fn(t1, t2, t3) -> t,
t1: Decoder(t1),
t2: Decoder(t2),
t3: Decoder(t3),
) -> Decoder(t) {
fn(value) {
case t1(value), t2(value), t3(value) {
Ok(a), Ok(b), Ok(c) -> Ok(constructor(a, b, c))
a, b, c ->
Error(list.flatten([all_errors(a), all_errors(b), all_errors(c)]))
}
}
}
/// Decode 4 values from a `Dynamic` value.
///
/// ## Examples
///
/// ```gleam
/// > from(#(1, 2.1, "3", "4"))
/// > |> decode4(
/// > MyRecord,
/// > element(0, int),
/// > element(1, float),
/// > element(2, string),
/// > element(3, string),
/// > )
/// Ok(MyRecord(1, 2.1, "3", "4"))
/// ```
///
/// ```gleam
/// > from(#("", "", "", ""))
/// > |> decode4(
/// > MyRecord,