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
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]}
Converts an atom from the bitmask into its underlying value
iex> MyBitmask.atom_to_bitmask(:flag_3)
4
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]
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
Converts an integer into a bitmask
iex> MyBitmask.int_to_bitmask(3)
%MyBitmask{bitmask: 3, flags: [:flag_1, :flag_2]}