generated from mg/zig-template
added SmolStr
This commit is contained in:
parent
650a824b16
commit
2116081424
6 changed files with 132 additions and 50 deletions
11
src/main.zig
11
src/main.zig
|
|
@ -1,11 +0,0 @@
|
|||
const std = @import("std");
|
||||
|
||||
pub fn main() !void {
|
||||
const stdout_file = std.io.getStdOut().writer();
|
||||
var bw = std.io.bufferedWriter(stdout_file);
|
||||
const stdout = bw.writer();
|
||||
|
||||
try stdout.print("Hello, World.\n", .{});
|
||||
|
||||
try bw.flush();
|
||||
}
|
||||
85
src/root.zig
85
src/root.zig
|
|
@ -1 +1,86 @@
|
|||
const std = @import("std");
|
||||
|
||||
pub const SmolStr = struct {
|
||||
pub const max_inline_len: usize = 22;
|
||||
|
||||
const Inner = union(enum) {
|
||||
inl: struct {
|
||||
len: u8,
|
||||
data: [22]u8,
|
||||
},
|
||||
heap: []const u8,
|
||||
};
|
||||
|
||||
inner: Inner,
|
||||
|
||||
pub fn init(alloc: std.mem.Allocator, s: []const u8) !SmolStr {
|
||||
if (s.len <= max_inline_len) {
|
||||
return initInline(s);
|
||||
}
|
||||
|
||||
const s_ = try alloc.dupe(u8, s);
|
||||
|
||||
const inner = Inner{
|
||||
.heap = s_,
|
||||
};
|
||||
|
||||
return .{ .inner = inner };
|
||||
}
|
||||
|
||||
pub fn initInline(s: []const u8) SmolStr {
|
||||
if (s.len > max_inline_len) {
|
||||
var buf: [1024]u8 = undefined;
|
||||
|
||||
var msg: []const u8 = undefined;
|
||||
|
||||
msg = std.fmt.bufPrint(&buf, "Tried to inline string \"{s}\" of len {}", .{ s, s.len }) catch |e| switch (e) {
|
||||
error.NoSpaceLeft => blk: {
|
||||
break :blk std.fmt.bufPrint(&buf, "Tried to inline string of len {}", .{s.len}) catch unreachable;
|
||||
},
|
||||
};
|
||||
|
||||
@panic(msg);
|
||||
}
|
||||
|
||||
var inner = Inner{ .inl = .{
|
||||
.len = @intCast(s.len),
|
||||
.data = undefined,
|
||||
} };
|
||||
|
||||
@memcpy(inner.inl.data[0..s.len], s);
|
||||
|
||||
return .{ .inner = inner };
|
||||
}
|
||||
|
||||
pub fn deinit(self: SmolStr, alloc: std.mem.Allocator) void {
|
||||
switch (self.inner) {
|
||||
.inl => {},
|
||||
.heap => |s| alloc.free(s),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn str(self: *const SmolStr) []const u8 {
|
||||
switch (self.inner) {
|
||||
.inl => |*inl| return inl.data[0..self.len()],
|
||||
.heap => |s| return s,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn len(self: SmolStr) usize {
|
||||
switch (self.inner) {
|
||||
.inl => |*inl| return inl.len,
|
||||
.heap => |s| return s.len,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn format(self: SmolStr, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
|
||||
_ = fmt;
|
||||
_ = options;
|
||||
|
||||
try writer.print("{s}", .{self.str()});
|
||||
}
|
||||
};
|
||||
|
||||
test {
|
||||
try std.testing.expectEqual(24, @sizeOf(SmolStr));
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue