Skip to content

Instantly share code, notes, and snippets.

@dreid
Created August 26, 2011 20:34
Show Gist options
  • Save dreid/1174372 to your computer and use it in GitHub Desktop.
Save dreid/1174372 to your computer and use it in GitHub Desktop.
Efficient binary strip?
-module(bstrip).
-export([bstrip/1, bstrip/2]).
bstrip(Bin) ->
bstrip(Bin, both).
bstrip(Bin, left) ->
blstrip(Bin);
bstrip(Bin, right) ->
brstrip(Bin);
bstrip(Bin, both) ->
blstrip(brstrip(Bin)).
blstrip(<<"\t", Bin/binary>>) ->
blstrip(Bin);
blstrip(<<"\n", Bin/binary>>) ->
blstrip(Bin);
blstrip(<<"\r", Bin/binary>>) ->
blstrip(Bin);
blstrip(<<" ", Bin/binary>>) ->
blstrip(Bin);
blstrip(Bin) ->
brstrip(Bin).
brstrip(Bin) ->
brstrip(Bin, size(Bin)-1).
brstrip(Bin, Size) ->
NextSize = Size-1,
case Bin of
<<Bin2:Size/binary, " ">> ->
brstrip(Bin2, NextSize);
<<Bin2:Size/binary, "\r">> ->
brstrip(Bin2, NextSize);
<<Bin2:Size/binary, "\n">> ->
brstrip(Bin2, NextSize);
<<Bin2:Size/binary, "\t">> ->
brstrip(Bin2, NextSize);
StrippedBin ->
StrippedBin
end.
-ifdef(TEST).
-include_lib("eunit/include/eunit.hrl").
bstrip_test_() ->
Tests = [<<" foo bar">>,
<<" foo bar ">>,
<<"\r\n \t foo bar">>,
<<" foo bar \r\n \t ">>],
[{iolist_to_binary(io_lib:format("~p", [Input])),
?_assertEqual(<<"foo bar">>, bstrip(Input))} ||
Input <- Tests].
-endif.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment