Skip to content

Instantly share code, notes, and snippets.

@lpgauth
Created January 26, 2020 15:49
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 lpgauth/de6642df3c69eec4c0aeb9fb0023551d to your computer and use it in GitHub Desktop.
Save lpgauth/de6642df3c69eec4c0aeb9fb0023551d to your computer and use it in GitHub Desktop.
-module(bloomfilter).
-export([new/1, insert/2, contains/2]).
-define(PREFIX, [<<"foo">>, <<"bar">>, <<"baz">>]).
new(Size) ->
{bf, Size, atomics:new(Size, [])}.
insert({bf, Size, Ref}, Key) ->
[atomics:put(Ref, Index, 1) || Index <- indexes(Key, Size)].
contains({bf, Size, Ref}, Key) ->
lists:all(fun (Index) -> atomics:get(Ref, Index) =:= 1 end, indexes(Key, Size)).
%% private
indexes(Key, Size) ->
[binary:decode_unsigned(crypto:hash(blake2b, <<Prefix/binary, Key/binary>>)) rem Size || Prefix <- ?PREFIX].
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment