Advertisement
Guest User

Untitled

a guest
Jun 29th, 2025
32
0
13 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 2.15 KB | None | 0 0
  1. const std = @import("std");
  2.  
  3. const SlabError = error{
  4.     OutOfRange,
  5.     SlotOccupied,
  6.     EmptySlot,
  7.     RemoveEmptySlot,
  8. };
  9.  
  10. const SlabConfig = struct {
  11.     safe: bool = true,
  12.     dynamic: bool = true,
  13.     size: comptime_int,
  14. };
  15.  
  16. pub fn createSlab(comptime T: type, comptime cfg: SlabConfig) type {
  17.     return struct {
  18.         const Self = @This();
  19.         allocator: std.mem.Allocator,
  20.         data: []?T,
  21.  
  22.         pub fn init(allocator: ?std.mem.Allocator) !Self {
  23.             if (comptime cfg.dynamic) {
  24.                 if (allocator == null) @compileError("Allocator is required for dynamic slab.");
  25.                 const data = try allocator.?.alloc(?T, cfg.size);
  26.                 for (data) |*slot| slot.* = null;
  27.                 return Self{
  28.                     .allocator = allocator.?,
  29.                     // .data = comptime @as(&T, &[_]?T{null} ** cfg.size),
  30.                 };
  31.             } else {
  32.                 return Self{
  33.                     .allocator = undefined,
  34.                     .data = @memset(, elem),
  35.                 };
  36.             }
  37.         }
  38.  
  39.         inline fn checkOutOfRage(self: *Self, index: usize) !void {
  40.             if (cfg.safe and index >= self.data.len) return SlabError.OutOfRange;
  41.         }
  42.  
  43.         pub fn insertAt(self: *Self, index: usize, value: T) SlabError!void {
  44.             try checkOutOfRage(index);
  45.             if (self.data[index] != null) return SlabError.SlotOccupied;
  46.             self.data[index] = value;
  47.         }
  48.  
  49.         pub fn remove(self: *Self, index: usize) SlabError!void {
  50.             if (comptime cfg.safe and self.data[index] == null) return SlabError.RemoveEmptySlot;
  51.             self.data[index] = null;
  52.         }
  53.  
  54.         pub fn get(self: *Self, index: usize) SlabError!*T {
  55.             try checkOutOfRage(index);
  56.  
  57.             const maybe = self.data[index] orelse return SlabError.EmptySlot;
  58.             return &maybe;
  59.         }
  60.     };
  61. }
  62.  
  63. test "init" {
  64.     const Slab = createSlab(u32, .{ .dynamic = false, .size = 3000, .safe = false });
  65.     const slab = try Slab.init(null);
  66.     try slab.insertAt(2500, 25);
  67.     std.debug.print("{}\n", .{slab.get(2500)});
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement