flexible.Struct - a FlexibleStruct/Array alternative

flexible.Struct

Hello. I’m hoping for some feedback on this alternative to the FlexibleStruct/FlexibleArray pull request. Its similar but adds lots of stuff like a user Layout API, size and offset helpers and additions to the Self API (value(), ptr(), slice(), sliceField(), sliceLen()).

I haven’t benchmarked it yet :sweat_smile: but its designed to be faster than the orignal with flexible fields after Layout fields and sorted by alignment. WIth this, we can simd prefix sum the aligned sizes in constant time. It does trade some possible padding after Layout for this so beware.

I’ve been using it in my toy roaring bitmap project and it seems pretty decent so far. Lots of things I want to do including moving the repo to Codeberg. But give it a try. We can make small and fast designs with flexible arrays.

I’m hoping for criticism to improve this including the decision to add computed methods (which may be slower than fixed field access) and the additional padding tradeoff. I’m considering turning this into an alternative to the zig FlexibleStruct PR above since it sounds like Andrew is interested in getting something merged.

@tristanpemble I’m interested to hear from original author and maybe work together toward getting something merged. Let me know if you have a minute. I’ve also commented on that issue as archaistvolts. Thanks for the original! I love the idea.



flexible.Struct


A single buffer layout library for structs with flexible fields.

About

User defined Layout fields are first in memory with order determined by Zig. Flexible fields are second and sorted by descending alignment. With no padding, flexible offsets can be calculated in constant time (see calcOffsets()).

Features

  1. Support all structs: auto, extern, packed
  2. Constant time field access.
  3. APIs: Layout, Self and bytes. Users can ptrCast between them.
  4. Computed fields.
  5. LSP cooperation. Avoid created/refified types which break autocomplete.

Docs

Usage

Add a pub const flexible_array_capacities decl to your Layout which maps flexible array fields to their capacities.

const Layout = struct {
        capacity: u8,
        flexible: [*]u8 = undefined,
        computed: [*]u8 = undefined,

        pub const flexible_array_capacities = .{
            .flexible = .capacity,
            .computed = .computedLen,
        };

        pub fn computedLen(_: *const @This()) usize {
            return 68;
        }
    };

    const Model = Struct(Layout, .{});
    const initlayout = Layout{ .capacity = 42 };
    var buf: Model.Buf(&initlayout) align(Model.ALIGN) = undefined; // buffer must be aligned
    const model = try Model.initBuffer(&buf, &initlayout);
    try testing.expectEqual(42, model.value(.capacity));
    try testing.expectEqual(42, model.slice(.flexible).len);
    try testing.expectEqual(42, model.asLayout().capacity); // Self <-> Layout
    try testing.expectEqual(42, Model.fromLayout(model.asLayout()).value(.capacity));
    try testing.expectEqual(68, model.slice(.computed).len);
    try testing.expectEqual(136, model.sizeInBytes()); // 24+42+68(~8)=134(~8)=136
}

Supported Zig versions

0.16. 0.17 coming soon.

3 Likes

I’d be interested to know more about your specific use case. When I made the original thing, I was messing around and theorizing about comptime stuff without ever using it in anything. I think Andrew asked me to PR it cause he kept wanting something when working on std.Io.

I do remember that it became clear to me that the decision on whether or not to support the ABI use cases were key to reigning in the complexity of the solution. features like you’ve built for computed lengths, precise positioning, etc are great for that kind of ABI/(de)serialization but I felt might not be worth generalizing for the “I want to shove data into a flat buffer” type of use case I remember were in the standard library.

however, it sounds like you built it cause you needed it, which is great. I prefer solutions built for real problems! :slight_smile: I would love to hear more about yours.

1 Like

I’ve been using it in my toy roaring bitmap project. I did try something more similar to the original FlexibleStruct in my CRoaring port, zroaring. But dropped it for a ~10% perf improvement using cached flexible pointer fields. Its possible I wasn’t using the FlexibleStruct API optimally. Like maybe I needed to better cache slice(.field) results. I did try but ended up skeptical of the inline alignForward loop in offsetOf() at the time.

So this design is meant to overcome that performance difference. My use case is very similar to zroaring’s with the following flexible data structures. Its a compressed a bitmap representation similar to a roaring bitmap but with a single container type storing words interpreted as array, bitset, or run instead of roaring’s array, bitset and run container types.

In zroaring I found keeping the Container metadata and data together in memory to be a perf win. So I’m doing something similar here.

        const HiLoModel = flexible.Struct(HiLo, .{ .Size = usize });

        const HiLo = struct {
            len: HiCardinality,
            capacity: HiCardinality,
            keys: [*]Hi,
            containers: [*]Container,
            allocation_size: usize,

            pub const flexible_array_capacities = .{
                .keys = .capacity,
                .containers = .capacity,
            };

        };

        const ContainerModel = flexible.Struct(Container, .{});
        const Tag = enum(u2) { unset, array, bitset, run };
        const Tag4 = packed struct { _0: Tag, _1: Tag, _2: Tag, _3: Tag };
        const Word = u64;
        const HalfWord = u32;
        const Wordx = extern union {
            array: WordLosArr,
            bitset: Word,
            run: packed struct(Word) {
                start: HalfWord,
                length: HalfWord,
            },
        };

        pub const Container = struct {
            tags: [*]Tag4 = undefined,
            words: [*]Wordx = undefined,
            wordslen: LoCardinality,
            wordscapacity: LoCardinality,
            cardinality: LoCardinality,

            pub const flexible_array_capacities = .{ .words = .wordscapacity, .tags = .tagsCapacity };

            pub fn tagsCapacity(c: *const Container) LoCardinality {
                return (c.wordscapacity + 3) / 4;
            }
        };

I’ve attempted to solve this by putting the Layout first in memory (with zig handling ordering) and flexible fields afterward. I’m not certain, but think this is a valid way to support extern and packed layouts. It may add padding before flexible fields but thats a tradeoff I’m happy with. I feel like it doesn’t add much complexity and pays off in with fast offset calculations. I haven’t done benchmarking yet :sweat_smile: but I feel like limiting offset calculations to flexible fields and doing a SIMD prefix sum should usually win. Maybe my calcOffsets() would suffer given many flexible fields, not sure.

I’ll try to make a benchmark script soon and share results either here or in the ‘add FlexibleStruct’ PR on codeberg.

Let me know if you have any questions about my use case, the implementation, or thoughts on possibly using some of these ideas in a std PR.

EDIT:

Interesting. Maybe in Io.Writer? Curious to learn more about the original use case and how FlexibleStruct addressed it. I’ve thought an interesting use case might be a flexible ArrayList, with user len/capacity types to reduce size. But not sure about adding yet another type param.

Main branch is updated to 0.17.0. I’ve created a zig-0.16.0 branch. I’ve added some new methods too:

    add grow/shrinkCapacities, moveField

    - previously only copyField, copy existed
    - add writeFlexibleOffsets and initCapacitiesPinned

I needed shrinkCapacities in my roaring bitmap project.

I’ve demo’d them in the doc test too:

test Struct {
    const Layout = struct {
        capacity: u8,
        flexible: [*]u8 = undefined,
        computed: [*]u8 = undefined,

        pub const flexible_array_capacities = .{
            .flexible = .capacity,
            .computed = .computedLen,
        };

        pub fn computedLen(_: *const @This()) usize {
            return 68;
        }
    };

    const Model = Struct(Layout, .{});
    const initlayout = Layout{ .capacity = 42 };
    var buf: Model.Buf(&initlayout) align(Model.ALIGN) = undefined; // buffer must be aligned
    const model = try Model.initBuffer(&buf, &initlayout);
    try testing.expectEqual(42, model.value(.capacity));
    try testing.expectEqual(42, model.slice(.flexible).len);
    try testing.expectEqual(42, model.asLayout().capacity); // Self <-> Layout
    try testing.expectEqual(42, Model.fromLayout(model.asLayout()).value(.capacity));
    try testing.expectEqual(68, model.slice(.computed).len);
    try testing.expectEqual(136, model.sizeInBytes()); // (24+42+68)~8=134~8=136

    // change capacities then check last field (computed) has moved and retains values
    @memset(model.slice(.computed), 69);
    const computed1 = model.value(.computed);
    model.shrinkCapacities(&.{ .capacity = 36 }); // shrink and move
    try testing.expectEqual(128, model.sizeInBytes()); // (24+36+68)~8=128~8=128
    const computed2 = model.value(.computed);
    try testing.expectEqual(69, model.slice(.computed)[0]);
    try testing.expectEqual(69, model.slice(.computed)[35]);
    try testing.expectEqual(computed1 - 6, computed2);
    model.growCapacities(&.{ .capacity = 48 }); // grow and move
    try testing.expectEqual(144, model.sizeInBytes()); // (24+48+68)~8=140~8=144
    try testing.expectEqual(69, model.slice(.computed)[0]);
    try testing.expectEqual(69, model.slice(.computed)[35]);
    try testing.expectEqual(computed1 + 6, model.value(.computed));
}

I’ve been thinking about ways to simplify the API and hoping for suggestions. Currently there are 4 APIs: Capacities (Lengths), Self, Layout and bytes. The original, FlexibleStruct, includes Capacities and Self but I find Layout and Capacities to be the most essential. So I’m a little torn.

Put another way, what should be removed? The Self API is my leading candidate for removal. But it has convenient method call syntax. On the other hand, I’ve found that it leads to code where you have 2 bindings, a *Layout and a *Struct(Layout) which isn’t great. Maybe its necessary though? Help! :joy:

I’ve also compiled these TODOS. Sharing here in case anyone has any thoughts or wants to work on them.

TODOS - IDEAS

  • Options
    • user overrides for methods such as calcOffsets.
  • reduce binary footprint
    • remove inline loops and comptime params.
  • de/serialization helpers.
  • when fixed padding is large enough for a ‘buffer_capacity’ Size, add a
    managed API with resize, resizeAssumeCapacity, resizeBounded and a hidden
    field helper.