PageRenderTime 73ms CodeModel.GetById 69ms app.highlight 2ms RepoModel.GetById 0ms app.codeStats 0ms

/src/support/z_quoted_printable.erl

https://code.google.com/p/zotonic/
Erlang | 51 lines | 23 code | 9 blank | 19 comment | 0 complexity | 80a70368b31188b416d44949366f8a8e MD5 | raw file
 1%% @author Marc Worrell <marc@worrell.nl>
 2%% Date: 2010-02-12
 3%% @copyright 2010 Marc Worrell
 4%% @doc Encode data to quoted printable strings.
 5
 6%% Copyright 2010 Marc Worrell
 7%%
 8%% Licensed under the Apache License, Version 2.0 (the "License");
 9%% you may not use this file except in compliance with the License.
10%% You may obtain a copy of the License at
11%% 
12%%     http://www.apache.org/licenses/LICENSE-2.0
13%% 
14%% Unless required by applicable law or agreed to in writing, software
15%% distributed under the License is distributed on an "AS IS" BASIS,
16%% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17%% See the License for the specific language governing permissions and
18%% limitations under the License.
19
20-module(z_quoted_printable).
21
22-author("Marc Worrell <marc@worrell.nl>").
23
24-export([
25    encode/1
26]).
27
28
29%% @doc Encode a string as quoted printable.
30%% @spec encode(iolist()) -> binary()
31encode(L) when is_list(L) ->
32    encode(iolist_to_binary(L));
33encode(B) when is_binary(B) ->
34    encode(B, 0, <<>>).
35    
36    encode(<<>>, _, Acc) ->
37        Acc;
38    encode(B, Len, Acc) when Len >= 72 ->
39        encode(B, 0, <<Acc/binary, $=, 13, 10>>);
40    encode(<<C,Rest/binary>>, Len, Acc) when C < 32 orelse C >= 127 orelse C =:= $= orelse C =:= $. ->
41        H1 = to_hex(C div 16),
42        H2 = to_hex(C rem 16),
43        encode(Rest, Len+3, <<Acc/binary, $=, H1, H2>>);
44    encode(<<C,Rest/binary>>, Len, Acc) ->
45        encode(Rest, Len+1, <<Acc/binary, C>>).
46
47
48to_hex(C) when C < 10 -> 
49    C + $0;
50to_hex(C) -> 
51    C - 10 + $A.