SIGN IN SIGN UP
2019-03-02 16:46:04 -05:00
const std = @import("std.zig");
const builtin = @import("builtin");
const math = std.math;
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
const print = std.debug.print;
pub const FailingAllocator = @import("testing/failing_allocator.zig").FailingAllocator;
/// This should only be used in temporary test programs.
pub const allocator = allocator_instance.allocator();
pub var allocator_instance = std.heap.GeneralPurposeAllocator(.{}){};
pub const failing_allocator = failing_allocator_instance.allocator();
pub var failing_allocator_instance = FailingAllocator.init(base_allocator_instance.allocator(), 0);
2020-01-29 13:18:04 -06:00
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
pub var base_allocator_instance = std.heap.FixedBufferAllocator.init("");
2020-01-29 13:18:04 -06:00
/// TODO https://github.com/ziglang/zig/issues/5738
pub var log_level = std.log.Level.warn;
/// This is available to any test that wants to execute Zig in a child process.
/// It will be the same executable that is running `zig test`.
pub var zig_exe_path: []const u8 = undefined;
/// This function is intended to be used only in tests. It prints diagnostics to stderr
/// and then aborts when actual_error_union is not expected_error.
2021-05-04 19:36:59 +03:00
pub fn expectError(expected_error: anyerror, actual_error_union: anytype) !void {
if (actual_error_union) |actual_payload| {
std.debug.print("expected error.{s}, found {any}\n", .{ @errorName(expected_error), actual_payload });
2021-05-04 19:36:59 +03:00
return error.TestUnexpectedError;
} else |actual_error| {
if (expected_error != actual_error) {
std.debug.print("expected error.{s}, found error.{s}\n", .{
@errorName(expected_error),
@errorName(actual_error),
});
2021-05-04 19:36:59 +03:00
return error.TestExpectedError;
}
}
}
/// This function is intended to be used only in tests. When the two values are not
/// equal, prints diagnostics to stderr to show exactly how they are not equal,
/// then aborts.
/// `actual` is casted to the type of `expected`.
2021-05-04 19:36:59 +03:00
pub fn expectEqual(expected: anytype, actual: @TypeOf(expected)) !void {
switch (@typeInfo(@TypeOf(actual))) {
2019-07-21 19:56:37 -04:00
.NoReturn,
.BoundFn,
.Opaque,
.Frame,
.AnyFrame,
=> @compileError("value of type " ++ @typeName(@TypeOf(actual)) ++ " encountered"),
2019-07-21 19:56:37 -04:00
.Undefined,
.Null,
.Void,
=> return,
.Type => {
if (actual != expected) {
std.debug.print("expected type {s}, found type {s}\n", .{ @typeName(expected), @typeName(actual) });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
},
2019-07-21 19:56:37 -04:00
.Bool,
.Int,
.Float,
.ComptimeFloat,
.ComptimeInt,
.EnumLiteral,
.Enum,
.Fn,
.ErrorSet,
=> {
if (actual != expected) {
std.debug.print("expected {}, found {}\n", .{ expected, actual });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
},
2019-07-21 19:56:37 -04:00
.Pointer => |pointer| {
switch (pointer.size) {
.One, .Many, .C => {
if (actual != expected) {
std.debug.print("expected {*}, found {*}\n", .{ expected, actual });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
},
separate std.Target and std.zig.CrossTarget Zig now supports a more fine-grained sense of what is native and what is not. Some examples: This is now allowed: -target native Different OS but native CPU, default Windows C ABI: -target native-windows This could be useful for example when running in Wine. Different CPU but native OS, native C ABI. -target x86_64-native -mcpu=skylake Different C ABI but otherwise native target: -target native-native-musl -target native-native-gnu Lots of breaking changes to related std lib APIs. Calls to getOs() will need to be changed to getOsTag(). Calls to getArch() will need to be changed to getCpuArch(). Usage of Target.Cross and Target.Native need to be updated to use CrossTarget API. `std.build.Builder.standardTargetOptions` is changed to accept its parameters as a struct with default values. It now has the ability to specify a whitelist of targets allowed, as well as the default target. Rather than two different ways of collecting the target, it's now always a string that is validated, and prints helpful diagnostics for invalid targets. This feature should now be actually useful, and contributions welcome to further improve the user experience. `std.build.LibExeObjStep.setTheTarget` is removed. `std.build.LibExeObjStep.setTarget` is updated to take a CrossTarget parameter. `std.build.LibExeObjStep.setTargetGLibC` is removed. glibc versions are handled in the CrossTarget API and can be specified with the `-target` triple. `std.builtin.Version` gains a `format` method.
2020-02-26 01:18:23 -05:00
.Slice => {
if (actual.ptr != expected.ptr) {
std.debug.print("expected slice ptr {*}, found {*}\n", .{ expected.ptr, actual.ptr });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
if (actual.len != expected.len) {
std.debug.print("expected slice len {}, found {}\n", .{ expected.len, actual.len });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
},
}
},
2021-05-04 19:36:59 +03:00
.Array => |array| try expectEqualSlices(array.child, &expected, &actual),
stage2: implement `@ctz` and `@clz` including SIMD AIR: * `array_elem_val` is now allowed to be used with a vector as the array type. * New instructions: splat, vector_init AstGen: * The splat ZIR instruction uses coerced_ty for the ResultLoc, avoiding an unnecessary `as` instruction, since the coercion will be performed in Sema. * Builtins that accept vectors now ignore the type parameter. Comment from this commit reproduced here: The accepted proposal #6835 tells us to remove the type parameter from these builtins. To stay source-compatible with stage1, we still observe the parameter here, but we do not encode it into the ZIR. To implement this proposal in stage2, only AstGen code will need to be changed. Sema: * `clz` and `ctz` ZIR instructions are now handled by the same function which accept AIR tag and comptime eval function pointer to differentiate. * `@typeInfo` for vectors is implemented. * `@splat` is implemented. It takes advantage of `Value.Tag.repeated` 😎 * `elemValue` is implemented for vectors, when the index is a scalar. Handling a vector index is still TODO. * Element-wise coercion is implemented for vectors. It could probably be optimized a bit, but it is at least complete & correct. * `Type.intInfo` supports vectors, returning int info for the element. * `Value.ctz` initial implementation. Needs work. * `Value.eql` is implemented for arrays and vectors. LLVM backend: * Implement vector support when lowering `array_elem_val`. * Implement vector support when lowering `ctz` and `clz`. * Implement `splat` and `vector_init`.
2022-01-12 23:53:26 -07:00
.Vector => |info| {
2020-01-07 19:14:37 +05:00
var i: usize = 0;
stage2: implement `@ctz` and `@clz` including SIMD AIR: * `array_elem_val` is now allowed to be used with a vector as the array type. * New instructions: splat, vector_init AstGen: * The splat ZIR instruction uses coerced_ty for the ResultLoc, avoiding an unnecessary `as` instruction, since the coercion will be performed in Sema. * Builtins that accept vectors now ignore the type parameter. Comment from this commit reproduced here: The accepted proposal #6835 tells us to remove the type parameter from these builtins. To stay source-compatible with stage1, we still observe the parameter here, but we do not encode it into the ZIR. To implement this proposal in stage2, only AstGen code will need to be changed. Sema: * `clz` and `ctz` ZIR instructions are now handled by the same function which accept AIR tag and comptime eval function pointer to differentiate. * `@typeInfo` for vectors is implemented. * `@splat` is implemented. It takes advantage of `Value.Tag.repeated` 😎 * `elemValue` is implemented for vectors, when the index is a scalar. Handling a vector index is still TODO. * Element-wise coercion is implemented for vectors. It could probably be optimized a bit, but it is at least complete & correct. * `Type.intInfo` supports vectors, returning int info for the element. * `Value.ctz` initial implementation. Needs work. * `Value.eql` is implemented for arrays and vectors. LLVM backend: * Implement vector support when lowering `array_elem_val`. * Implement vector support when lowering `ctz` and `clz`. * Implement `splat` and `vector_init`.
2022-01-12 23:53:26 -07:00
while (i < info.len) : (i += 1) {
2020-01-07 19:14:37 +05:00
if (!std.meta.eql(expected[i], actual[i])) {
stage2: implement `@ctz` and `@clz` including SIMD AIR: * `array_elem_val` is now allowed to be used with a vector as the array type. * New instructions: splat, vector_init AstGen: * The splat ZIR instruction uses coerced_ty for the ResultLoc, avoiding an unnecessary `as` instruction, since the coercion will be performed in Sema. * Builtins that accept vectors now ignore the type parameter. Comment from this commit reproduced here: The accepted proposal #6835 tells us to remove the type parameter from these builtins. To stay source-compatible with stage1, we still observe the parameter here, but we do not encode it into the ZIR. To implement this proposal in stage2, only AstGen code will need to be changed. Sema: * `clz` and `ctz` ZIR instructions are now handled by the same function which accept AIR tag and comptime eval function pointer to differentiate. * `@typeInfo` for vectors is implemented. * `@splat` is implemented. It takes advantage of `Value.Tag.repeated` 😎 * `elemValue` is implemented for vectors, when the index is a scalar. Handling a vector index is still TODO. * Element-wise coercion is implemented for vectors. It could probably be optimized a bit, but it is at least complete & correct. * `Type.intInfo` supports vectors, returning int info for the element. * `Value.ctz` initial implementation. Needs work. * `Value.eql` is implemented for arrays and vectors. LLVM backend: * Implement vector support when lowering `array_elem_val`. * Implement vector support when lowering `ctz` and `clz`. * Implement `splat` and `vector_init`.
2022-01-12 23:53:26 -07:00
std.debug.print("index {} incorrect. expected {}, found {}\n", .{
i, expected[i], actual[i],
});
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
2020-01-07 19:14:37 +05:00
}
}
},
2019-07-21 19:56:37 -04:00
.Struct => |structType| {
inline for (structType.fields) |field| {
2021-05-04 19:36:59 +03:00
try expectEqual(@field(expected, field.name), @field(actual, field.name));
}
},
2019-07-21 19:56:37 -04:00
.Union => |union_info| {
if (union_info.tag_type == null) {
@compileError("Unable to compare untagged union values");
}
const Tag = std.meta.Tag(@TypeOf(expected));
const expectedTag = @as(Tag, expected);
const actualTag = @as(Tag, actual);
2021-05-04 19:36:59 +03:00
try expectEqual(expectedTag, actualTag);
// we only reach this loop if the tags are equal
inline for (std.meta.fields(@TypeOf(actual))) |fld| {
if (std.mem.eql(u8, fld.name, @tagName(actualTag))) {
2021-05-04 19:36:59 +03:00
try expectEqual(@field(expected, fld.name), @field(actual, fld.name));
return;
}
}
// we iterate over *all* union fields
// => we should never get here as the loop above is
// including all possible values.
unreachable;
},
2019-07-21 19:56:37 -04:00
.Optional => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
2021-05-04 19:36:59 +03:00
try expectEqual(expected_payload, actual_payload);
} else {
std.debug.print("expected {any}, found null\n", .{expected_payload});
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
} else {
if (actual) |actual_payload| {
std.debug.print("expected null, found {any}\n", .{actual_payload});
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
}
},
2019-07-21 19:56:37 -04:00
.ErrorUnion => {
if (expected) |expected_payload| {
if (actual) |actual_payload| {
2021-05-04 19:36:59 +03:00
try expectEqual(expected_payload, actual_payload);
} else |actual_err| {
std.debug.print("expected {any}, found {}\n", .{ expected_payload, actual_err });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
} else |expected_err| {
if (actual) |actual_payload| {
std.debug.print("expected {}, found {any}\n", .{ expected_err, actual_payload });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
} else |actual_err| {
2021-05-04 19:36:59 +03:00
try expectEqual(expected_err, actual_err);
}
}
},
}
}
test "expectEqual.union(enum)" {
const T = union(enum) {
a: i32,
b: f32,
};
const a10 = T{ .a = 10 };
2021-05-04 19:36:59 +03:00
try expectEqual(a10, a10);
}
2021-01-11 20:30:43 -05:00
/// This function is intended to be used only in tests. When the formatted result of the template
/// and its arguments does not equal the expected text, it prints diagnostics to stderr to show how
/// they are not equal, then returns an error.
pub fn expectFmt(expected: []const u8, comptime template: []const u8, args: anytype) !void {
const result = try std.fmt.allocPrint(allocator, template, args);
defer allocator.free(result);
if (std.mem.eql(u8, result, expected)) return;
print("\n====== expected this output: =========\n", .{});
print("{s}", .{expected});
print("\n======== instead found this: =========\n", .{});
print("{s}", .{result});
print("\n======================================\n", .{});
2021-05-04 19:36:59 +03:00
return error.TestExpectedFmt;
2021-01-11 20:30:43 -05:00
}
/// This function is intended to be used only in tests. When the actual value is
/// not approximately equal to the expected value, prints diagnostics to stderr
/// to show exactly how they are not equal, then aborts.
/// See `math.approxEqAbs` for more informations on the tolerance parameter.
2020-06-23 18:05:32 +02:00
/// The types must be floating point
2021-05-04 19:36:59 +03:00
pub fn expectApproxEqAbs(expected: anytype, actual: @TypeOf(expected), tolerance: @TypeOf(expected)) !void {
const T = @TypeOf(expected);
switch (@typeInfo(T)) {
2021-05-04 19:36:59 +03:00
.Float => if (!math.approxEqAbs(T, expected, actual, tolerance)) {
std.debug.print("actual {}, not within absolute tolerance {} of expected {}\n", .{ actual, tolerance, expected });
2021-05-04 19:36:59 +03:00
return error.TestExpectedApproxEqAbs;
},
.ComptimeFloat => @compileError("Cannot approximately compare two comptime_float values"),
2020-06-23 18:05:32 +02:00
else => @compileError("Unable to compare non floating point values"),
}
}
test "expectApproxEqAbs" {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const pos_x: T = 12.0;
const pos_y: T = 12.06;
const neg_x: T = -12.0;
const neg_y: T = -12.06;
2020-06-23 18:05:32 +02:00
2021-05-04 19:36:59 +03:00
try expectApproxEqAbs(pos_x, pos_y, 0.1);
try expectApproxEqAbs(neg_x, neg_y, 0.1);
}
2020-06-23 18:05:32 +02:00
}
/// This function is intended to be used only in tests. When the actual value is
/// not approximately equal to the expected value, prints diagnostics to stderr
/// to show exactly how they are not equal, then aborts.
/// See `math.approxEqRel` for more informations on the tolerance parameter.
2020-06-23 18:08:15 +02:00
/// The types must be floating point
2021-05-04 19:36:59 +03:00
pub fn expectApproxEqRel(expected: anytype, actual: @TypeOf(expected), tolerance: @TypeOf(expected)) !void {
const T = @TypeOf(expected);
switch (@typeInfo(T)) {
2021-05-04 19:36:59 +03:00
.Float => if (!math.approxEqRel(T, expected, actual, tolerance)) {
std.debug.print("actual {}, not within relative tolerance {} of expected {}\n", .{ actual, tolerance, expected });
2021-05-04 19:36:59 +03:00
return error.TestExpectedApproxEqRel;
},
.ComptimeFloat => @compileError("Cannot approximately compare two comptime_float values"),
2020-06-23 18:08:15 +02:00
else => @compileError("Unable to compare non floating point values"),
}
}
test "expectApproxEqRel" {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime math.epsilon(T);
const sqrt_eps_value = comptime math.sqrt(eps_value);
const pos_x: T = 12.0;
const pos_y: T = pos_x + 2 * eps_value;
const neg_x: T = -12.0;
const neg_y: T = neg_x - 2 * eps_value;
2020-06-23 18:08:15 +02:00
2021-05-04 19:36:59 +03:00
try expectApproxEqRel(pos_x, pos_y, sqrt_eps_value);
try expectApproxEqRel(neg_x, neg_y, sqrt_eps_value);
}
2020-06-23 18:08:15 +02:00
}
/// This function is intended to be used only in tests. When the two slices are not
/// equal, prints diagnostics to stderr to show exactly how they are not equal,
/// then aborts.
2020-12-08 21:54:46 -07:00
/// If your inputs are UTF-8 encoded strings, consider calling `expectEqualStrings` instead.
2021-05-04 19:36:59 +03:00
pub fn expectEqualSlices(comptime T: type, expected: []const T, actual: []const T) !void {
// TODO better printing of the difference
// If the arrays are small enough we could print the whole thing
// If the child type is u8 and no weird bytes, we could print it as strings
// Even for the length difference, it would be useful to see the values of the slices probably.
if (expected.len != actual.len) {
std.debug.print("slice lengths differ. expected {d}, found {d}\n", .{ expected.len, actual.len });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
var i: usize = 0;
while (i < expected.len) : (i += 1) {
2019-12-22 06:37:25 +05:00
if (!std.meta.eql(expected[i], actual[i])) {
std.debug.print("index {} incorrect. expected {any}, found {any}\n", .{ i, expected[i], actual[i] });
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
}
}
/// This function is intended to be used only in tests. When `ok` is false, the test fails.
/// A message is printed to stderr and then abort is called.
2021-05-04 19:36:59 +03:00
pub fn expect(ok: bool) !void {
if (!ok) return error.TestUnexpectedResult;
}
2019-12-22 06:37:25 +05:00
pub const TmpDir = struct {
dir: std.fs.Dir,
parent_dir: std.fs.Dir,
sub_path: [sub_path_len]u8,
const random_bytes_count = 12;
std/base64: cleanups & support url-safe and other non-padded variants This makes a few changes to the base64 codecs. * The padding character is optional. The common "URL-safe" variant, in particular, is generally not used with padding. This is also the case for password hashes, so having this will avoid code duplication with bcrypt, scrypt and other functions. * The URL-safe variant is added. Instead of having individual constants for each parameter of each variant, we are now grouping these in a struct. So, `standard_pad_char` just becomes `standard.pad_char`. * Types are not `snake_case`'d any more. So, `standard_encoder` becomes `standard.Encoder`, as it is a type. * Creating a decoder with ignored characters required the alphabet and padding. Now, `standard.decoderWithIgnore(<ignored chars>)` returns a decoder with the standard parameters and the set of ignored chars. * Whatever applies to `standard.*` obviously also works with `url_safe.*` * the `calcSize()` interface was inconsistent, taking a length in the encoder, and a slice in the encoder. Rename the variant that takes a slice to `calcSizeForSlice()`. * In the decoder with ignored characters, add `calcSizeUpperBound()`, which is more useful than the one that takes a slice in order to size a fixed buffer before we have the data. * Return `error.InvalidCharacter` when the input actually contains characters that are neither padding nor part of the alphabet. If we hit a padding issue (which includes extra bits at the end), consistently return `error.InvalidPadding`. * Don't keep the `char_in_alphabet` array permanently in a decoder; it is only required for sanity checks during initialization. * Tests are unchanged, but now cover both the standard (padded) and the url-safe (non-padded) variants. * Add an error set, rename `OutputTooSmallError` to `NoSpaceLeft` to match the `hex2bin` equivalent.
2021-03-19 19:26:30 +01:00
const sub_path_len = std.fs.base64_encoder.calcSize(random_bytes_count);
pub fn cleanup(self: *TmpDir) void {
self.dir.close();
self.parent_dir.deleteTree(&self.sub_path) catch {};
self.parent_dir.close();
self.* = undefined;
}
};
2020-05-18 17:10:02 +02:00
fn getCwdOrWasiPreopen() std.fs.Dir {
if (builtin.os.tag == .wasi and !builtin.link_libc) {
2020-05-18 17:10:02 +02:00
var preopens = std.fs.wasi.PreopenList.init(allocator);
defer preopens.deinit();
preopens.populate() catch
@panic("unable to make tmp dir for testing: unable to populate preopens");
const preopen = preopens.find(std.fs.wasi.PreopenType{ .Dir = "." }) orelse
2020-05-18 17:10:02 +02:00
@panic("unable to make tmp dir for testing: didn't find '.' in the preopens");
return std.fs.Dir{ .fd = preopen.fd };
} else {
return std.fs.cwd();
}
}
pub fn tmpDir(opts: std.fs.Dir.OpenDirOptions) TmpDir {
var random_bytes: [TmpDir.random_bytes_count]u8 = undefined;
std.crypto.random.bytes(&random_bytes);
var sub_path: [TmpDir.sub_path_len]u8 = undefined;
_ = std.fs.base64_encoder.encode(&sub_path, &random_bytes);
2020-05-18 17:10:02 +02:00
var cwd = getCwdOrWasiPreopen();
var cache_dir = cwd.makeOpenPath("zig-cache", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open zig-cache dir");
defer cache_dir.close();
var parent_dir = cache_dir.makeOpenPath("tmp", .{}) catch
@panic("unable to make tmp dir for testing: unable to make and open zig-cache/tmp dir");
var dir = parent_dir.makeOpenPath(&sub_path, opts) catch
@panic("unable to make tmp dir for testing: unable to make and open the tmp dir");
return .{
.dir = dir,
.parent_dir = parent_dir,
.sub_path = sub_path,
};
}
2019-12-22 06:37:25 +05:00
test "expectEqual nested array" {
const a = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
const b = [2][2]f32{
[_]f32{ 1.0, 0.0 },
[_]f32{ 0.0, 1.0 },
};
2021-05-04 19:36:59 +03:00
try expectEqual(a, b);
2019-12-22 06:37:25 +05:00
}
2020-01-07 19:14:37 +05:00
test "expectEqual vector" {
var a = @splat(4, @as(u32, 4));
var b = @splat(4, @as(u32, 4));
2021-05-04 19:36:59 +03:00
try expectEqual(a, b);
2020-01-07 19:14:37 +05:00
}
2021-05-04 19:36:59 +03:00
pub fn expectEqualStrings(expected: []const u8, actual: []const u8) !void {
if (std.mem.indexOfDiff(u8, actual, expected)) |diff_index| {
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("\n====== expected this output: =========\n", .{});
printWithVisibleNewlines(expected);
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("\n======== instead found this: =========\n", .{});
printWithVisibleNewlines(actual);
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("\n======================================\n", .{});
var diff_line_number: usize = 1;
for (expected[0..diff_index]) |value| {
if (value == '\n') diff_line_number += 1;
}
print("First difference occurs on line {d}:\n", .{diff_line_number});
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("expected:\n", .{});
printIndicatorLine(expected, diff_index);
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("found:\n", .{});
printIndicatorLine(actual, diff_index);
2021-05-04 19:36:59 +03:00
return error.TestExpectedEqual;
}
}
2021-05-04 19:36:59 +03:00
pub fn expectStringEndsWith(actual: []const u8, expected_ends_with: []const u8) !void {
2020-12-08 21:54:46 -07:00
if (std.mem.endsWith(u8, actual, expected_ends_with))
return;
const shortened_actual = if (actual.len >= expected_ends_with.len)
actual[(actual.len - expected_ends_with.len)..]
2020-12-08 21:54:46 -07:00
else
actual;
print("\n====== expected to end with: =========\n", .{});
printWithVisibleNewlines(expected_ends_with);
print("\n====== instead ended with: ===========\n", .{});
printWithVisibleNewlines(shortened_actual);
print("\n========= full output: ==============\n", .{});
printWithVisibleNewlines(actual);
print("\n======================================\n", .{});
2021-05-04 19:36:59 +03:00
return error.TestExpectedEndsWith;
2020-12-08 21:54:46 -07:00
}
fn printIndicatorLine(source: []const u8, indicator_index: usize) void {
const line_begin_index = if (std.mem.lastIndexOfScalar(u8, source[0..indicator_index], '\n')) |line_begin|
line_begin + 1
else
0;
const line_end_index = if (std.mem.indexOfScalar(u8, source[indicator_index..], '\n')) |line_end|
(indicator_index + line_end)
else
source.len;
printLine(source[line_begin_index..line_end_index]);
{
var i: usize = line_begin_index;
while (i < indicator_index) : (i += 1)
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print(" ", .{});
}
std: introduce GeneralPurposeAllocator `std.GeneralPurposeAllocator` is now available. It is a function that takes a configuration struct (with default field values) and returns an allocator. There is a detailed description of this allocator in the doc comments at the top of the new file. The main feature of this allocator is that it is *safe*. It prevents double-free, use-after-free, and detects leaks. Some deprecation compile errors are removed. The Allocator interface gains `old_align` as a new parameter to `resizeFn`. This is useful to quickly look up allocations. `std.heap.page_allocator` is improved to use mmap address hints to avoid obtaining the same virtual address pages when unmapping and mapping pages. The new general purpose allocator uses the page allocator as its backing allocator by default. `std.testing.allocator` is replaced with usage of this new allocator, which does leak checking, and so the LeakCheckAllocator is retired. stage1 is improved so that the `@typeInfo` of a pointer has a lazy value for the alignment of the child type, to avoid false dependency loops when dealing with pointers to async function frames. The `std.mem.Allocator` interface is refactored to be in its own file. `std.Mutex` now exposes the dummy mutex with `std.Mutex.Dummy`. This allocator is great for debug mode, however it needs some work to have better performance in release modes. The next step will be setting up a series of tests in ziglang/gotta-go-fast and then making improvements to the implementation.
2020-08-07 22:35:15 -07:00
print("^\n", .{});
}
fn printWithVisibleNewlines(source: []const u8) void {
var i: usize = 0;
while (std.mem.indexOfScalar(u8, source[i..], '\n')) |nl| : (i += nl + 1) {
printLine(source[i .. i + nl]);
}
print("{s}␃\n", .{source[i..]}); // End of Text symbol (ETX)
}
fn printLine(line: []const u8) void {
if (line.len != 0) switch (line[line.len - 1]) {
' ', '\t' => return print("{s}⏎\n", .{line}), // Carriage return symbol,
else => {},
};
print("{s}\n", .{line});
}
test {
2021-05-04 19:36:59 +03:00
try expectEqualStrings("foo", "foo");
}
/// Given a type, reference all the declarations inside, so that the semantic analyzer sees them.
pub fn refAllDecls(comptime T: type) void {
if (!builtin.is_test) return;
inline for (std.meta.declarations(T)) |decl| {
_ = decl;
}
}