multidimensional bitmaps in Lua
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env lua5.4 | |
--[[ | |
This file is licensed under the license `CC BY-NC-ND 4.0`, visit "https://creativecommons.org/licenses/by-nc-nd/4.0/" for additional information. | |
author: wfrsk @ github.com | |
]] | |
local INTEGER_SIZE <const> = string.packsize( "j" ) * 8 | |
local function make_bitmap( x_bounds ) | |
local integers_required = math.ceil( x_bounds / INTEGER_SIZE ) | |
local internal_bitmap, external_adapter do | |
internal_bitmap = { } do | |
for index = 1, integers_required do | |
internal_bitmap[ index ] = 0 | |
end | |
end | |
local function index_routine( _, bitspace_index ) | |
assert( type( bitspace_index ) == "number", "index must be an integer" ) | |
local integer_index, bit_index = math.ceil( bitspace_index / INTEGER_SIZE ), bitspace_index % INTEGER_SIZE | |
return assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) & ( 1 << ( bit_index - 1 ) ) | |
end | |
local function newindex_routine( _, bitspace_index, new_value ) | |
assert( type( bitspace_index ) == "number", "index must be an integer" ) | |
local integer_index, bit_index = math.ceil( bitspace_index / INTEGER_SIZE ), bitspace_index % INTEGER_SIZE | |
internal_bitmap[ integer_index ] = ( new_value & 1 ) == 1 and assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) | ( 1 << ( bit_index - 1 ) ) or assert( internal_bitmap[ integer_index ], "index given out of bounds for bitmap" ) & ~( 1 << ( bit_index - 1 ) ) | |
end | |
external_adapter = setmetatable( { }, { __index = index_routine, __newindex = newindex_routine } ) | |
end | |
return external_adapter | |
end | |
local function make_bitmap_2d( x_bounds, y_bounds ) | |
local bidimensional_bitmap = { } do | |
for index = 1, x_bounds do | |
bidimensional_bitmap[ index ] = make_bitmap( y_bounds ) | |
end | |
end | |
return bidimensional_bitmap | |
end | |
local function make_bitmap_3d( x_bounds, y_bounds, z_bounds ) | |
local tridimensional_bitmap = { } do | |
for index = 1, x_bounds do | |
tridimensional_bitmap[ index ] = make_bitmap_2d( y_bounds, z_bounds ) | |
end | |
end | |
return tridimensional_bitmap | |
end | |
return { make_bitmap = make_bitmap, make_bitmap_2d = make_bitmap_2d, make_bitmap_3d = make_bitmap_3d } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment