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