View Source Bitmask behaviour (Bitmask v0.1.1)

A use macro for automatically generating a Bitmask from a collection of atoms, with support for saving them to a database via the provided Ecto.Type.

You can create a bitmask like so:

defmodule MyBitmask do
  use Bitmask, [
    :flag_1,
    :flag_2,
    :flag_3,
    :flag_4,
  ]
end

Or, you can define specific values for each field:

defmodule MyBitmask do
  import Bitwise
  use Bitmask, [
    flag_1: 1 <<< 0,
    flag_2: 1 <<< 1,
    flag_3: 1 <<< 2,
    flag_4: 1 <<< 3,
  ]
end

The generated bitmask can also optinally be used with ecto. It stores the flags in the DB as a bigint:

defmodule SomeEctoSchema do
  use Ecto.Schema
  schema "bitmasks" do
    field :my_bitmask, MyBitmask
  end
end

Link to this section Summary

Callbacks

Converts a list of atoms into a bitmask

Converts an atom from the bitmask into its underlying value

Returns the a list of all the bitmasks flags

Checks if a bitmask has a flag set

Converts an integer into a bitmask

Link to this section Callbacks

Link to this callback

atom_flags_to_bitmask(list)

View Source (since 0.1.0)
@callback atom_flags_to_bitmask([atom()]) :: %{bitmask: integer(), flags: [atom()]}

Converts a list of atoms into a bitmask

iex> MyBitmask.atom_flags_to_bitmask([:flag_1, :flag_3])
%MyBitmask{bitmask: 5, flags: [:flag_1, :flag_3]}
Link to this callback

atom_to_bitmask(atom)

View Source (since 0.1.0)
@callback atom_to_bitmask(atom()) :: integer()

Converts an atom from the bitmask into its underlying value

iex> MyBitmask.atom_to_bitmask(:flag_3)
4
Link to this callback

get_all_values()

View Source (since 0.1.0)
@callback get_all_values() :: [{atom(), integer()}]

Returns the a list of all the bitmasks flags

iex> MyBitmask.get_all_values()
[flag_1: 1, flag_2: 2, flag_3: 4, flag_4: 8]
Link to this callback

has_flag(arg1, atom)

View Source (since 0.1.0)
@callback has_flag(%{bitmask: integer(), flags: [atom()]} | integer(), atom()) ::
  boolean()

Checks if a bitmask has a flag set

iex> bitmask = MyBitmask.int_to_bitmask(3)
%MyBitmask{bitmask: 3, flags: [:flag_1, :flag_2]}
iex> MyBitmask.has_flag(bitmask, :flag_2)
true
Link to this callback

int_to_bitmask(integer)

View Source (since 0.1.0)
@callback int_to_bitmask(integer()) :: %{bitmask: integer(), flags: [atom()]}

Converts an integer into a bitmask

iex> MyBitmask.int_to_bitmask(3)
%MyBitmask{bitmask: 3, flags: [:flag_1, :flag_2]}