From 10048b0d31d0db923ae39c6bbd67139ed6252f6f Mon Sep 17 00:00:00 2001 From: Sam Atman Date: Wed, 30 Apr 2025 20:30:39 -0400 Subject: Allocation Failure Tests These turned up an excessive amount of allocations in CanonData and CompatData, which have been reduced to two through the somewhat squirrely use of 'magic numbers'. There are now allocation tests for every allocated structure in the library, and they run to completion in a reasonable amount of time. So, that's nice. --- src/CompatData.zig | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'src/CompatData.zig') diff --git a/src/CompatData.zig b/src/CompatData.zig index d787103..794abca 100644 --- a/src/CompatData.zig +++ b/src/CompatData.zig @@ -1,6 +1,7 @@ //! Compatibility Data nfkd: [][]u21 = undefined, +cps: []u21 = undefined, const CompatData = @This(); @@ -15,27 +16,35 @@ pub fn init(allocator: mem.Allocator) !CompatData { var cpdata = CompatData{ .nfkd = try allocator.alloc([]u21, 0x110000), }; + { + errdefer allocator.free(cpdata.nfkd); + cpdata.cps = try allocator.alloc(u21, magic.compat_size); + } errdefer cpdata.deinit(allocator); @memset(cpdata.nfkd, &.{}); + var total_len: usize = 0; + while (true) { const len: u8 = try reader.readInt(u8, endian); if (len == 0) break; const cp = try reader.readInt(u24, endian); - cpdata.nfkd[cp] = try allocator.alloc(u21, len - 1); + const nk_s = cpdata.cps[total_len..][0 .. len - 1]; for (0..len - 1) |i| { - cpdata.nfkd[cp][i] = @intCast(try reader.readInt(u24, endian)); + nk_s[i] = @intCast(try reader.readInt(u24, endian)); } + cpdata.nfkd[cp] = nk_s; + total_len += len - 1; } + if (comptime magic.print) std.debug.print("CompatData magic number: {d}", .{total_len}); + return cpdata; } pub fn deinit(cpdata: *const CompatData, allocator: mem.Allocator) void { - for (cpdata.nfkd) |slice| { - if (slice.len != 0) allocator.free(slice); - } + allocator.free(cpdata.cps); allocator.free(cpdata.nfkd); } @@ -48,3 +57,4 @@ const std = @import("std"); const builtin = @import("builtin"); const compress = std.compress; const mem = std.mem; +const magic = @import("magic"); -- cgit v1.2.3