1%%
2%% %CopyrightBegin%
3%%
4%% Copyright Ericsson AB 2012-2016. All Rights Reserved.
5%%
6%% Licensed under the Apache License, Version 2.0 (the "License");
7%% you may not use this file except in compliance with the License.
8%% You may obtain a copy of the License at
9%%
10%%     http://www.apache.org/licenses/LICENSE-2.0
11%%
12%% Unless required by applicable law or agreed to in writing, software
13%% distributed under the License is distributed on an "AS IS" BASIS,
14%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15%% See the License for the specific language governing permissions and
16%% limitations under the License.
17%%
18%% %CopyrightEnd%
19%%
20%%
21-module(asn1rtt_uper).
22
23-export([skipextensions/3]).
24-export([complete/1, complete_NFP/1]).
25
26skipextensions(Bytes0, Nr, ExtensionBitstr) when is_bitstring(ExtensionBitstr) ->
27    Prev = Nr - 1,
28    case ExtensionBitstr of
29	<<_:Prev,1:1,_/bitstring>> ->
30	    {Len,Bytes1} = decode_length(Bytes0),
31	    <<_:Len/binary,Bytes2/bitstring>> = Bytes1,
32	    skipextensions(Bytes2, Nr+1, ExtensionBitstr);
33	<<_:Prev,0:1,_/bitstring>> ->
34	    skipextensions(Bytes0, Nr+1, ExtensionBitstr);
35	_ ->
36	    Bytes0
37    end.
38
39%% un-constrained
40decode_length(<<0:1,Oct:7,Rest/bitstring>>)  ->
41    {Oct,Rest};
42decode_length(<<2:2,Val:14,Rest/bitstring>>)  ->
43    {Val,Rest};
44decode_length(<<3:2,_:14,_Rest/bitstring>>)  ->
45    exit({error,{asn1,{decode_length,{nyi,above_16k}}}}).
46
47%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
48%% complete(InList) -> ByteList
49%% Takes a coded list with bits and bytes and converts it to a list of bytes
50%% Should be applied as the last step at encode of a complete ASN.1 type
51%%
52complete(InList) when is_list(InList) ->
53    case list_to_bitstring(InList) of
54	<<>> ->
55	    <<0>>;
56	Res ->
57	    Sz = bit_size(Res),
58	    case Sz band 7 of
59		0 -> Res;
60		Bits -> <<Res:Sz/bitstring,0:(8-Bits)>>
61	end
62    end;
63complete(Bin) when is_binary(Bin) ->
64    case Bin of
65	<<>> -> <<0>>;
66	_ -> Bin
67    end;
68complete(InList) when is_bitstring(InList) ->
69    Sz = bit_size(InList),
70    PadLen = 8 - (Sz band 7),
71    <<InList:Sz/bitstring,0:PadLen>>.
72
73%% Special version of complete that does not align the completed message.
74complete_NFP(InList) when is_list(InList) ->
75    list_to_bitstring(InList);
76complete_NFP(InList) when is_bitstring(InList) ->
77    InList.
78