| 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 An unsigned variable length little endian integer. |
| 16 |
|
|
| 17 |
|
-module(msmp_integer_variable). |
| 18 |
|
|
| 19 |
|
|
| 20 |
|
-export([decode/0]). |
| 21 |
|
-export([encode/0]). |
| 22 |
|
|
| 23 |
|
|
| 24 |
|
-type variable_length() :: msmp:u1() |
| 25 |
|
| msmp:u2() |
| 26 |
|
| msmp:u3() |
| 27 |
|
| msmp:u8(). |
| 28 |
|
|
| 29 |
|
|
| 30 |
|
%% @doc Decode an unsigned variable length little endian integer. |
| 31 |
|
-spec decode() -> scran:parser(binary(), variable_length()). |
| 32 |
|
|
| 33 |
|
decode() -> |
| 34 |
281 |
fun |
| 35 |
|
(<<I:8, Remaining/bytes>>) when I < 251 -> |
| 36 |
265 |
{Remaining, I}; |
| 37 |
|
|
| 38 |
|
(<<16#fc, I:16/little, Remaining/bytes>>) when I >= 251, I < 1 bsl 16 -> |
| 39 |
3 |
{Remaining, I}; |
| 40 |
|
|
| 41 |
|
(<<16#fd, I:24/little, Remaining/bytes>>) when I >= 1 bsl 16, I < 1 bsl 24 -> |
| 42 |
:-( |
{Remaining, I}; |
| 43 |
|
|
| 44 |
|
(<<16#fe, I:64/little, Remaining/bytes>>) when I >= 1 bsl 24, I < 1 bsl 64 -> |
| 45 |
:-( |
{Remaining, I}; |
| 46 |
|
|
| 47 |
|
(_) -> |
| 48 |
22 |
nomatch |
| 49 |
|
end. |
| 50 |
|
|
| 51 |
|
|
| 52 |
|
%% @doc Encode an unsigned variable length little endian integer. |
| 53 |
|
-spec encode() -> narcs:encoder(non_neg_integer(), binary()). |
| 54 |
|
|
| 55 |
|
encode() -> |
| 56 |
54 |
fun |
| 57 |
|
(I) when I < 251 -> |
| 58 |
53 |
<<I:8>>; |
| 59 |
|
|
| 60 |
|
(I) when I >= 251, I < 1 bsl 16 -> |
| 61 |
:-( |
<<16#fc, I:16/little>>; |
| 62 |
|
|
| 63 |
|
(I) when I >= 1 bsl 16, I < 1 bsl 24 -> |
| 64 |
:-( |
<<16#fd, I:24/little>>; |
| 65 |
|
|
| 66 |
|
(I) when I >= 1 bsl 24, I < 1 bsl 64 -> |
| 67 |
:-( |
<<16#fe, I:64/little>> |
| 68 |
|
end. |