So I was reading about the German String optimization (the one that is impossible in Rust, btw). And I think I came up with something nice. What do you guys think? What would you add?
pub const String = packed struct {
len: u32,
payload: packed union {
content: @Vector(12, u8),
heap: packed struct { prefix: @Vector(4, u8), ptr: [*]u8 },
},
pub fn format(
self: String,
writer: *std.Io.Writer,
) std.Io.Writer.Error!void {
if (self.len <= 12) {
const content: [12]u8 = self.payload.content;
try writer.print("{s}", .{content[0..self.len]});
} else try writer.print("{s}", .{self.payload.heap.ptr[0..self.len]});
}
pub fn init(
alloc: std.mem.Allocator,
s: []const u8,
) std.mem.Allocator.Error!String {
const len: u32 = @truncate(s.len);
if (len <= 12) {
var content: [12]u8 = @splat(0);
@memcpy(content[0..len], s);
return .{ .len = len, .payload = .{ .content = content } };
} else {
var prefix: [4]u8 = @splat(0);
@memcpy(&prefix, s[0..4]);
return .{ .len = len, .payload = .{
.heap = .{
.prefix = prefix,
.ptr = (try alloc.dupe(u8, s)).ptr,
},
} };
}
}
pub fn deinit(
self: *String,
alloc: std.mem.Allocator,
) void {
defer self.len = 0;
if (self.len > 12) alloc.free(self.payload.heap.ptr[0..self.len]);
}
pub fn eql(
lhs: String,
rhs: String,
) bool {
if (lhs.len != rhs.len) return false;
if (lhs.len <= 12)
return @reduce(
.And,
lhs.payload.content == rhs.payload.content,
);
if (@reduce(
.Or,
lhs.payload.heap.prefix != rhs.payload.heap.prefix,
))
return false;
const len = lhs.len;
return std.mem.eql(
u8,
lhs.payload.heap.ptr[0..len],
rhs.payload.heap.ptr[0..len],
);
}
pub fn copy_to_bytes(
self: String,
alloc: std.mem.Allocator,
) std.mem.Allocator.Error![]const u8 {
return std.fmt.allocPrint(alloc, "{f}", .{self});
}
};
edit: fixed a bug in the quality function !! not false results, just more work than necessary.