Skip to main content

Bitmasks

There are few points in Uala's backend application that use bitmasks, and the majority of them are used to store time availability data. A bitmask represent the availability using bits (0 and 1), and by default, 0 means "no availability" and 1 means availability. Each bit represent a single time slot (e.g.: time_slot = 900 (15min), each bit represent availability of 15min).

Reading a bitmask​

Reading the bitmaks from right to left is the natural order of time slots (starting from beginning of day to the end of day). Note that by default a bitmask represent at maximum a single day of availability. The lower limit (beginning of day) of the bitmask is set by Uala::TimeVariables.time_table_start and the upper limit (end of day) is set by Uala::TimeVariables.time_table_end.

Some examples:

0b11110000 -> availability from 9:00 to 10:00
0b0 -> no availability at all
0b10101010 -> availability on 8:15, 8:45, 9:15, 9:45

NB leading zeros are not significant (0b0001 = 0b1)

NB when the bitmask is represented as integer, using .to_s(2) method will transform it in a base 2 string

Operation with bitmasks​

The most common usage with bitmask is to check if some requested time range is available or not; to do that we obviously need two bitmasks, one is the requested availability (request_bitmask) and the other one is our availability bitmask (availability_bitmask).

To check if the request is satisfied, the bitwise AND between the two bitmasks should equal to the request_bitmask:

availability_bitmask & request_bitmask == request_bitmask

This operation ensures that each requested slot is available.

Some examples:

request_bitmask = 0b11110000

1. availability_bitmask = 0b0
-> 0b0 & 0b11110000 -> 0b0 -> no availability

2. availability_bitmask = 0b11111110
-> 0b11111110 & 0b11110000 -> 0b11110000 -> availability

3. availability_bitmask = 0b11011110
-> 0b11011110 & 0b11110000 -> 0b10110000 -> no availability