Skip to content

Instantly share code, notes, and snippets.

@nothke
Last active October 20, 2023 19:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nothke/02faf82b57e292e178069875de108ebd to your computer and use it in GitHub Desktop.
Save nothke/02faf82b57e292e178069875de108ebd to your computer and use it in GitHub Desktop.
Zig code I wrote on stream to show some cool features
const std = @import("std");
const DivisionError = error{
DivisionByZero,
OperandIsNan,
};
fn divide(a: f32, b: f32) DivisionError!f32 {
if (b == 0) {
return DivisionError.DivisionByZero;
} else if (std.math.isNan(a) or std.math.isNan(b)) {
return DivisionError.OperandIsNan;
}
return a / b;
}
const StructToPassIntoFunction = struct { i32, i32 };
fn funWithStruct(str: StructToPassIntoFunction) void {
std.log.info("str: {}, {}", .{ str.@"0", str.@"1" });
}
fn scale(vec: anytype, scalar: f32) @TypeOf(vec) {
return vec * @as(@TypeOf(vec), @splat(scalar));
}
pub fn main() !void {
{
std.log.info("Array for loop:", .{});
var array = [_]i32{ 1, 2, 3, 4, 5 };
for (&array) |*element| {
element.* = 10;
std.log.info("element is: {}", .{element.*});
}
}
{
std.log.info("Iterate index:", .{});
for (0..10) |i| {
std.log.info("i: {}", .{i});
}
}
{
var array = [_]i32{ 1, 2, 3, 4, 5, 1, 2, 3 };
var array2 = [_]i32{ 9, 5, 6, 7, 2, 3, 4, 5, 4, 5, 6 };
for (array, array2[0..array.len], 0..array.len) |e1, *e2, i| {
e2.* = e1 * 2;
std.log.info("for i: {} array: {}, array2: {}", .{ i, e1, e2.* });
}
}
{
std.log.info("Optionals:", .{});
var a: i32 = 4;
_ = a;
var b: ?i32 = 5;
//const c: i32 = if (b) |value| value else 0;
const c: i32 = b orelse 0;
//const c: i32 = b.?;
std.log.info("c: {}", .{c});
if (b != null) {
std.log.info("b exists!", .{});
} else {
std.log.info("b is null :'(", .{});
}
std.log.info("if with optional capture!", .{});
if (b) |value| {
std.log.info("b exists! And is: {}", .{value});
} else {
std.log.info("b is null :'(", .{});
}
}
{
std.log.info("pointers*", .{});
var a: i32 = 42;
var aPtr = &a;
aPtr.* = 12;
std.log.info("a: {}", .{a});
const StructWithPointer = struct {
ptr: ?*i32 = null,
};
var str = StructWithPointer{ .ptr = &a };
std.log.info("str value: {}", .{str.ptr.?.*});
var aPtr4: [*c]i32 = &a;
std.log.info("{} = {}", .{ aPtr.*, aPtr4[0] });
var arr = [_]i32{ 1, 2, 3, 4, 6 };
var arrPtr: [*]i32 = &arr;
var arrPtrC: [*c]i32 = &arr;
std.log.info("many pointer: {}, c like: {}", .{ arrPtr[0], arrPtrC.* });
}
{
std.log.info("impossible node", .{});
const Node = struct {
const Self = @This();
parent: ?*Self = null,
child: ?*Self = null,
text: []const u8 = "default",
};
var topNode = Node{ .text = "TOP" };
var betweenNode = Node{ .parent = &topNode, .text = "middle :'(" };
var lowerNode = Node{ .parent = &betweenNode, .text = "lower" };
topNode.child = &betweenNode;
betweenNode.child = &lowerNode;
var nextChild: ?*Node = &topNode;
while (nextChild) |nextChildPtr| {
std.log.info("next child is: {s}", .{nextChildPtr.*.text});
nextChild = nextChildPtr.child;
} else {
std.log.info("Reached end of tree!", .{});
}
}
{
std.log.info("Errors!", .{});
const MyError = error{
NumberError,
};
var a: i32 = 42;
_ = a;
var aWithError: MyError!i32 = 42;
const b = try aWithError;
_ = b;
const c = aWithError catch 0;
_ = c;
var division = try divide(12, 12);
std.log.info("division result: {d:.2}", .{division});
}
{
std.log.info("Heap allocataors!", .{});
var alloc = std.heap.page_allocator;
var intPtr = try alloc.create(i32);
intPtr.* = 42;
std.log.info("my heap allocated int is: {}", .{intPtr.*});
}
{
//std::vector<int>
const alloc = std.heap.page_allocator;
var list = std.ArrayList(i32).init(alloc);
//defer list.deinit();
try list.append(4);
try list.append(9);
try list.append(31);
_ = list.swapRemove(0);
_ = list.pop();
for (list.items) |value| {
std.log.info("list value: {}", .{value});
}
} // this is where list gets deinited()!
{
std.log.info("NO ctors/dtors\n", .{});
const MyStruct = struct {
number: i32 = 0,
text: []const u8 = "default",
const Self = @This();
const Error = error{NotAnEvenNumber};
fn init(self: *Self, numberToHalve: i32) !void {
if (@mod(numberToHalve, @as(i32, 2)) == 1)
return Error.NotAnEvenNumber;
self.*.number = @divTrunc(numberToHalve, 2);
}
fn deinit(self: *Self) void {
self.*.number = 0;
}
fn log(self: Self) void {
std.log.info("str, num: {}, text: {s}", .{ self.number, self.text });
}
};
var str = MyStruct{ .text = "something else" };
try str.init(12);
defer str.deinit();
str.log();
MyStruct.log(str);
}
{
var buffer: [64]u8 = undefined;
var alloc = std.heap.FixedBufferAllocator.init(&buffer);
{
var list = std.ArrayList(i32).init(alloc.allocator());
defer list.deinit();
try list.append(3);
try list.append(5);
try list.append(67);
for (list.items) |value| {
std.log.info("fixed buffer list value: {}", .{value});
}
}
//alloc.allocator().create(i32);
}
{
std.log.info("GPA\n", .{});
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const alloc = gpa.allocator();
defer _ = gpa.deinit();
{
var list = std.ArrayList(i32).init(alloc);
defer list.deinit();
try list.append(3);
try list.append(5);
try list.append(67);
for (list.items) |value| {
std.log.info("fixed buffer list value: {}", .{value});
}
}
var aPtr = try alloc.create(i32);
defer alloc.destroy(aPtr);
aPtr.* = 10;
}
{
std.log.info("No operator overloads!", .{});
const Vec3 = struct {
x: f32,
y: f32,
const Self = @This();
fn dot(self: Self, other: Self) f32 {
return self.x * other.x + self.y * other.y;
}
};
var vec1 = Vec3{ .x = 1, .y = 2 };
var vec2 = vec1;
const dotProduct = vec1.dot(vec2);
std.log.info("dotProduct: {}", .{dotProduct});
}
{
funWithStruct(.{ 1, 3 });
var thing = .{ .a = 3, .b = 3 };
_ = thing;
}
{
const a: f32 = 12;
const b: f32 = 13;
std.log.info("sum: {d:.2}", .{a + b});
const Vec3 = @Vector(3, f32);
const vec1 = Vec3{ 1, 2, 3 };
const vec2 = Vec3{ 3, 2, 1 };
const vec3 = @Vector(4, f32){ 1, 2, 3, 4 };
_ = vec3;
const resultVec = vec1 + vec2;
std.log.info("resultVec: {d:.1}", .{resultVec});
const vec4: Vec3 = @splat(1);
const vecReduced = @reduce(std.builtin.ReduceOp.Add, vec4);
std.log.info("vec4: {d:.1}, {d:.1}", .{ vec4, vecReduced });
const scaledVec4 = vec4 * @as(Vec3, @splat(100));
std.log.info("scaledVec4: {d:.1}", .{scaledVec4});
std.log.info("scaledVec: {}", .{scale(scaledVec4, 4)});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment