Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const std = @import("std");
- const SlabError = error{
- OutOfRange,
- SlotOccupied,
- EmptySlot,
- RemoveEmptySlot,
- };
- const SlabConfig = struct {
- safe: bool = true,
- dynamic: bool = true,
- size: comptime_int,
- };
- pub fn createSlab(comptime T: type, comptime cfg: SlabConfig) type {
- return struct {
- const Self = @This();
- allocator: std.mem.Allocator,
- data: []?T,
- pub fn init(allocator: ?std.mem.Allocator) !Self {
- if (comptime cfg.dynamic) {
- if (allocator == null) @compileError("Allocator is required for dynamic slab.");
- const data = try allocator.?.alloc(?T, cfg.size);
- for (data) |*slot| slot.* = null;
- return Self{
- .allocator = allocator.?,
- // .data = comptime @as(&T, &[_]?T{null} ** cfg.size),
- };
- } else {
- return Self{
- .allocator = undefined,
- .data = @memset(, elem),
- };
- }
- }
- inline fn checkOutOfRage(self: *Self, index: usize) !void {
- if (cfg.safe and index >= self.data.len) return SlabError.OutOfRange;
- }
- pub fn insertAt(self: *Self, index: usize, value: T) SlabError!void {
- try checkOutOfRage(index);
- if (self.data[index] != null) return SlabError.SlotOccupied;
- self.data[index] = value;
- }
- pub fn remove(self: *Self, index: usize) SlabError!void {
- if (comptime cfg.safe and self.data[index] == null) return SlabError.RemoveEmptySlot;
- self.data[index] = null;
- }
- pub fn get(self: *Self, index: usize) SlabError!*T {
- try checkOutOfRage(index);
- const maybe = self.data[index] orelse return SlabError.EmptySlot;
- return &maybe;
- }
- };
- }
- test "init" {
- const Slab = createSlab(u32, .{ .dynamic = false, .size = 3000, .safe = false });
- const slab = try Slab.init(null);
- try slab.insertAt(2500, 25);
- std.debug.print("{}\n", .{slab.get(2500)});
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement