Skip to content

Instantly share code, notes, and snippets.

@awsong
Created July 22, 2011 09:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save awsong/1099160 to your computer and use it in GitHub Desktop.
Save awsong/1099160 to your computer and use it in GitHub Desktop.
Erlang WebSocket message masking test code snippet
-module(websocket_client).
-compile(export_all).
-on_load(init/0).
init() ->
ok = erlang:load_nif("./nif_mask", 3).
nif_mask(_,_,_) ->
exit(nif_library_not_loaded).
mask(Key,Data,Accu) ->
case Data of
<<A:32,Rest/binary>> ->
C = binary:encode_unsigned(A bxor Key),
mask(Key,Rest,<<Accu/binary,C/binary>>);
<<A:24>> ->
<<B:24, _:8>> = binary:encode_unsigned(Key),
C = binary:encode_unsigned(A bxor B),
<<Accu/binary,C/binary>>;
<<A:16>> ->
<<B:16, _:16>> = binary:encode_unsigned(Key),
C = binary:encode_unsigned(A bxor B),
<<Accu/binary,C/binary>>;
<<A:8>> ->
<<B:8, _:24>> = binary:encode_unsigned(Key),
C = binary:encode_unsigned(A bxor B),
<<Accu/binary,C/binary>>;
<<>> ->
Accu
end.
test() ->
Max = 1024*1024*8+1,
Step = 1024*512,
Key = binary:decode_unsigned(<<16#37,16#fa,16#21,16#3d>>),
A = lists:seq(1,Max,Step),
B = lists:map(fun (D) -> binary:copy(<<100>>,D) end, A),
C = lists:map(fun (D) -> timer:tc(websocket_client, mask, [Key, D, <<>>]) end, B),
D = lists:zip(A, C),
lists:map(fun ({Index,{Time,_Val}}) -> io:format(user,"~p: ~p~n", [Index,Time]) end, D).
test1() ->
Max = 1024*1024*32,
Key = binary:decode_unsigned(<<16#37,16#fa,16#21,16#3d>>),
B = binary:copy(<<100>>,Max),
io:format("~p~n",[erlang:memory()]),
timer:tc(websocket_client, mask, [Key, B, <<>>]).
test2() ->
Max = 1024*1024*8+1,
Step = 1024*512,
Key = <<16#37,16#fa,16#21,16#3d>>,
A = lists:seq(1,Max,Step),
B = lists:map(fun (D) -> binary:copy(<<100>>,D) end, A),
C = lists:map(fun (D) -> timer:tc(websocket_client, nif_mask, [Key, D, <<>>]) end, B),
D = lists:zip(A, C),
lists:map(fun ({Index,{Time,_Val}}) -> io:format(user,"~p: ~p~n", [Index,Time]) end, D).
test3() ->
Max = 1024*1024*32,
Key = <<16#37,16#fa,16#21,16#3d>>,
B = binary:copy(<<100>>,Max),
io:format("~p~n",[erlang:memory()]),
timer:tc(websocket_client, nif_mask, [Key, B, <<>>]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment