Skip to content

Creating a roaring bitmap extension

Chung Leong edited this page Nov 17, 2026 · 5 revisions

In this exercise we're going to create a PHP extension that adds support for roaring bitmap. We're going to be using the zroaring library. It seems the most mature of the available projects and it supports Zig 0.17.x.

Getting started

First, make sure you have the Zig compiler installed on your computer. Then download the latest release of ZPX from the project's release page. Unzip the file and rename the directory to roaring.

Open composer.json and change the name of the extension to roaring:

{
    "name": "mycompany\/roaring",
    "description": "A description of my application",
    "version": "0.1.0"
}

Open src/Extension.zig and replace the boilerplate code with the following:

const php = @import("php/root.zig");

pub const @"export zig\\roaring\\Bitmap" = php.Class.Custom(@import("Bitmap.zig"));

Our extension will export a single class: Bitmap. Its implemention will be stored in src/Bitmap.zig. Let us create that now. We'll begin with the basic skeleton:

const php = @import("php/root.zig");

pub fn init() !@This() {
    php.print("init\n", .{});
    return .{};
}

pub fn deinit(self: *@This()) void {
    _ = self;
    php.print("deinit\n", .{});
}

pub fn readDimension(self: *@This(), key: php.Value, access: php.Value.Access) !php.Value {
    _ = self;
    php.print("readDimension {}, {}\n", .{
        try key.getUnsigned(),
        access,
    });
    return .fromBoolean(false);
}

pub fn hasDimension(self: *@This(), key: php.Value, check_empty: bool) !bool {
    _ = self;
    php.print("hasDimension {}, {}\n", .{
        try key.getUnsigned(),
        check_empty,
    });
    return true;
}

pub fn writeDimension(self: *@This(), key: php.Value, value: php.Value) !void {
    _ = self;
    php.print("writeDimension {}, {}\n", .{
        try key.getUnsigned(),
        try value.getBoolean(),
    });
}

pub fn unsetDimension(self: *@This(), key: php.Value) !void {
    _ = self;
    php.print("unsetDimension {}\n", .{
        try key.getUnsigned(),
    });
}

pub fn countElements(self: *@This()) !usize {
    _ = self;
    php.print("countElements\n", .{});
    return 456;
}

We want our bitmap object to behave like an array. For this, we have to implement the five handlers shown above. The code doesn't do anything but let us compile it to get a sense of how the mechanism works.

In a bash window, run ./build. After a minute or so, the binary should be ready:

Building extension at optimization level "ReleaseSmall" for PHP 8.5 (linux/x86_64)
Downloading https://downloads.php.net/~windows/releases/php-devel-pack-8.5.12-1-nts-Win32-vs17-x64.zip
Created 1 dynamic-linked library:

extensions/8.5/php_roaring.so

Create a test script:

<?php

use zig\roaring\Bitmap;

$bm = new Bitmap();
echo $bm[1234];
$bm[888] = true;
echo isset($bm[4567]), "\n";
unset($bm[777]);
echo count($bm), "\n";
unset($bm);

And run it:

php -d extension=extensions/8.5/php_roaring.so test.php
init
readDimension 1234, .read
writeDimension 888, true
hasDimension 4567, false
1
unsetDimension 777
countElements
456
deinit

Install Zroaring

Run the following command to add zroaring to the project:

zig fetch --save git+https://codeberg.org/archaistvolts/zroaring

Open build.extra.zig and add zroaring as a dependency and its module to the list of imports:

const std = @import("std");

pub fn getImports(b: *std.Build, args: anytype) []const std.Build.Module.Import {
    const zroaring_dep = b.dependency("zroaring", .{
        .target = args.target,
        .optimize = args.optimize,
    });
    return &.{
        .{ .name = "zroaring", .module = zroaring_dep.module("zroaring") },
    };
}

Implementing basic functionalities

Returning to Bitmap.zig, first bring zroaring into the namespace and add its Bitmap type as a field:

const zroaring = @import("zroaring");

const php = @import("php/root.zig");

bitmap: zroaring.Bitmap,

Then we initialize that field in our init function, which now takes one optional argument:

pub fn init(args: struct {
    indices: []u32 = &.{},
}) !@This() {
    var bm: zroaring.Bitmap = .empty;
    _ = try bm.add_many(php.allocator, args.indices);
    return .{ .bitmap = bm };
}

indices contains indices of elements that we want set to true. Zroaring implements a 32-bit roaring bitmap so all indices are u32. add_many() returns the number of unique elements added, which we don't really care about.

We free the field in deinit:

pub fn deinit(self: *@This()) void {
    self.bitmap.deinit(php.allocator);
}

In readDimension() we read it:

pub fn readDimension(self: *@This(), key: php.Value, _: php.Value.Access) !php.Value {
    const index = try key.getIntegerAs(u32, .{});
    const found = self.bitmap.contains(index);
    return .fromBoolean(found);
}

Here, we're using getIntegerAs() to ensure the number we're getting is within the range of a u32. The same is done in writeDimension():

pub fn writeDimension(self: *@This(), key: php.Value, value: php.Value) !void {
    const index = try key.getIntegerAs(u32, .{});
    if (try value.getBoolean()) {
        try self.bitmap.add(php.allocator, index);
    } else {
        try self.bitmap.remove(php.allocator, index);
    }
}

When the given value is true, we add the index to the set. Otherwise we remove it.

Conceptually, our bitmap is a giant boolean array with 4294967296 elements. Every possible key yields a value. That means hasDimension() should always return true:

pub fn hasDimension(_: *@This(), key: php.Value, _: bool) !bool {
    _ = try key.getIntegerAs(u32, .{});
    return true;
}

Unsetting an element meanwhile is impossible:

pub fn unsetDimension(_: *@This(), _: php.Value) !void {
    return error.InvalidOperation;
}

For our last handler, countElements, we could in theory return 4294967296. As that's not very useful we're going to return the number of indices in the set instead:

pub fn countElements(self: *@This()) !usize {
    return self.bitmap.get_cardinality();
}

Cardinality is the number of elements in a set.

Okay, we're ready to compile the extension. Run ./build again then try running the following code:

<?php

use zig\roaring\Bitmap;

$bm = new Bitmap([ 123, 4567, 88888 ]);
echo "123 => {$bm[123]}\n";
echo "124 => {$bm[124]}\n";
echo "88888 => {$bm[88888]}\n";
$bm[1234] = true;
$bm[88888] = $bm[123] = false;
echo count($bm), "\n";
echo "1234 => {$bm[1234]}\n";
123 => 1
124 => 
88888 => 1
2
1234 => 1

Implementing getProperties() and iterator

An object's getProperties handler is invoked in situations where PHP needs all its properties. For example, when print_r() is used. Since zroaring provides a standard iterator, we can implement our handler in a straight forward manner:

pub fn getProperties(self: *@This(), _: php.Object.PropertiesPurpose) ?*php.Array {
    const arr: *php.Array = .create();
    var iter: zroaring.Iterator = .init(self.bitmap);
    while (iter.next()) |index| {
        arr.set(index, .fromBoolean(true));
    }
    return arr;
}

Let us give our bitmap class an iterator as well so that users can use the foreach (...) construct:

pub fn iterate(self: *@This()) Iterator {
    return .init(self.bitmap);
}

const Iterator = struct {
    pub fn init(bitmap: zroaring.Bitmap) @This() {
        return .{ .bm_iter = .init(bitmap) };
    }

    pub fn next(self: *@This()) ?@Tuple(&.{ u32, bool }) {
        const index = self.bm_iter.next() orelse return null;
        return .{ index, true };
    }

    bm_iter: zroaring.Iterator,
};

And the result:

<?php

use zig\roaring\Bitmap;

$bm = new Bitmap([ 1, 3, 5, 7, 9 ]);
print_r($bm);
foreach ($bm as $key => $value) {
    echo "$key => $value\n";
}
zig\roaring\Bitmap Object
(
    [1] => 1
    [3] => 1
    [5] => 1
    [7] => 1
    [9] => 1
)
1 => 1
3 => 1
5 => 1
7 => 1
9 => 1

Implementing bitwise operators

Much of the power of roaring bitmaps comes from the fact that bitwise operations like AND and XOR can be performed on them very efficiently. To enable that, we need to implement the doOperation handler:

pub fn doOperation(opcode: php.Object.Opcode, op1: php.Value, op2: php.Value) !php.Value {
    const self = try op1.getCustom(@This());
    const other = try op2.getCustom(@This());
    const output = switch (opcode) {
        .bitwise_and => try self.bitmap.@"and"(php.allocator, other.bitmap),
        .bitwise_or => try self.bitmap.@"or"(php.allocator, other.bitmap),
        .bitwise_xor => try self.bitmap.xor(php.allocator, other.bitmap),
        else => return error.IllegalOperation,
    };
    const result: @This() = .{ .bitmap = output };
    return .createFromStruct(result, .{});
}

We use Value.getCustom() to obtain instances of our bitmap class. Value.createFromStruct(), meanwhile, creates an object from the given struct. We use it to return the result from zroaring's and, or, and xor functions.

For testing our new code:

<?php

use zig\roaring\Bitmap;

$bm1 = new Bitmap([ 1, 3, 5, 7, 9 ]);
$bm2 = new Bitmap([ 1, 2, 3, 4, 5 ]);
print_r($bm1 & $bm2);
print_r($bm1 | $bm2);
print_r($bm1 ^ $bm2);
zig\roaring\Bitmap Object
(
    [1] => 1
    [3] => 1
    [5] => 1
)
zig\roaring\Bitmap Object
(
    [1] => 1
    [2] => 1
    [3] => 1
    [4] => 1
    [5] => 1
    [7] => 1
    [9] => 1
)
zig\roaring\Bitmap Object
(
    [2] => 1
    [4] => 1
    [7] => 1
    [9] => 1
)

Freezing a roaring bitmap

Roaring bitmaps can be converted to a more optimized, "frozen" form that takes up less memory and is more performant. The frozen form must reside in properly aligned memory (required by SIMD CPU instructions) and is immutable. We'd need to "thaw" the bitmap first to make changes to it.

To enable freezing capability, we need to first add a field to our struct for storing the frozen bytes:

bitmap: zroaring.Bitmap,
frozen: ?[]align(zroaring.constants.BLOCK_ALIGN) u8 = null,

Then we implement freeze():

pub fn freeze(self: *@This()) !void {
    if (self.frozen != null) return;
    // optimize the data first
    if (try self.bitmap.run_optimize(php.allocator)) {
        _ = try self.bitmap.shrink_to_fit(php.allocator);
    }
    // allocate aligned memory for frozen representation
    const size = self.bitmap.frozen_size_in_bytes();
    const bytes = try php.allocator.alignedAlloc(u8, .fromByteUnits(zroaring.constants.BLOCK_ALIGN), size);
    errdefer php.allocator.free(bytes);
    // obtain the frozen form
    try self.bitmap.frozen_serialize(bytes);
    // create a new bitmap based on the frozen data
    const new_bm: zroaring.Bitmap = try .frozen_view(php.allocator, bytes);
    // free the existing one
    self.bitmap.deinit(php.allocator);
    self.bitmap = new_bm;
    self.frozen = bytes;
}

And thaw():

pub fn thaw(self: *@This()) !void {
    if (self.frozen == null) return;
    // create mutatable copy
    const new_bm = try self.bitmap.@"or"(php.allocator, self.bitmap);
    // free the frozen bitmap and memory
    self.bitmap.deinit(php.allocator);
    php.allocator.free(self.frozen.?);
    self.bitmap = new_bm;
    self.frozen = null;
}

And make these two functions available in PHP with the following declarations:

pub const @"call freeze" = freeze;
pub const @"call thaw" = thaw;

At the same time, let us add a read-only "frozen" property to the bitmap:

pub fn @"get frozen"(self: *@This()) bool {
    return self.frozen != null;
}

Once a bitmap is frozen, its bytes are portable. The user can take these bytes, store them in a database, and recreate the same bitmap later. To make the frozen bytes accessible, we're going to implement the casting handler:

pub fn castObject(self: *@This(), kind: php.Value.Kind) !php.Value {
    return switch (kind) {
        .string => if (self.frozen) |bytes| .fromString(.create(bytes)) else error.NotFrozen,
        else => error.IllegalOperation,
    };
}

Now we need to modify our init function so that it would also accept a string. We do this by make its sole argument a union type:

pub fn init(args: struct {
    init: union(enum) {
        indices: []const u32,
        frozen: []const u8,
    } = .{ .indices = &.{} },
}) !@This() {
    switch (args.init) {
        .indices => |indices| {
            var bm: zroaring.Bitmap = .empty;
            _ = try bm.add_many(php.allocator, indices);
            return .{ .bitmap = bm };
        },
        .frozen => |frozen| {
            const bytes = try php.allocator.alignedAlloc(u8, .fromByteUnits(zroaring.constants.BLOCK_ALIGN), frozen.len);
            errdefer php.allocator.free(bytes);
            @memcpy(bytes, frozen);
            const bm: zroaring.Bitmap = try .frozen_view(php.allocator, bytes);
            return .{ .bitmap = bm, .frozen = bytes };
        },
    }
}

Before we forget, we need to free the memory in deinit():

pub fn deinit(self: *@This()) void {
    self.bitmap.deinit(php.allocator);
    if (self.frozen) |bytes| php.allocator.free(bytes);
}

And we need to add a line in writeDimension() to prevent it from modifying a frozen bitmap:

pub fn writeDimension(self: *@This(), key: php.Value, value: php.Value) !void {
    if (self.frozen != null) return error.Frozen;
    // ...
}

Putting in the finishing touch

We're nearly done. As a finishing touch, we're going to implement the compareWith handler so that the user can check if two bitmaps are the same:

pub fn compareWith(self: *@This(), other_value: php.Value) !c_int {
    const other = try other_value.getCustom(@This());
    return if (self.bitmap.equals(other.bitmap))
        0
    else if (@intFromPtr(self) < @intFromPtr(other))
        -1
    else
        1;
}

The function is expected to return the same set of values as PHP's "UFO" operator: -1, 0, 1. Since in our case only 0 makes logical sense, we resort to a nonsensical pointer comparison when the two don't match for consistency sake.

Conclusion

I hope you managed to follow the code without problem. If you have any question, feel free to ask me in the discussion section. With the help of Zig, creating a PHP extension is very easy. The possibilities it opens up are endless. This is well worth looking into.

When a module is written in Zig, it tends to be easier to use. Zig is designed to also work with C libraries. Many have been specifically packaged to work with the Zig compiler. Visit the GitHub page of the All You Codebase project too see what's available.

Clone this wiki locally