Created
August 26, 2011 20:34
-
-
Save dreid/1174372 to your computer and use it in GitHub Desktop.
Efficient binary strip?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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