| 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 Parser combinators that deal with bit inputs |
| 17 |
|
|
| 18 |
|
-module(scran_bits). |
| 19 |
|
|
| 20 |
|
|
| 21 |
|
-export([into_boolean/0]). |
| 22 |
|
-export([tag/1]). |
| 23 |
|
-export([take/1]). |
| 24 |
|
-include_lib("kernel/include/logger.hrl"). |
| 25 |
|
|
| 26 |
|
|
| 27 |
|
%% @doc Takes 1 bit from the input converting it into a boolean. |
| 28 |
|
%% @returns A tuple of the remaining input and a boolean result. |
| 29 |
|
|
| 30 |
|
-spec into_boolean() -> scran:parser(<<_:_*1>>, boolean()). |
| 31 |
|
|
| 32 |
|
into_boolean() -> |
| 33 |
11 |
fun |
| 34 |
|
(<<0:1, Remaining/bits>>) -> |
| 35 |
40 |
{Remaining, false}; |
| 36 |
|
|
| 37 |
|
(<<1:1, Remaining/bits>>) -> |
| 38 |
18 |
{Remaining, true}; |
| 39 |
|
|
| 40 |
|
(_) -> |
| 41 |
7 |
nomatch |
| 42 |
|
end. |
| 43 |
|
|
| 44 |
|
|
| 45 |
|
%% @doc Return the matching input. |
| 46 |
|
|
| 47 |
|
-spec tag(bitstring()) -> scran:parser(<<_:_*1>>, <<_:_*1>>). |
| 48 |
|
|
| 49 |
|
tag(Tag) -> |
| 50 |
:-( |
fun |
| 51 |
|
(<<Matched:(bit_size(Tag))/bits, Remaining/bits>>) |
| 52 |
|
when Tag == Matched -> |
| 53 |
:-( |
{Remaining, Tag}; |
| 54 |
|
|
| 55 |
|
(_) -> |
| 56 |
:-( |
nomatch |
| 57 |
|
end. |
| 58 |
|
|
| 59 |
|
|
| 60 |
|
take(N) when is_integer(N), N >= 0 -> |
| 61 |
:-( |
?LOG_DEBUG(#{n => N}), |
| 62 |
:-( |
fun |
| 63 |
|
(<<Taken:N/bits, Remaining/bits>>) -> |
| 64 |
:-( |
?LOG_DEBUG(#{n => N, |
| 65 |
|
taken => Taken, |
| 66 |
:-( |
remaining => Remaining}), |
| 67 |
|
|
| 68 |
:-( |
{Remaining, Taken}; |
| 69 |
|
|
| 70 |
|
(Otherwise) -> |
| 71 |
:-( |
?LOG_DEBUG(#{nomatch => Otherwise, n => N}), |
| 72 |
:-( |
nomatch |
| 73 |
|
end. |