lib/zen/src/site/page/plan.zig

daab053ee43316e1809a84551d573ddd1e5bf3d2

 1 const std = @import("std");
 2 
 3 const model = @import("model.zig");
 4 
 5 pub const Limits = struct {
 6     max_page_bytes: usize,
 7 };
 8 
 9 pub const Plan = struct {
10     max_page_bytes: usize = 0,
11 
12     pub fn inspect(file_bytes: u64, limits: Limits) model.Error!Plan {
13         var plan: Plan = .{};
14         try plan.observe(file_bytes, limits);
15         return plan;
16     }
17 
18     pub fn observe(self: *Plan, file_bytes: u64, limits: Limits) model.Error!void {
19         const exact = std.math.cast(usize, file_bytes) orelse
20             return error.SitePageCapacityExceeded;
21         if (exact > limits.max_page_bytes) return error.SitePageCapacityExceeded;
22         self.max_page_bytes = @max(self.max_page_bytes, exact);
23     }
24 
25     pub fn exactLimits(self: Plan) Limits {
26         return .{ .max_page_bytes = self.max_page_bytes };
27     }
28 };
29 
30 test "site page plan preserves the largest admitted file" {
31     var plan: Plan = .{};
32     try plan.observe(7, .{ .max_page_bytes = 11 });
33     try plan.observe(11, .{ .max_page_bytes = 11 });
34     try plan.observe(3, .{ .max_page_bytes = 11 });
35     try std.testing.expectEqual(Limits{ .max_page_bytes = 11 }, plan.exactLimits());
36 }
37 
38 test "site page plan rejects max plus one before mutation" {
39     var plan = try Plan.inspect(17, .{ .max_page_bytes = 17 });
40     try std.testing.expectError(
41         error.SitePageCapacityExceeded,
42         plan.observe(18, .{ .max_page_bytes = 17 }),
43     );
44     try std.testing.expectEqual(Limits{ .max_page_bytes = 17 }, plan.exactLimits());
45     if (@sizeOf(usize) < @sizeOf(u64)) {
46         try std.testing.expectError(
47             error.SitePageCapacityExceeded,
48             Plan.inspect(@as(u64, std.math.maxInt(usize)) + 1, .{
49                 .max_page_bytes = std.math.maxInt(usize),
50             }),
51         );
52     }
53 }