1 |
|
%% Copyright (c) 2023 Peter Morgan <peter.james.morgan@gmail.com> |
2 |
|
%% |
3 |
|
%% Licensed under the Apache License, Version 2.0 (the "License"); |
4 |
|
%% you may not use this file except in compliance with the License. |
5 |
|
%% You may obtain a copy of the License at |
6 |
|
%% |
7 |
|
%% http://www.apache.org/licenses/LICENSE-2.0 |
8 |
|
%% |
9 |
|
%% Unless required by applicable law or agreed to in writing, software |
10 |
|
%% distributed under the License is distributed on an "AS IS" BASIS, |
11 |
|
%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 |
|
%% See the License for the specific language governing permissions and |
13 |
|
%% limitations under the License. |
14 |
|
|
15 |
|
|
16 |
|
%% @doc Encoder combinators. |
17 |
|
|
18 |
|
-module(narcs_combinator). |
19 |
|
|
20 |
|
|
21 |
|
-export([condition/2]). |
22 |
|
-export([map_result/2]). |
23 |
|
-export([rest/0]). |
24 |
|
-export([v/2]). |
25 |
|
-include_lib("kernel/include/logger.hrl"). |
26 |
|
|
27 |
|
|
28 |
|
%% @doc Map the result of the supplied encoder. |
29 |
|
|
30 |
|
map_result(Encoder, Mapping) -> |
31 |
9 |
fun |
32 |
|
(Decoded) -> |
33 |
6 |
(Mapping(Encoder(Decoded))) |
34 |
|
end. |
35 |
|
|
36 |
|
|
37 |
|
%% @doc Apply the encoder if the condition is true. |
38 |
|
|
39 |
|
-type condition() :: boolean() |
40 |
|
| atom(). |
41 |
|
|
42 |
|
-spec condition(condition(), narcs:encoder()) -> narcs:encoder(). |
43 |
|
|
44 |
|
condition(true, Encoder) -> |
45 |
:-( |
fun |
46 |
|
(Decoded) -> |
47 |
:-( |
(Encoder)(Decoded) |
48 |
|
end; |
49 |
|
|
50 |
|
condition(false, _) -> |
51 |
:-( |
fun |
52 |
|
(_) -> |
53 |
:-( |
<<>> |
54 |
|
end; |
55 |
|
|
56 |
|
condition(Key, Encoder) -> |
57 |
1 |
fun |
58 |
|
(#{Key := true} = Decoded) -> |
59 |
1 |
(Encoder)(Decoded); |
60 |
|
|
61 |
|
(#{Key := false}) -> |
62 |
1 |
<<>>; |
63 |
|
|
64 |
|
(_) -> |
65 |
:-( |
error(badarg, [Key, Encoder]) |
66 |
|
end. |
67 |
|
|
68 |
|
|
69 |
|
%% @doc Apply an encoder on the value represented by the supplied key. |
70 |
|
|
71 |
|
-spec v(any(), narcs:encoder()) -> narcs:encoder(map(), narcs:output()). |
72 |
|
|
73 |
|
v(Key, Encoder) -> |
74 |
8 |
fun |
75 |
|
(#{Key := Value} = Decoded) -> |
76 |
4 |
?LOG_DEBUG(#{key => Key, value => Value, decoded => Decoded}), |
77 |
4 |
Encoder(Value); |
78 |
|
|
79 |
|
(_) -> |
80 |
:-( |
error(badarg, [Key, Encoder]) |
81 |
|
end. |
82 |
|
|
83 |
|
|
84 |
|
%% @doc Use the rest of the output as is. |
85 |
|
|
86 |
|
-spec rest() -> narcs:encoder(). |
87 |
|
|
88 |
|
rest() -> |
89 |
:-( |
fun |
90 |
|
(Decoded) -> |
91 |
:-( |
Decoded |
92 |
|
end. |