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 |
|
%% @doc Encoder combinators that deal with byte output. |
16 |
|
|
17 |
|
-module(narcs_bytes). |
18 |
|
|
19 |
|
|
20 |
|
-export([from_atom/0]). |
21 |
|
-export([length_encoded/1]). |
22 |
|
-export([null_terminated/0]). |
23 |
|
-export([tag/1]). |
24 |
|
-export([take/1]). |
25 |
|
-include_lib("kernel/include/logger.hrl"). |
26 |
|
|
27 |
|
|
28 |
|
%% @doc Use the supplied encoder to write the length of output. |
29 |
|
|
30 |
|
-spec length_encoded(narcs:encoder(A, iodata())) -> narcs:encoder(A, iodata()). |
31 |
|
|
32 |
|
length_encoded(Encoder) -> |
33 |
9 |
fun |
34 |
|
(Decoded) -> |
35 |
5 |
?LOG_DEBUG(#{encoder => Encoder, decoded => Decoded}), |
36 |
5 |
[Encoder(iolist_size(Decoded)), Decoded] |
37 |
|
end. |
38 |
|
|
39 |
|
|
40 |
|
-spec null_terminated() -> narcs:encoder(iodata(), iodata()). |
41 |
|
|
42 |
|
%% @doc Write a null byte after the output. |
43 |
|
|
44 |
|
null_terminated() -> |
45 |
4 |
fun |
46 |
|
(Decoded) -> |
47 |
5 |
[Decoded, 0] |
48 |
|
end. |
49 |
|
|
50 |
|
|
51 |
|
-spec from_atom() -> narcs:encoder(atom(), binary()). |
52 |
|
|
53 |
|
%% @doc Write an atom as a sequence of bytes. |
54 |
|
|
55 |
|
from_atom() -> |
56 |
4 |
fun |
57 |
|
(Decoded) -> |
58 |
4 |
erlang:atom_to_binary(Decoded) |
59 |
|
end. |
60 |
|
|
61 |
|
|
62 |
|
-spec tag(binary()) -> narcs:encoder(any(), binary()). |
63 |
|
|
64 |
|
%% @doc Write the matching output. |
65 |
|
|
66 |
|
tag(Tag) -> |
67 |
:-( |
fun |
68 |
|
(_) -> |
69 |
:-( |
Tag |
70 |
|
end. |
71 |
|
|
72 |
|
|
73 |
|
-spec take(non_neg_integer()) -> narcs:encoder(binary(), binary()). |
74 |
|
|
75 |
|
%% @doc Output the number bytes. |
76 |
|
|
77 |
|
take(N) -> |
78 |
1 |
fun |
79 |
|
(<<Decoded:N/bytes>>) -> |
80 |
1 |
Decoded |
81 |
|
end. |