zig/test/cases/cast.zig

67 lines
1.7 KiB
Zig
Raw Normal View History

2017-01-05 00:57:48 -08:00
const assert = @import("std").debug.assert;
const mem = @import("std").mem;
2016-12-21 22:42:30 -08:00
test "intToPtrCast" {
2017-01-05 00:57:48 -08:00
const x = isize(13);
const y = (&u8)(x);
const z = usize(y);
assert(z == 13);
2016-12-21 22:42:30 -08:00
}
test "numLitIntToPtrCast" {
const vga_mem = (&u16)(0xB8000);
assert(usize(vga_mem) == 0xB8000);
}
test "pointerReinterpretConstFloatToInt" {
const float: f64 = 5.99999999999994648725e-01;
const float_ptr = &float;
const int_ptr = @ptrcast(&i32, float_ptr);
const int_val = *int_ptr;
assert(int_val == 858993411);
}
test "implicitly cast a pointer to a const pointer of it" {
var x: i32 = 1;
const xp = &x;
funcWithConstPtrPtr(xp);
assert(x == 2);
}
fn funcWithConstPtrPtr(x: &const &i32) {
**x += 1;
}
error ItBroke;
test "explicit cast from integer to error type" {
testCastIntToErr(error.ItBroke);
comptime testCastIntToErr(error.ItBroke);
}
fn testCastIntToErr(err: error) {
const x = usize(err);
const y = error(x);
assert(error.ItBroke == y);
}
test "peer resolve arrays of different size to const slice" {
assert(mem.eql(u8, boolToStr(true), "true"));
assert(mem.eql(u8, boolToStr(false), "false"));
comptime assert(mem.eql(u8, boolToStr(true), "true"));
comptime assert(mem.eql(u8, boolToStr(false), "false"));
}
fn boolToStr(b: bool) -> []const u8 {
if (b) "true" else "false"
}
test "peer resolve array and const slice" {
testPeerResolveArrayConstSlice(true);
comptime testPeerResolveArrayConstSlice(true);
}
fn testPeerResolveArrayConstSlice(b: bool) {
const value1 = if (b) "aoeu" else ([]const u8)("zz");
const value2 = if (b) ([]const u8)("zz") else "aoeu";
assert(mem.eql(u8, value1, "aoeu"));
assert(mem.eql(u8, value2, "zz"));
}