Learning Zig from the official language reference.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

80 lines
1.8 KiB

const std = @import("std");
const debug = std.debug;
const testing = std.testing;
test "@bitCast" {
var x1: u32 = 42;
var x2 = @bitCast(i32, x1);
testing.expectEqual(x2, 42);
// reequires @sizeOf(type1) == @sizeOf(type2)
//var x3: u16 = @bitCast(u16, x1);
}
test "@alignCast" {
var ptr: *u32 align(@alignOf(u32)) = undefined;
var ptr_aligned = @alignCast(2, ptr);
testing.expectEqual(@typeInfo(@TypeOf(ptr_aligned)).Pointer.alignment, 2);
}
test "@boolToInt" {
testing.expectEqual(@boolToInt(false), 0);
testing.expectEqual(@boolToInt(true), 1);
}
test "@enumToInt" {
const E = enum(u32) {
one = 123,
two = 213,
three = 99,
};
testing.expectEqual(@enumToInt(E.one), 123);
testing.expectEqual(@enumToInt(E.two), 213);
testing.expectEqual(@enumToInt(E.three), 99);
}
test "@errSetCast" {
const E1 = error{ Foo, Bar, Baz };
const E2 = error{ Foo, Baz };
const e1: E1 = E1.Baz;
const e2: E2 = @errSetCast(E2, e1);
// this does not work, of course
// const e11: E1 = E1.Bar;
// const e22: E2 = @errSetCast(E1, e11);
}
test "@floatCast" {
var x1: f64 = 1.2345;
var x2: f32 = @floatCast(f32, x1);
}
test "@floatToInt" {
var x1: f32 = 123.2345;
var x2: u32 = @floatToInt(u32, x1);
debug.print("{}\n", .{x2});
}
test "@intCast" {
var x1: i128 = 54321;
var x2: u32 = @intCast(u32, x1);
testing.expectEqual(x1, x2);
}
test "@intToEnum" {
const E = enum { one, two, three };
const e1 = @intToEnum(E, 0);
testing.expectEqual(E.one, e1);
const e2 = @intToEnum(E, 1);
testing.expectEqual(E.two, e2);
const e3 = @intToEnum(E, 2);
testing.expectEqual(E.three, e3);
}
test "@ptrCast" {
var p1: *const i32 = &@as(i32, 100);
var p2 = @ptrCast(*const i16, p1);
testing.expectEqual(p1.*, p2.*);
}