Files
zig-experiments/src/main.zig
David Allemang 36f8b3d65b random testing
2024-03-04 16:18:06 -05:00

81 lines
2.2 KiB
Zig

const std = @import("std");
const json = @import("json");
fn concat(ally: std.mem.Allocator, u: []const u8, v: []const u8) ![]const u8 {
const res = try ally.alloc(u8, u.len + v.len);
@memcpy(res[0..u.len], u);
@memcpy(res[u.len .. u.len + v.len], v);
return res;
}
const Shape = union(enum) {
rect: struct { w: f32, h: f32 },
square: struct { s: f32 },
circle: struct { r: f32 },
};
fn show(shape: Shape) void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const all = gpa.allocator();
const text = json.toSlice(all, shape) catch unreachable;
defer all.free(text);
std.debug.print("shape: {s}\n", .{text});
// switch (shape) {
// Shape.rect => |r| std.debug.print("rect: {} x {}\n", .{ r.w, r.h }),
// Shape.square => |s| std.debug.print("square: {}\n", .{s.s}),
// Shape.circle => |c| std.debug.print("circle: {}\n", .{c.r}),
// }
}
const Point = struct {
x: i32,
y: i32,
};
pub fn main() !void {
var big_buf: [1 << 20]u8 = undefined; // 1 MB
var fixed = std.heap.FixedBufferAllocator.init(&big_buf);
const ally = fixed.allocator();
var s: Shape = Shape{ .circle = .{ .r = 99 } };
show(s);
s = Shape{ .rect = .{ .w = 1, .h = 2 } };
show(s);
const val = Point{ .x = 1, .y = 2 };
const ser = try json.toSlice(ally, val);
defer ally.free(ser);
std.debug.print("{s}\n", .{ser});
const deser = try json.fromSlice(ally, Point, ser);
std.debug.print("{any}\n", .{deser});
var hash_map = std.StringArrayHashMap([]const u8).init(ally);
defer hash_map.deinit();
try hash_map.put("foo", "bar");
try hash_map.put("fizz", "buzz");
try hash_map.put("qux", "quxx");
const x = try concat(ally, hash_map.get("fizz").?, hash_map.get("foo").?);
defer ally.free(x);
std.debug.print("x={s}\n", .{x});
var iter = hash_map.iterator();
while (iter.next()) |it| {
std.debug.print("{s} {s}\n", .{ it.key_ptr.*, it.value_ptr.* });
}
}
test concat {
const x = "hello";
const y = "world";
const z = try concat(std.testing.allocator, x, y);
defer std.testing.allocator.free(z);
try std.testing.expectEqualStrings(z, "helloworld");
}