Merge remote-tracking branch 'origin/master' into stage2-whole-file-astgen

Conflicts:
 * doc/langref.html.in
 * lib/std/enums.zig
 * lib/std/fmt.zig
 * lib/std/hash/auto_hash.zig
 * lib/std/math.zig
 * lib/std/mem.zig
 * lib/std/meta.zig
 * test/behavior/alignof.zig
 * test/behavior/bitcast.zig
 * test/behavior/bugs/1421.zig
 * test/behavior/cast.zig
 * test/behavior/ptrcast.zig
 * test/behavior/type_info.zig
 * test/behavior/vector.zig

Master branch added `try` to a bunch of testing function calls, and some
lines also had changed how to refer to the native architecture and other
`@import("builtin")` stuff.
This commit is contained in:
Andrew Kelley 2021-05-08 14:45:21 -07:00
commit 5619ce2406
408 changed files with 12487 additions and 12478 deletions

File diff suppressed because it is too large Load Diff

View File

@ -249,13 +249,13 @@ test "SemanticVersion format" {
"+justmeta",
"9.8.7+meta+meta",
"9.8.7-whatever+meta+meta",
}) |invalid| expectError(error.InvalidVersion, parse(invalid));
}) |invalid| try expectError(error.InvalidVersion, parse(invalid));
// Valid version string that may overflow.
const big_valid = "99999999999999999999999.999999999999999999.99999999999999999";
if (parse(big_valid)) |ver| {
try std.testing.expectFmt(big_valid, "{}", .{ver});
} else |err| expect(err == error.Overflow);
} else |err| try expect(err == error.Overflow);
// Invalid version string that may overflow.
const big_invalid = "99999999999999999999999.999999999999999999.99999999999999999----RC-SNAPSHOT.12.09.1--------------------------------..12";
@ -264,22 +264,22 @@ test "SemanticVersion format" {
test "SemanticVersion precedence" {
// SemVer 2 spec 11.2 example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1.
expect(order(try parse("1.0.0"), try parse("2.0.0")) == .lt);
expect(order(try parse("2.0.0"), try parse("2.1.0")) == .lt);
expect(order(try parse("2.1.0"), try parse("2.1.1")) == .lt);
try expect(order(try parse("1.0.0"), try parse("2.0.0")) == .lt);
try expect(order(try parse("2.0.0"), try parse("2.1.0")) == .lt);
try expect(order(try parse("2.1.0"), try parse("2.1.1")) == .lt);
// SemVer 2 spec 11.3 example: 1.0.0-alpha < 1.0.0.
expect(order(try parse("1.0.0-alpha"), try parse("1.0.0")) == .lt);
try expect(order(try parse("1.0.0-alpha"), try parse("1.0.0")) == .lt);
// SemVer 2 spec 11.4 example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta <
// 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.
expect(order(try parse("1.0.0-alpha"), try parse("1.0.0-alpha.1")) == .lt);
expect(order(try parse("1.0.0-alpha.1"), try parse("1.0.0-alpha.beta")) == .lt);
expect(order(try parse("1.0.0-alpha.beta"), try parse("1.0.0-beta")) == .lt);
expect(order(try parse("1.0.0-beta"), try parse("1.0.0-beta.2")) == .lt);
expect(order(try parse("1.0.0-beta.2"), try parse("1.0.0-beta.11")) == .lt);
expect(order(try parse("1.0.0-beta.11"), try parse("1.0.0-rc.1")) == .lt);
expect(order(try parse("1.0.0-rc.1"), try parse("1.0.0")) == .lt);
try expect(order(try parse("1.0.0-alpha"), try parse("1.0.0-alpha.1")) == .lt);
try expect(order(try parse("1.0.0-alpha.1"), try parse("1.0.0-alpha.beta")) == .lt);
try expect(order(try parse("1.0.0-alpha.beta"), try parse("1.0.0-beta")) == .lt);
try expect(order(try parse("1.0.0-beta"), try parse("1.0.0-beta.2")) == .lt);
try expect(order(try parse("1.0.0-beta.2"), try parse("1.0.0-beta.11")) == .lt);
try expect(order(try parse("1.0.0-beta.11"), try parse("1.0.0-rc.1")) == .lt);
try expect(order(try parse("1.0.0-rc.1"), try parse("1.0.0")) == .lt);
}
test "zig_version" {

View File

@ -176,7 +176,7 @@ test "basic usage" {
// test local code paths
{
var event = AutoResetEvent{};
testing.expectError(error.TimedOut, event.timedWait(1));
try testing.expectError(error.TimedOut, event.timedWait(1));
event.set();
event.wait();
}
@ -192,28 +192,28 @@ test "basic usage" {
const Self = @This();
fn sender(self: *Self) void {
testing.expect(self.value == 0);
fn sender(self: *Self) !void {
try testing.expect(self.value == 0);
self.value = 1;
self.out.set();
self.in.wait();
testing.expect(self.value == 2);
try testing.expect(self.value == 2);
self.value = 3;
self.out.set();
self.in.wait();
testing.expect(self.value == 4);
try testing.expect(self.value == 4);
}
fn receiver(self: *Self) void {
fn receiver(self: *Self) !void {
self.out.wait();
testing.expect(self.value == 1);
try testing.expect(self.value == 1);
self.value = 2;
self.in.set();
self.out.wait();
testing.expect(self.value == 3);
try testing.expect(self.value == 3);
self.value = 4;
self.in.set();
}

View File

@ -294,7 +294,7 @@ test "basic usage" {
if (builtin.single_threaded) {
worker(&context);
testing.expect(context.data == TestContext.incr_count);
try testing.expect(context.data == TestContext.incr_count);
} else {
const thread_count = 10;
var threads: [thread_count]*std.Thread = undefined;
@ -304,7 +304,7 @@ test "basic usage" {
for (threads) |t|
t.wait();
testing.expect(context.data == thread_count * TestContext.incr_count);
try testing.expect(context.data == thread_count * TestContext.incr_count);
}
}

View File

@ -204,7 +204,7 @@ test "basic usage" {
event.reset();
event.set();
testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
try testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
// test cross-thread signaling
if (builtin.single_threaded)
@ -233,25 +233,25 @@ test "basic usage" {
self.* = undefined;
}
fn sender(self: *Self) void {
fn sender(self: *Self) !void {
// update value and signal input
testing.expect(self.value == 0);
try testing.expect(self.value == 0);
self.value = 1;
self.in.set();
// wait for receiver to update value and signal output
self.out.wait();
testing.expect(self.value == 2);
try testing.expect(self.value == 2);
// update value and signal final input
self.value = 3;
self.in.set();
}
fn receiver(self: *Self) void {
fn receiver(self: *Self) !void {
// wait for sender to update value and signal input
self.in.wait();
assert(self.value == 1);
try testing.expect(self.value == 1);
// update value and signal output
self.in.reset();
@ -260,7 +260,7 @@ test "basic usage" {
// wait for sender to update value and signal final input
self.in.wait();
assert(self.value == 3);
try testing.expect(self.value == 3);
}
fn sleeper(self: *Self) void {
@ -272,9 +272,9 @@ test "basic usage" {
fn timedWaiter(self: *Self) !void {
self.in.wait();
testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try self.out.timedWait(time.ns_per_ms * 100);
testing.expect(self.value == 5);
try testing.expect(self.value == 5);
}
};
@ -283,7 +283,7 @@ test "basic usage" {
defer context.deinit();
const receiver = try std.Thread.spawn(Context.receiver, &context);
defer receiver.wait();
context.sender();
try context.sender();
if (false) {
// I have now observed this fail on macOS, Windows, and Linux.

View File

@ -320,7 +320,7 @@ test "basic usage" {
event.reset();
event.set();
testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
try testing.expectEqual(TimedWaitResult.event_set, event.timedWait(1));
// test cross-thread signaling
if (std.builtin.single_threaded)
@ -333,25 +333,25 @@ test "basic usage" {
in: StaticResetEvent = .{},
out: StaticResetEvent = .{},
fn sender(self: *Self) void {
fn sender(self: *Self) !void {
// update value and signal input
testing.expect(self.value == 0);
try testing.expect(self.value == 0);
self.value = 1;
self.in.set();
// wait for receiver to update value and signal output
self.out.wait();
testing.expect(self.value == 2);
try testing.expect(self.value == 2);
// update value and signal final input
self.value = 3;
self.in.set();
}
fn receiver(self: *Self) void {
fn receiver(self: *Self) !void {
// wait for sender to update value and signal input
self.in.wait();
assert(self.value == 1);
try testing.expect(self.value == 1);
// update value and signal output
self.in.reset();
@ -360,7 +360,7 @@ test "basic usage" {
// wait for sender to update value and signal final input
self.in.wait();
assert(self.value == 3);
try testing.expect(self.value == 3);
}
fn sleeper(self: *Self) void {
@ -372,16 +372,16 @@ test "basic usage" {
fn timedWaiter(self: *Self) !void {
self.in.wait();
testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try testing.expectEqual(TimedWaitResult.timed_out, self.out.timedWait(time.ns_per_us));
try self.out.timedWait(time.ns_per_ms * 100);
testing.expect(self.value == 5);
try testing.expect(self.value == 5);
}
};
var context = Context{};
const receiver = try std.Thread.spawn(Context.receiver, &context);
defer receiver.wait();
context.sender();
try context.sender();
if (false) {
// I have now observed this fail on macOS, Windows, and Linux.

View File

@ -1088,63 +1088,63 @@ test "basic hash map usage" {
var map = AutoArrayHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
testing.expect((try map.fetchPut(1, 11)) == null);
testing.expect((try map.fetchPut(2, 22)) == null);
testing.expect((try map.fetchPut(3, 33)) == null);
testing.expect((try map.fetchPut(4, 44)) == null);
try testing.expect((try map.fetchPut(1, 11)) == null);
try testing.expect((try map.fetchPut(2, 22)) == null);
try testing.expect((try map.fetchPut(3, 33)) == null);
try testing.expect((try map.fetchPut(4, 44)) == null);
try map.putNoClobber(5, 55);
testing.expect((try map.fetchPut(5, 66)).?.value == 55);
testing.expect((try map.fetchPut(5, 55)).?.value == 66);
try testing.expect((try map.fetchPut(5, 66)).?.value == 55);
try testing.expect((try map.fetchPut(5, 55)).?.value == 66);
const gop1 = try map.getOrPut(5);
testing.expect(gop1.found_existing == true);
testing.expect(gop1.entry.value == 55);
testing.expect(gop1.index == 4);
try testing.expect(gop1.found_existing == true);
try testing.expect(gop1.entry.value == 55);
try testing.expect(gop1.index == 4);
gop1.entry.value = 77;
testing.expect(map.getEntry(5).?.value == 77);
try testing.expect(map.getEntry(5).?.value == 77);
const gop2 = try map.getOrPut(99);
testing.expect(gop2.found_existing == false);
testing.expect(gop2.index == 5);
try testing.expect(gop2.found_existing == false);
try testing.expect(gop2.index == 5);
gop2.entry.value = 42;
testing.expect(map.getEntry(99).?.value == 42);
try testing.expect(map.getEntry(99).?.value == 42);
const gop3 = try map.getOrPutValue(5, 5);
testing.expect(gop3.value == 77);
try testing.expect(gop3.value == 77);
const gop4 = try map.getOrPutValue(100, 41);
testing.expect(gop4.value == 41);
try testing.expect(gop4.value == 41);
testing.expect(map.contains(2));
testing.expect(map.getEntry(2).?.value == 22);
testing.expect(map.get(2).? == 22);
try testing.expect(map.contains(2));
try testing.expect(map.getEntry(2).?.value == 22);
try testing.expect(map.get(2).? == 22);
const rmv1 = map.swapRemove(2);
testing.expect(rmv1.?.key == 2);
testing.expect(rmv1.?.value == 22);
testing.expect(map.swapRemove(2) == null);
testing.expect(map.getEntry(2) == null);
testing.expect(map.get(2) == null);
try testing.expect(rmv1.?.key == 2);
try testing.expect(rmv1.?.value == 22);
try testing.expect(map.swapRemove(2) == null);
try testing.expect(map.getEntry(2) == null);
try testing.expect(map.get(2) == null);
// Since we've used `swapRemove` above, the index of this entry should remain unchanged.
testing.expect(map.getIndex(100).? == 1);
try testing.expect(map.getIndex(100).? == 1);
const gop5 = try map.getOrPut(5);
testing.expect(gop5.found_existing == true);
testing.expect(gop5.entry.value == 77);
testing.expect(gop5.index == 4);
try testing.expect(gop5.found_existing == true);
try testing.expect(gop5.entry.value == 77);
try testing.expect(gop5.index == 4);
// Whereas, if we do an `orderedRemove`, it should move the index forward one spot.
const rmv2 = map.orderedRemove(100);
testing.expect(rmv2.?.key == 100);
testing.expect(rmv2.?.value == 41);
testing.expect(map.orderedRemove(100) == null);
testing.expect(map.getEntry(100) == null);
testing.expect(map.get(100) == null);
try testing.expect(rmv2.?.key == 100);
try testing.expect(rmv2.?.value == 41);
try testing.expect(map.orderedRemove(100) == null);
try testing.expect(map.getEntry(100) == null);
try testing.expect(map.get(100) == null);
const gop6 = try map.getOrPut(5);
testing.expect(gop6.found_existing == true);
testing.expect(gop6.entry.value == 77);
testing.expect(gop6.index == 3);
try testing.expect(gop6.found_existing == true);
try testing.expect(gop6.entry.value == 77);
try testing.expect(gop6.index == 3);
map.removeAssertDiscard(3);
}
@ -1180,11 +1180,11 @@ test "iterator hash map" {
while (it.next()) |entry| : (count += 1) {
buffer[@intCast(usize, entry.key)] = entry.value;
}
testing.expect(count == 3);
testing.expect(it.next() == null);
try testing.expect(count == 3);
try testing.expect(it.next() == null);
for (buffer) |v, i| {
testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
}
it.reset();
@ -1196,13 +1196,13 @@ test "iterator hash map" {
}
for (buffer[0..2]) |v, i| {
testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
try testing.expect(buffer[@intCast(usize, keys[i])] == values[i]);
}
it.reset();
var entry = it.next().?;
testing.expect(entry.key == first_entry.key);
testing.expect(entry.value == first_entry.value);
try testing.expect(entry.key == first_entry.key);
try testing.expect(entry.value == first_entry.value);
}
test "ensure capacity" {
@ -1211,13 +1211,13 @@ test "ensure capacity" {
try map.ensureCapacity(20);
const initial_capacity = map.capacity();
testing.expect(initial_capacity >= 20);
try testing.expect(initial_capacity >= 20);
var i: i32 = 0;
while (i < 20) : (i += 1) {
testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
}
// shouldn't resize from putAssumeCapacity
testing.expect(initial_capacity == map.capacity());
try testing.expect(initial_capacity == map.capacity());
}
test "clone" {
@ -1235,7 +1235,7 @@ test "clone" {
i = 0;
while (i < 10) : (i += 1) {
testing.expect(copy.get(i).? == i * 10);
try testing.expect(copy.get(i).? == i * 10);
}
}
@ -1247,35 +1247,35 @@ test "shrink" {
const num_entries = 20;
var i: i32 = 0;
while (i < num_entries) : (i += 1)
testing.expect((try map.fetchPut(i, i * 10)) == null);
try testing.expect((try map.fetchPut(i, i * 10)) == null);
testing.expect(map.unmanaged.index_header != null);
testing.expect(map.count() == num_entries);
try testing.expect(map.unmanaged.index_header != null);
try testing.expect(map.count() == num_entries);
// Test `shrinkRetainingCapacity`.
map.shrinkRetainingCapacity(17);
testing.expect(map.count() == 17);
testing.expect(map.capacity() == 20);
try testing.expect(map.count() == 17);
try testing.expect(map.capacity() == 20);
i = 0;
while (i < num_entries) : (i += 1) {
const gop = try map.getOrPut(i);
if (i < 17) {
testing.expect(gop.found_existing == true);
testing.expect(gop.entry.value == i * 10);
} else testing.expect(gop.found_existing == false);
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
} else try testing.expect(gop.found_existing == false);
}
// Test `shrinkAndFree`.
map.shrinkAndFree(15);
testing.expect(map.count() == 15);
testing.expect(map.capacity() == 15);
try testing.expect(map.count() == 15);
try testing.expect(map.capacity() == 15);
i = 0;
while (i < num_entries) : (i += 1) {
const gop = try map.getOrPut(i);
if (i < 15) {
testing.expect(gop.found_existing == true);
testing.expect(gop.entry.value == i * 10);
} else testing.expect(gop.found_existing == false);
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
} else try testing.expect(gop.found_existing == false);
}
}
@ -1288,12 +1288,12 @@ test "pop" {
var i: i32 = 0;
while (i < 9) : (i += 1) {
testing.expect((try map.fetchPut(i, i)) == null);
try testing.expect((try map.fetchPut(i, i)) == null);
}
while (i > 0) : (i -= 1) {
const pop = map.pop();
testing.expect(pop.key == i - 1 and pop.value == i - 1);
try testing.expect(pop.key == i - 1 and pop.value == i - 1);
}
}
@ -1305,10 +1305,10 @@ test "reIndex" {
const num_indexed_entries = 20;
var i: i32 = 0;
while (i < num_indexed_entries) : (i += 1)
testing.expect((try map.fetchPut(i, i * 10)) == null);
try testing.expect((try map.fetchPut(i, i * 10)) == null);
// Make sure we allocated an index header.
testing.expect(map.unmanaged.index_header != null);
try testing.expect(map.unmanaged.index_header != null);
// Now write to the underlying array list directly.
const num_unindexed_entries = 20;
@ -1327,9 +1327,9 @@ test "reIndex" {
i = 0;
while (i < num_indexed_entries + num_unindexed_entries) : (i += 1) {
const gop = try map.getOrPut(i);
testing.expect(gop.found_existing == true);
testing.expect(gop.entry.value == i * 10);
testing.expect(gop.index == i);
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
try testing.expect(gop.index == i);
}
}
@ -1356,9 +1356,9 @@ test "fromOwnedArrayList" {
i = 0;
while (i < num_entries) : (i += 1) {
const gop = try map.getOrPut(i);
testing.expect(gop.found_existing == true);
testing.expect(gop.entry.value == i * 10);
testing.expect(gop.index == i);
try testing.expect(gop.found_existing == true);
try testing.expect(gop.entry.value == i * 10);
try testing.expect(gop.index == i);
}
}

View File

@ -741,15 +741,15 @@ test "std.ArrayList/ArrayListUnmanaged.init" {
var list = ArrayList(i32).init(testing.allocator);
defer list.deinit();
testing.expect(list.items.len == 0);
testing.expect(list.capacity == 0);
try testing.expect(list.items.len == 0);
try testing.expect(list.capacity == 0);
}
{
var list = ArrayListUnmanaged(i32){};
testing.expect(list.items.len == 0);
testing.expect(list.capacity == 0);
try testing.expect(list.items.len == 0);
try testing.expect(list.capacity == 0);
}
}
@ -758,14 +758,14 @@ test "std.ArrayList/ArrayListUnmanaged.initCapacity" {
{
var list = try ArrayList(i8).initCapacity(a, 200);
defer list.deinit();
testing.expect(list.items.len == 0);
testing.expect(list.capacity >= 200);
try testing.expect(list.items.len == 0);
try testing.expect(list.capacity >= 200);
}
{
var list = try ArrayListUnmanaged(i8).initCapacity(a, 200);
defer list.deinit(a);
testing.expect(list.items.len == 0);
testing.expect(list.capacity >= 200);
try testing.expect(list.items.len == 0);
try testing.expect(list.capacity >= 200);
}
}
@ -785,33 +785,33 @@ test "std.ArrayList/ArrayListUnmanaged.basic" {
{
var i: usize = 0;
while (i < 10) : (i += 1) {
testing.expect(list.items[i] == @intCast(i32, i + 1));
try testing.expect(list.items[i] == @intCast(i32, i + 1));
}
}
for (list.items) |v, i| {
testing.expect(v == @intCast(i32, i + 1));
try testing.expect(v == @intCast(i32, i + 1));
}
testing.expect(list.pop() == 10);
testing.expect(list.items.len == 9);
try testing.expect(list.pop() == 10);
try testing.expect(list.items.len == 9);
list.appendSlice(&[_]i32{ 1, 2, 3 }) catch unreachable;
testing.expect(list.items.len == 12);
testing.expect(list.pop() == 3);
testing.expect(list.pop() == 2);
testing.expect(list.pop() == 1);
testing.expect(list.items.len == 9);
try testing.expect(list.items.len == 12);
try testing.expect(list.pop() == 3);
try testing.expect(list.pop() == 2);
try testing.expect(list.pop() == 1);
try testing.expect(list.items.len == 9);
list.appendSlice(&[_]i32{}) catch unreachable;
testing.expect(list.items.len == 9);
try testing.expect(list.items.len == 9);
// can only set on indices < self.items.len
list.items[7] = 33;
list.items[8] = 42;
testing.expect(list.pop() == 42);
testing.expect(list.pop() == 33);
try testing.expect(list.pop() == 42);
try testing.expect(list.pop() == 33);
}
{
var list = ArrayListUnmanaged(i32){};
@ -827,33 +827,33 @@ test "std.ArrayList/ArrayListUnmanaged.basic" {
{
var i: usize = 0;
while (i < 10) : (i += 1) {
testing.expect(list.items[i] == @intCast(i32, i + 1));
try testing.expect(list.items[i] == @intCast(i32, i + 1));
}
}
for (list.items) |v, i| {
testing.expect(v == @intCast(i32, i + 1));
try testing.expect(v == @intCast(i32, i + 1));
}
testing.expect(list.pop() == 10);
testing.expect(list.items.len == 9);
try testing.expect(list.pop() == 10);
try testing.expect(list.items.len == 9);
list.appendSlice(a, &[_]i32{ 1, 2, 3 }) catch unreachable;
testing.expect(list.items.len == 12);
testing.expect(list.pop() == 3);
testing.expect(list.pop() == 2);
testing.expect(list.pop() == 1);
testing.expect(list.items.len == 9);
try testing.expect(list.items.len == 12);
try testing.expect(list.pop() == 3);
try testing.expect(list.pop() == 2);
try testing.expect(list.pop() == 1);
try testing.expect(list.items.len == 9);
list.appendSlice(a, &[_]i32{}) catch unreachable;
testing.expect(list.items.len == 9);
try testing.expect(list.items.len == 9);
// can only set on indices < self.items.len
list.items[7] = 33;
list.items[8] = 42;
testing.expect(list.pop() == 42);
testing.expect(list.pop() == 33);
try testing.expect(list.pop() == 42);
try testing.expect(list.pop() == 33);
}
}
@ -864,9 +864,9 @@ test "std.ArrayList/ArrayListUnmanaged.appendNTimes" {
defer list.deinit();
try list.appendNTimes(2, 10);
testing.expectEqual(@as(usize, 10), list.items.len);
try testing.expectEqual(@as(usize, 10), list.items.len);
for (list.items) |element| {
testing.expectEqual(@as(i32, 2), element);
try testing.expectEqual(@as(i32, 2), element);
}
}
{
@ -874,9 +874,9 @@ test "std.ArrayList/ArrayListUnmanaged.appendNTimes" {
defer list.deinit(a);
try list.appendNTimes(a, 2, 10);
testing.expectEqual(@as(usize, 10), list.items.len);
try testing.expectEqual(@as(usize, 10), list.items.len);
for (list.items) |element| {
testing.expectEqual(@as(i32, 2), element);
try testing.expectEqual(@as(i32, 2), element);
}
}
}
@ -886,12 +886,12 @@ test "std.ArrayList/ArrayListUnmanaged.appendNTimes with failing allocator" {
{
var list = ArrayList(i32).init(a);
defer list.deinit();
testing.expectError(error.OutOfMemory, list.appendNTimes(2, 10));
try testing.expectError(error.OutOfMemory, list.appendNTimes(2, 10));
}
{
var list = ArrayListUnmanaged(i32){};
defer list.deinit(a);
testing.expectError(error.OutOfMemory, list.appendNTimes(a, 2, 10));
try testing.expectError(error.OutOfMemory, list.appendNTimes(a, 2, 10));
}
}
@ -910,18 +910,18 @@ test "std.ArrayList/ArrayListUnmanaged.orderedRemove" {
try list.append(7);
//remove from middle
testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
testing.expectEqual(@as(i32, 5), list.items[3]);
testing.expectEqual(@as(usize, 6), list.items.len);
try testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
try testing.expectEqual(@as(i32, 5), list.items[3]);
try testing.expectEqual(@as(usize, 6), list.items.len);
//remove from end
testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
testing.expectEqual(@as(usize, 5), list.items.len);
try testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
try testing.expectEqual(@as(usize, 5), list.items.len);
//remove from front
testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
testing.expectEqual(@as(i32, 2), list.items[0]);
testing.expectEqual(@as(usize, 4), list.items.len);
try testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
try testing.expectEqual(@as(i32, 2), list.items[0]);
try testing.expectEqual(@as(usize, 4), list.items.len);
}
{
var list = ArrayListUnmanaged(i32){};
@ -936,18 +936,18 @@ test "std.ArrayList/ArrayListUnmanaged.orderedRemove" {
try list.append(a, 7);
//remove from middle
testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
testing.expectEqual(@as(i32, 5), list.items[3]);
testing.expectEqual(@as(usize, 6), list.items.len);
try testing.expectEqual(@as(i32, 4), list.orderedRemove(3));
try testing.expectEqual(@as(i32, 5), list.items[3]);
try testing.expectEqual(@as(usize, 6), list.items.len);
//remove from end
testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
testing.expectEqual(@as(usize, 5), list.items.len);
try testing.expectEqual(@as(i32, 7), list.orderedRemove(5));
try testing.expectEqual(@as(usize, 5), list.items.len);
//remove from front
testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
testing.expectEqual(@as(i32, 2), list.items[0]);
testing.expectEqual(@as(usize, 4), list.items.len);
try testing.expectEqual(@as(i32, 1), list.orderedRemove(0));
try testing.expectEqual(@as(i32, 2), list.items[0]);
try testing.expectEqual(@as(usize, 4), list.items.len);
}
}
@ -966,18 +966,18 @@ test "std.ArrayList/ArrayListUnmanaged.swapRemove" {
try list.append(7);
//remove from middle
testing.expect(list.swapRemove(3) == 4);
testing.expect(list.items[3] == 7);
testing.expect(list.items.len == 6);
try testing.expect(list.swapRemove(3) == 4);
try testing.expect(list.items[3] == 7);
try testing.expect(list.items.len == 6);
//remove from end
testing.expect(list.swapRemove(5) == 6);
testing.expect(list.items.len == 5);
try testing.expect(list.swapRemove(5) == 6);
try testing.expect(list.items.len == 5);
//remove from front
testing.expect(list.swapRemove(0) == 1);
testing.expect(list.items[0] == 5);
testing.expect(list.items.len == 4);
try testing.expect(list.swapRemove(0) == 1);
try testing.expect(list.items[0] == 5);
try testing.expect(list.items.len == 4);
}
{
var list = ArrayListUnmanaged(i32){};
@ -992,18 +992,18 @@ test "std.ArrayList/ArrayListUnmanaged.swapRemove" {
try list.append(a, 7);
//remove from middle
testing.expect(list.swapRemove(3) == 4);
testing.expect(list.items[3] == 7);
testing.expect(list.items.len == 6);
try testing.expect(list.swapRemove(3) == 4);
try testing.expect(list.items[3] == 7);
try testing.expect(list.items.len == 6);
//remove from end
testing.expect(list.swapRemove(5) == 6);
testing.expect(list.items.len == 5);
try testing.expect(list.swapRemove(5) == 6);
try testing.expect(list.items.len == 5);
//remove from front
testing.expect(list.swapRemove(0) == 1);
testing.expect(list.items[0] == 5);
testing.expect(list.items.len == 4);
try testing.expect(list.swapRemove(0) == 1);
try testing.expect(list.items[0] == 5);
try testing.expect(list.items.len == 4);
}
}
@ -1017,10 +1017,10 @@ test "std.ArrayList/ArrayListUnmanaged.insert" {
try list.append(2);
try list.append(3);
try list.insert(0, 5);
testing.expect(list.items[0] == 5);
testing.expect(list.items[1] == 1);
testing.expect(list.items[2] == 2);
testing.expect(list.items[3] == 3);
try testing.expect(list.items[0] == 5);
try testing.expect(list.items[1] == 1);
try testing.expect(list.items[2] == 2);
try testing.expect(list.items[3] == 3);
}
{
var list = ArrayListUnmanaged(i32){};
@ -1030,10 +1030,10 @@ test "std.ArrayList/ArrayListUnmanaged.insert" {
try list.append(a, 2);
try list.append(a, 3);
try list.insert(a, 0, 5);
testing.expect(list.items[0] == 5);
testing.expect(list.items[1] == 1);
testing.expect(list.items[2] == 2);
testing.expect(list.items[3] == 3);
try testing.expect(list.items[0] == 5);
try testing.expect(list.items[1] == 1);
try testing.expect(list.items[2] == 2);
try testing.expect(list.items[3] == 3);
}
}
@ -1048,17 +1048,17 @@ test "std.ArrayList/ArrayListUnmanaged.insertSlice" {
try list.append(3);
try list.append(4);
try list.insertSlice(1, &[_]i32{ 9, 8 });
testing.expect(list.items[0] == 1);
testing.expect(list.items[1] == 9);
testing.expect(list.items[2] == 8);
testing.expect(list.items[3] == 2);
testing.expect(list.items[4] == 3);
testing.expect(list.items[5] == 4);
try testing.expect(list.items[0] == 1);
try testing.expect(list.items[1] == 9);
try testing.expect(list.items[2] == 8);
try testing.expect(list.items[3] == 2);
try testing.expect(list.items[4] == 3);
try testing.expect(list.items[5] == 4);
const items = [_]i32{1};
try list.insertSlice(0, items[0..0]);
testing.expect(list.items.len == 6);
testing.expect(list.items[0] == 1);
try testing.expect(list.items.len == 6);
try testing.expect(list.items[0] == 1);
}
{
var list = ArrayListUnmanaged(i32){};
@ -1069,17 +1069,17 @@ test "std.ArrayList/ArrayListUnmanaged.insertSlice" {
try list.append(a, 3);
try list.append(a, 4);
try list.insertSlice(a, 1, &[_]i32{ 9, 8 });
testing.expect(list.items[0] == 1);
testing.expect(list.items[1] == 9);
testing.expect(list.items[2] == 8);
testing.expect(list.items[3] == 2);
testing.expect(list.items[4] == 3);
testing.expect(list.items[5] == 4);
try testing.expect(list.items[0] == 1);
try testing.expect(list.items[1] == 9);
try testing.expect(list.items[2] == 8);
try testing.expect(list.items[3] == 2);
try testing.expect(list.items[4] == 3);
try testing.expect(list.items[5] == 4);
const items = [_]i32{1};
try list.insertSlice(a, 0, items[0..0]);
testing.expect(list.items.len == 6);
testing.expect(list.items[0] == 1);
try testing.expect(list.items.len == 6);
try testing.expect(list.items[0] == 1);
}
}
@ -1112,13 +1112,13 @@ test "std.ArrayList/ArrayListUnmanaged.replaceRange" {
try list_lt.replaceRange(1, 2, &new);
// after_range > new_items.len in function body
testing.expect(1 + 4 > new.len);
try testing.expect(1 + 4 > new.len);
try list_gt.replaceRange(1, 4, &new);
testing.expectEqualSlices(i32, list_zero.items, &result_zero);
testing.expectEqualSlices(i32, list_eq.items, &result_eq);
testing.expectEqualSlices(i32, list_lt.items, &result_le);
testing.expectEqualSlices(i32, list_gt.items, &result_gt);
try testing.expectEqualSlices(i32, list_zero.items, &result_zero);
try testing.expectEqualSlices(i32, list_eq.items, &result_eq);
try testing.expectEqualSlices(i32, list_lt.items, &result_le);
try testing.expectEqualSlices(i32, list_gt.items, &result_gt);
}
{
var list_zero = ArrayListUnmanaged(i32){};
@ -1136,13 +1136,13 @@ test "std.ArrayList/ArrayListUnmanaged.replaceRange" {
try list_lt.replaceRange(a, 1, 2, &new);
// after_range > new_items.len in function body
testing.expect(1 + 4 > new.len);
try testing.expect(1 + 4 > new.len);
try list_gt.replaceRange(a, 1, 4, &new);
testing.expectEqualSlices(i32, list_zero.items, &result_zero);
testing.expectEqualSlices(i32, list_eq.items, &result_eq);
testing.expectEqualSlices(i32, list_lt.items, &result_le);
testing.expectEqualSlices(i32, list_gt.items, &result_gt);
try testing.expectEqualSlices(i32, list_zero.items, &result_zero);
try testing.expectEqualSlices(i32, list_eq.items, &result_eq);
try testing.expectEqualSlices(i32, list_lt.items, &result_le);
try testing.expectEqualSlices(i32, list_gt.items, &result_gt);
}
}
@ -1162,13 +1162,13 @@ test "std.ArrayList/ArrayListUnmanaged: ArrayList(T) of struct T" {
var root = Item{ .integer = 1, .sub_items = ArrayList(Item).init(a) };
defer root.sub_items.deinit();
try root.sub_items.append(Item{ .integer = 42, .sub_items = ArrayList(Item).init(a) });
testing.expect(root.sub_items.items[0].integer == 42);
try testing.expect(root.sub_items.items[0].integer == 42);
}
{
var root = ItemUnmanaged{ .integer = 1, .sub_items = ArrayListUnmanaged(ItemUnmanaged){} };
defer root.sub_items.deinit(a);
try root.sub_items.append(a, ItemUnmanaged{ .integer = 42, .sub_items = ArrayListUnmanaged(ItemUnmanaged){} });
testing.expect(root.sub_items.items[0].integer == 42);
try testing.expect(root.sub_items.items[0].integer == 42);
}
}
@ -1183,7 +1183,7 @@ test "std.ArrayList(u8)/ArrayListAligned implements writer" {
const y: i32 = 1234;
try buffer.writer().print("x: {}\ny: {}\n", .{ x, y });
testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", buffer.items);
}
{
var list = ArrayListAligned(u8, 2).init(a);
@ -1195,7 +1195,7 @@ test "std.ArrayList(u8)/ArrayListAligned implements writer" {
try writer.writeAll("d");
try writer.writeAll("efg");
testing.expectEqualSlices(u8, list.items, "abcdefg");
try testing.expectEqualSlices(u8, list.items, "abcdefg");
}
}
@ -1213,7 +1213,7 @@ test "std.ArrayList/ArrayListUnmanaged.shrink still sets length on error.OutOfMe
try list.append(3);
list.shrinkAndFree(1);
testing.expect(list.items.len == 1);
try testing.expect(list.items.len == 1);
}
{
var list = ArrayListUnmanaged(i32){};
@ -1223,7 +1223,7 @@ test "std.ArrayList/ArrayListUnmanaged.shrink still sets length on error.OutOfMe
try list.append(a, 3);
list.shrinkAndFree(a, 1);
testing.expect(list.items.len == 1);
try testing.expect(list.items.len == 1);
}
}
@ -1237,7 +1237,7 @@ test "std.ArrayList/ArrayListUnmanaged.addManyAsArray" {
try list.ensureTotalCapacity(8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
testing.expectEqualSlices(u8, list.items, "aoeuasdf");
try testing.expectEqualSlices(u8, list.items, "aoeuasdf");
}
{
var list = ArrayListUnmanaged(u8){};
@ -1247,7 +1247,7 @@ test "std.ArrayList/ArrayListUnmanaged.addManyAsArray" {
try list.ensureTotalCapacity(a, 8);
list.addManyAsArrayAssumeCapacity(4).* = "asdf".*;
testing.expectEqualSlices(u8, list.items, "aoeuasdf");
try testing.expectEqualSlices(u8, list.items, "aoeuasdf");
}
}
@ -1261,7 +1261,7 @@ test "std.ArrayList/ArrayListUnmanaged.toOwnedSliceSentinel" {
const result = try list.toOwnedSliceSentinel(0);
defer a.free(result);
testing.expectEqualStrings(result, mem.spanZ(result.ptr));
try testing.expectEqualStrings(result, mem.spanZ(result.ptr));
}
{
var list = ArrayListUnmanaged(u8){};
@ -1271,7 +1271,7 @@ test "std.ArrayList/ArrayListUnmanaged.toOwnedSliceSentinel" {
const result = try list.toOwnedSliceSentinel(a, 0);
defer a.free(result);
testing.expectEqualStrings(result, mem.spanZ(result.ptr));
try testing.expectEqualStrings(result, mem.spanZ(result.ptr));
}
}
@ -1285,7 +1285,7 @@ test "ArrayListAligned/ArrayListAlignedUnmanaged accepts unaligned slices" {
try list.insertSlice(2, &.{ 4, 5, 6, 7 });
try list.replaceRange(1, 3, &.{ 8, 9 });
testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });
try testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });
}
{
var list = std.ArrayListAlignedUnmanaged(u8, 8){};
@ -1295,6 +1295,6 @@ test "ArrayListAligned/ArrayListAlignedUnmanaged accepts unaligned slices" {
try list.insertSlice(a, 2, &.{ 4, 5, 6, 7 });
try list.replaceRange(a, 1, 3, &.{ 8, 9 });
testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });
try testing.expectEqualSlices(u8, list.items, &.{ 0, 8, 9, 6, 7, 2, 3 });
}
}

View File

@ -236,11 +236,11 @@ pub const spaces = [_]u8{ ' ', '\t', '\n', '\r', control_code.VT, control_code.F
test "spaces" {
const testing = std.testing;
for (spaces) |space| testing.expect(isSpace(space));
for (spaces) |space| try testing.expect(isSpace(space));
var i: u8 = 0;
while (isASCII(i)) : (i += 1) {
if (isSpace(i)) testing.expect(std.mem.indexOfScalar(u8, &spaces, i) != null);
if (isSpace(i)) try testing.expect(std.mem.indexOfScalar(u8, &spaces, i) != null);
}
}
@ -279,13 +279,13 @@ pub fn toLower(c: u8) u8 {
test "ascii character classes" {
const testing = std.testing;
testing.expect('C' == toUpper('c'));
testing.expect(':' == toUpper(':'));
testing.expect('\xab' == toUpper('\xab'));
testing.expect('c' == toLower('C'));
testing.expect(isAlpha('c'));
testing.expect(!isAlpha('5'));
testing.expect(isSpace(' '));
try testing.expect('C' == toUpper('c'));
try testing.expect(':' == toUpper(':'));
try testing.expect('\xab' == toUpper('\xab'));
try testing.expect('c' == toLower('C'));
try testing.expect(isAlpha('c'));
try testing.expect(!isAlpha('5'));
try testing.expect(isSpace(' '));
}
/// Allocates a lower case copy of `ascii_string`.
@ -301,7 +301,7 @@ pub fn allocLowerString(allocator: *std.mem.Allocator, ascii_string: []const u8)
test "allocLowerString" {
const result = try allocLowerString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
std.testing.expect(std.mem.eql(u8, "abcdefghijklmnopqrst0234+💩!", result));
try std.testing.expect(std.mem.eql(u8, "abcdefghijklmnopqrst0234+💩!", result));
}
/// Allocates an upper case copy of `ascii_string`.
@ -317,7 +317,7 @@ pub fn allocUpperString(allocator: *std.mem.Allocator, ascii_string: []const u8)
test "allocUpperString" {
const result = try allocUpperString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result);
std.testing.expect(std.mem.eql(u8, "ABCDEFGHIJKLMNOPQRST0234+💩!", result));
try std.testing.expect(std.mem.eql(u8, "ABCDEFGHIJKLMNOPQRST0234+💩!", result));
}
/// Compares strings `a` and `b` case insensitively and returns whether they are equal.
@ -330,9 +330,9 @@ pub fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {
}
test "eqlIgnoreCase" {
std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!"));
std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! "));
std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!"));
try std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!"));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! "));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!"));
}
pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
@ -340,8 +340,8 @@ pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
}
test "ascii.startsWithIgnoreCase" {
std.testing.expect(startsWithIgnoreCase("boB", "Bo"));
std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack"));
try std.testing.expect(startsWithIgnoreCase("boB", "Bo"));
try std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack"));
}
pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
@ -349,8 +349,8 @@ pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
}
test "ascii.endsWithIgnoreCase" {
std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack"));
std.testing.expect(!endsWithIgnoreCase("BoB", "Bo"));
try std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack"));
try std.testing.expect(!endsWithIgnoreCase("BoB", "Bo"));
}
/// Finds `substr` in `container`, ignoring case, starting at `start_index`.
@ -372,12 +372,12 @@ pub fn indexOfIgnoreCase(container: []const u8, substr: []const u8) ?usize {
}
test "indexOfIgnoreCase" {
std.testing.expect(indexOfIgnoreCase("one Two Three Four", "foUr").? == 14);
std.testing.expect(indexOfIgnoreCase("one two three FouR", "gOur") == null);
std.testing.expect(indexOfIgnoreCase("foO", "Foo").? == 0);
std.testing.expect(indexOfIgnoreCase("foo", "fool") == null);
try std.testing.expect(indexOfIgnoreCase("one Two Three Four", "foUr").? == 14);
try std.testing.expect(indexOfIgnoreCase("one two three FouR", "gOur") == null);
try std.testing.expect(indexOfIgnoreCase("foO", "Foo").? == 0);
try std.testing.expect(indexOfIgnoreCase("foo", "fool") == null);
std.testing.expect(indexOfIgnoreCase("FOO foo", "fOo").? == 0);
try std.testing.expect(indexOfIgnoreCase("FOO foo", "fOo").? == 0);
}
/// Compares two slices of numbers lexicographically. O(n).

View File

@ -47,9 +47,9 @@ pub const Bool = extern struct {
test "std.atomic.Bool" {
var a = Bool.init(false);
testing.expectEqual(false, a.xchg(false, .SeqCst));
testing.expectEqual(false, a.load(.SeqCst));
try testing.expectEqual(false, a.xchg(false, .SeqCst));
try testing.expectEqual(false, a.load(.SeqCst));
a.store(true, .SeqCst);
testing.expectEqual(true, a.xchg(false, .SeqCst));
testing.expectEqual(false, a.load(.SeqCst));
try testing.expectEqual(true, a.xchg(false, .SeqCst));
try testing.expectEqual(false, a.load(.SeqCst));
}

View File

@ -81,12 +81,12 @@ pub fn Int(comptime T: type) type {
test "std.atomic.Int" {
var a = Int(u8).init(0);
testing.expectEqual(@as(u8, 0), a.incr());
testing.expectEqual(@as(u8, 1), a.load(.SeqCst));
try testing.expectEqual(@as(u8, 0), a.incr());
try testing.expectEqual(@as(u8, 1), a.load(.SeqCst));
a.store(42, .SeqCst);
testing.expectEqual(@as(u8, 42), a.decr());
testing.expectEqual(@as(u8, 41), a.xchg(100));
testing.expectEqual(@as(u8, 100), a.fetchAdd(5));
testing.expectEqual(@as(u8, 105), a.get());
try testing.expectEqual(@as(u8, 42), a.decr());
try testing.expectEqual(@as(u8, 41), a.xchg(100));
try testing.expectEqual(@as(u8, 100), a.fetchAdd(5));
try testing.expectEqual(@as(u8, 105), a.get());
a.set(200);
}

View File

@ -195,24 +195,24 @@ test "std.atomic.Queue" {
};
if (builtin.single_threaded) {
expect(context.queue.isEmpty());
try expect(context.queue.isEmpty());
{
var i: usize = 0;
while (i < put_thread_count) : (i += 1) {
expect(startPuts(&context) == 0);
try expect(startPuts(&context) == 0);
}
}
expect(!context.queue.isEmpty());
try expect(!context.queue.isEmpty());
context.puts_done = true;
{
var i: usize = 0;
while (i < put_thread_count) : (i += 1) {
expect(startGets(&context) == 0);
try expect(startGets(&context) == 0);
}
}
expect(context.queue.isEmpty());
try expect(context.queue.isEmpty());
} else {
expect(context.queue.isEmpty());
try expect(context.queue.isEmpty());
var putters: [put_thread_count]*std.Thread = undefined;
for (putters) |*t| {
@ -229,7 +229,7 @@ test "std.atomic.Queue" {
for (getters) |t|
t.wait();
expect(context.queue.isEmpty());
try expect(context.queue.isEmpty());
}
if (context.put_sum != context.get_sum) {
@ -279,7 +279,7 @@ fn startGets(ctx: *Context) u8 {
test "std.atomic.Queue single-threaded" {
var queue = Queue(i32).init();
expect(queue.isEmpty());
try expect(queue.isEmpty());
var node_0 = Queue(i32).Node{
.data = 0,
@ -287,7 +287,7 @@ test "std.atomic.Queue single-threaded" {
.prev = undefined,
};
queue.put(&node_0);
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
var node_1 = Queue(i32).Node{
.data = 1,
@ -295,10 +295,10 @@ test "std.atomic.Queue single-threaded" {
.prev = undefined,
};
queue.put(&node_1);
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
expect(queue.get().?.data == 0);
expect(!queue.isEmpty());
try expect(queue.get().?.data == 0);
try expect(!queue.isEmpty());
var node_2 = Queue(i32).Node{
.data = 2,
@ -306,7 +306,7 @@ test "std.atomic.Queue single-threaded" {
.prev = undefined,
};
queue.put(&node_2);
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
var node_3 = Queue(i32).Node{
.data = 3,
@ -314,13 +314,13 @@ test "std.atomic.Queue single-threaded" {
.prev = undefined,
};
queue.put(&node_3);
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
expect(queue.get().?.data == 1);
expect(!queue.isEmpty());
try expect(queue.get().?.data == 1);
try expect(!queue.isEmpty());
expect(queue.get().?.data == 2);
expect(!queue.isEmpty());
try expect(queue.get().?.data == 2);
try expect(!queue.isEmpty());
var node_4 = Queue(i32).Node{
.data = 4,
@ -328,17 +328,17 @@ test "std.atomic.Queue single-threaded" {
.prev = undefined,
};
queue.put(&node_4);
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
expect(queue.get().?.data == 3);
try expect(queue.get().?.data == 3);
node_3.next = null;
expect(!queue.isEmpty());
try expect(!queue.isEmpty());
expect(queue.get().?.data == 4);
expect(queue.isEmpty());
try expect(queue.get().?.data == 4);
try expect(queue.isEmpty());
expect(queue.get() == null);
expect(queue.isEmpty());
try expect(queue.get() == null);
try expect(queue.isEmpty());
}
test "std.atomic.Queue dump" {
@ -352,7 +352,7 @@ test "std.atomic.Queue dump" {
// Test empty stream
fbs.reset();
try queue.dumpToStream(fbs.writer());
expect(mem.eql(u8, buffer[0..fbs.pos],
try expect(mem.eql(u8, buffer[0..fbs.pos],
\\head: (null)
\\tail: (null)
\\
@ -376,7 +376,7 @@ test "std.atomic.Queue dump" {
\\ (null)
\\
, .{ @ptrToInt(queue.head), @ptrToInt(queue.tail) });
expect(mem.eql(u8, buffer[0..fbs.pos], expected));
try expect(mem.eql(u8, buffer[0..fbs.pos], expected));
// Test a stream with two elements
var node_1 = Queue(i32).Node{
@ -397,5 +397,5 @@ test "std.atomic.Queue dump" {
\\ (null)
\\
, .{ @ptrToInt(queue.head), @ptrToInt(queue.head.?.next), @ptrToInt(queue.tail) });
expect(mem.eql(u8, buffer[0..fbs.pos], expected));
try expect(mem.eql(u8, buffer[0..fbs.pos], expected));
}

View File

@ -110,14 +110,14 @@ test "std.atomic.stack" {
{
var i: usize = 0;
while (i < put_thread_count) : (i += 1) {
expect(startPuts(&context) == 0);
try expect(startPuts(&context) == 0);
}
}
context.puts_done = true;
{
var i: usize = 0;
while (i < put_thread_count) : (i += 1) {
expect(startGets(&context) == 0);
try expect(startGets(&context) == 0);
}
}
} else {

View File

@ -318,14 +318,14 @@ pub const Base64DecoderWithIgnore = struct {
test "base64" {
@setEvalBranchQuota(8000);
testBase64() catch unreachable;
comptime testAllApis(standard, "comptime", "Y29tcHRpbWU=") catch unreachable;
try testBase64();
comptime try testAllApis(standard, "comptime", "Y29tcHRpbWU=");
}
test "base64 url_safe_no_pad" {
@setEvalBranchQuota(8000);
testBase64UrlSafeNoPad() catch unreachable;
comptime testAllApis(url_safe_no_pad, "comptime", "Y29tcHRpbWU") catch unreachable;
try testBase64UrlSafeNoPad();
comptime try testAllApis(url_safe_no_pad, "comptime", "Y29tcHRpbWU");
}
fn testBase64() !void {
@ -404,7 +404,7 @@ fn testAllApis(codecs: Codecs, expected_decoded: []const u8, expected_encoded: [
{
var buffer: [0x100]u8 = undefined;
const encoded = codecs.Encoder.encode(&buffer, expected_decoded);
testing.expectEqualSlices(u8, expected_encoded, encoded);
try testing.expectEqualSlices(u8, expected_encoded, encoded);
}
// Base64Decoder
@ -412,7 +412,7 @@ fn testAllApis(codecs: Codecs, expected_decoded: []const u8, expected_encoded: [
var buffer: [0x100]u8 = undefined;
var decoded = buffer[0..try codecs.Decoder.calcSizeForSlice(expected_encoded)];
try codecs.Decoder.decode(decoded, expected_encoded);
testing.expectEqualSlices(u8, expected_decoded, decoded);
try testing.expectEqualSlices(u8, expected_decoded, decoded);
}
// Base64DecoderWithIgnore
@ -421,8 +421,8 @@ fn testAllApis(codecs: Codecs, expected_decoded: []const u8, expected_encoded: [
var buffer: [0x100]u8 = undefined;
var decoded = buffer[0..try decoder_ignore_nothing.calcSizeUpperBound(expected_encoded.len)];
var written = try decoder_ignore_nothing.decode(decoded, expected_encoded);
testing.expect(written <= decoded.len);
testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
try testing.expect(written <= decoded.len);
try testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
}
}
@ -431,7 +431,7 @@ fn testDecodeIgnoreSpace(codecs: Codecs, expected_decoded: []const u8, encoded:
var buffer: [0x100]u8 = undefined;
var decoded = buffer[0..try decoder_ignore_space.calcSizeUpperBound(encoded.len)];
var written = try decoder_ignore_space.decode(decoded, encoded);
testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
try testing.expectEqualSlices(u8, expected_decoded, decoded[0..written]);
}
fn testError(codecs: Codecs, encoded: []const u8, expected_err: anyerror) !void {

View File

@ -998,9 +998,9 @@ fn BitSetIterator(comptime MaskInt: type, comptime options: IteratorOptions) typ
const testing = std.testing;
fn testBitSet(a: anytype, b: anytype, len: usize) void {
testing.expectEqual(len, a.capacity());
testing.expectEqual(len, b.capacity());
fn testBitSet(a: anytype, b: anytype, len: usize) !void {
try testing.expectEqual(len, a.capacity());
try testing.expectEqual(len, b.capacity());
{
var i: usize = 0;
@ -1010,50 +1010,50 @@ fn testBitSet(a: anytype, b: anytype, len: usize) void {
}
}
testing.expectEqual((len + 1) / 2, a.count());
testing.expectEqual((len + 3) / 4 + (len + 2) / 4, b.count());
try testing.expectEqual((len + 1) / 2, a.count());
try testing.expectEqual((len + 3) / 4 + (len + 2) / 4, b.count());
{
var iter = a.iterator(.{});
var i: usize = 0;
while (i < len) : (i += 2) {
testing.expectEqual(@as(?usize, i), iter.next());
try testing.expectEqual(@as(?usize, i), iter.next());
}
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
}
a.toggleAll();
{
var iter = a.iterator(.{});
var i: usize = 1;
while (i < len) : (i += 2) {
testing.expectEqual(@as(?usize, i), iter.next());
try testing.expectEqual(@as(?usize, i), iter.next());
}
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
}
{
var iter = b.iterator(.{ .kind = .unset });
var i: usize = 2;
while (i < len) : (i += 4) {
testing.expectEqual(@as(?usize, i), iter.next());
try testing.expectEqual(@as(?usize, i), iter.next());
if (i + 1 < len) {
testing.expectEqual(@as(?usize, i + 1), iter.next());
try testing.expectEqual(@as(?usize, i + 1), iter.next());
}
}
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
}
{
var i: usize = 0;
while (i < len) : (i += 1) {
testing.expectEqual(i & 1 != 0, a.isSet(i));
testing.expectEqual(i & 2 == 0, b.isSet(i));
try testing.expectEqual(i & 1 != 0, a.isSet(i));
try testing.expectEqual(i & 2 == 0, b.isSet(i));
}
}
@ -1061,8 +1061,8 @@ fn testBitSet(a: anytype, b: anytype, len: usize) void {
{
var i: usize = 0;
while (i < len) : (i += 1) {
testing.expectEqual(i & 1 != 0 or i & 2 == 0, a.isSet(i));
testing.expectEqual(i & 2 == 0, b.isSet(i));
try testing.expectEqual(i & 1 != 0 or i & 2 == 0, a.isSet(i));
try testing.expectEqual(i & 2 == 0, b.isSet(i));
}
i = len;
@ -1071,27 +1071,27 @@ fn testBitSet(a: anytype, b: anytype, len: usize) void {
while (i > 0) {
i -= 1;
if (i & 1 != 0 or i & 2 == 0) {
testing.expectEqual(@as(?usize, i), set.next());
try testing.expectEqual(@as(?usize, i), set.next());
} else {
testing.expectEqual(@as(?usize, i), unset.next());
try testing.expectEqual(@as(?usize, i), unset.next());
}
}
testing.expectEqual(@as(?usize, null), set.next());
testing.expectEqual(@as(?usize, null), set.next());
testing.expectEqual(@as(?usize, null), set.next());
testing.expectEqual(@as(?usize, null), unset.next());
testing.expectEqual(@as(?usize, null), unset.next());
testing.expectEqual(@as(?usize, null), unset.next());
try testing.expectEqual(@as(?usize, null), set.next());
try testing.expectEqual(@as(?usize, null), set.next());
try testing.expectEqual(@as(?usize, null), set.next());
try testing.expectEqual(@as(?usize, null), unset.next());
try testing.expectEqual(@as(?usize, null), unset.next());
try testing.expectEqual(@as(?usize, null), unset.next());
}
a.toggleSet(b.*);
{
testing.expectEqual(len / 4, a.count());
try testing.expectEqual(len / 4, a.count());
var i: usize = 0;
while (i < len) : (i += 1) {
testing.expectEqual(i & 1 != 0 and i & 2 != 0, a.isSet(i));
testing.expectEqual(i & 2 == 0, b.isSet(i));
try testing.expectEqual(i & 1 != 0 and i & 2 != 0, a.isSet(i));
try testing.expectEqual(i & 2 == 0, b.isSet(i));
if (i & 1 == 0) {
a.set(i);
} else {
@ -1102,29 +1102,29 @@ fn testBitSet(a: anytype, b: anytype, len: usize) void {
a.setIntersection(b.*);
{
testing.expectEqual((len + 3) / 4, a.count());
try testing.expectEqual((len + 3) / 4, a.count());
var i: usize = 0;
while (i < len) : (i += 1) {
testing.expectEqual(i & 1 == 0 and i & 2 == 0, a.isSet(i));
testing.expectEqual(i & 2 == 0, b.isSet(i));
try testing.expectEqual(i & 1 == 0 and i & 2 == 0, a.isSet(i));
try testing.expectEqual(i & 2 == 0, b.isSet(i));
}
}
a.toggleSet(a.*);
{
var iter = a.iterator(.{});
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(usize, 0), a.count());
}
{
var iter = a.iterator(.{ .direction = .reverse });
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(?usize, null), iter.next());
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(?usize, null), iter.next());
try testing.expectEqual(@as(usize, 0), a.count());
}
const test_bits = [_]usize{
@ -1139,51 +1139,51 @@ fn testBitSet(a: anytype, b: anytype, len: usize) void {
for (test_bits) |i| {
if (i < a.capacity()) {
testing.expectEqual(@as(?usize, i), a.findFirstSet());
testing.expectEqual(@as(?usize, i), a.toggleFirstSet());
try testing.expectEqual(@as(?usize, i), a.findFirstSet());
try testing.expectEqual(@as(?usize, i), a.toggleFirstSet());
}
}
testing.expectEqual(@as(?usize, null), a.findFirstSet());
testing.expectEqual(@as(?usize, null), a.toggleFirstSet());
testing.expectEqual(@as(?usize, null), a.findFirstSet());
testing.expectEqual(@as(?usize, null), a.toggleFirstSet());
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(?usize, null), a.findFirstSet());
try testing.expectEqual(@as(?usize, null), a.toggleFirstSet());
try testing.expectEqual(@as(?usize, null), a.findFirstSet());
try testing.expectEqual(@as(?usize, null), a.toggleFirstSet());
try testing.expectEqual(@as(usize, 0), a.count());
}
fn testStaticBitSet(comptime Set: type) void {
fn testStaticBitSet(comptime Set: type) !void {
var a = Set.initEmpty();
var b = Set.initFull();
testing.expectEqual(@as(usize, 0), a.count());
testing.expectEqual(@as(usize, Set.bit_length), b.count());
try testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(usize, Set.bit_length), b.count());
testBitSet(&a, &b, Set.bit_length);
try testBitSet(&a, &b, Set.bit_length);
}
test "IntegerBitSet" {
testStaticBitSet(IntegerBitSet(0));
testStaticBitSet(IntegerBitSet(1));
testStaticBitSet(IntegerBitSet(2));
testStaticBitSet(IntegerBitSet(5));
testStaticBitSet(IntegerBitSet(8));
testStaticBitSet(IntegerBitSet(32));
testStaticBitSet(IntegerBitSet(64));
testStaticBitSet(IntegerBitSet(127));
try testStaticBitSet(IntegerBitSet(0));
try testStaticBitSet(IntegerBitSet(1));
try testStaticBitSet(IntegerBitSet(2));
try testStaticBitSet(IntegerBitSet(5));
try testStaticBitSet(IntegerBitSet(8));
try testStaticBitSet(IntegerBitSet(32));
try testStaticBitSet(IntegerBitSet(64));
try testStaticBitSet(IntegerBitSet(127));
}
test "ArrayBitSet" {
inline for (.{ 0, 1, 2, 31, 32, 33, 63, 64, 65, 254, 500, 3000 }) |size| {
testStaticBitSet(ArrayBitSet(u8, size));
testStaticBitSet(ArrayBitSet(u16, size));
testStaticBitSet(ArrayBitSet(u32, size));
testStaticBitSet(ArrayBitSet(u64, size));
testStaticBitSet(ArrayBitSet(u128, size));
try testStaticBitSet(ArrayBitSet(u8, size));
try testStaticBitSet(ArrayBitSet(u16, size));
try testStaticBitSet(ArrayBitSet(u32, size));
try testStaticBitSet(ArrayBitSet(u64, size));
try testStaticBitSet(ArrayBitSet(u128, size));
}
}
test "DynamicBitSetUnmanaged" {
const allocator = std.testing.allocator;
var a = try DynamicBitSetUnmanaged.initEmpty(300, allocator);
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(usize, 0), a.count());
a.deinit(allocator);
a = try DynamicBitSetUnmanaged.initEmpty(0, allocator);
@ -1193,10 +1193,10 @@ test "DynamicBitSetUnmanaged" {
var tmp = try a.clone(allocator);
defer tmp.deinit(allocator);
testing.expectEqual(old_len, tmp.capacity());
try testing.expectEqual(old_len, tmp.capacity());
var i: usize = 0;
while (i < old_len) : (i += 1) {
testing.expectEqual(a.isSet(i), tmp.isSet(i));
try testing.expectEqual(a.isSet(i), tmp.isSet(i));
}
a.toggleSet(a); // zero a
@ -1206,24 +1206,24 @@ test "DynamicBitSetUnmanaged" {
try tmp.resize(size, false, allocator);
if (size > old_len) {
testing.expectEqual(size - old_len, a.count());
try testing.expectEqual(size - old_len, a.count());
} else {
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(usize, 0), a.count());
}
testing.expectEqual(@as(usize, 0), tmp.count());
try testing.expectEqual(@as(usize, 0), tmp.count());
var b = try DynamicBitSetUnmanaged.initFull(size, allocator);
defer b.deinit(allocator);
testing.expectEqual(@as(usize, size), b.count());
try testing.expectEqual(@as(usize, size), b.count());
testBitSet(&a, &b, size);
try testBitSet(&a, &b, size);
}
}
test "DynamicBitSet" {
const allocator = std.testing.allocator;
var a = try DynamicBitSet.initEmpty(300, allocator);
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(usize, 0), a.count());
a.deinit();
a = try DynamicBitSet.initEmpty(0, allocator);
@ -1233,10 +1233,10 @@ test "DynamicBitSet" {
var tmp = try a.clone(allocator);
defer tmp.deinit();
testing.expectEqual(old_len, tmp.capacity());
try testing.expectEqual(old_len, tmp.capacity());
var i: usize = 0;
while (i < old_len) : (i += 1) {
testing.expectEqual(a.isSet(i), tmp.isSet(i));
try testing.expectEqual(a.isSet(i), tmp.isSet(i));
}
a.toggleSet(a); // zero a
@ -1246,24 +1246,24 @@ test "DynamicBitSet" {
try tmp.resize(size, false);
if (size > old_len) {
testing.expectEqual(size - old_len, a.count());
try testing.expectEqual(size - old_len, a.count());
} else {
testing.expectEqual(@as(usize, 0), a.count());
try testing.expectEqual(@as(usize, 0), a.count());
}
testing.expectEqual(@as(usize, 0), tmp.count());
try testing.expectEqual(@as(usize, 0), tmp.count());
var b = try DynamicBitSet.initFull(size, allocator);
defer b.deinit();
testing.expectEqual(@as(usize, size), b.count());
try testing.expectEqual(@as(usize, size), b.count());
testBitSet(&a, &b, size);
try testBitSet(&a, &b, size);
}
}
test "StaticBitSet" {
testing.expectEqual(IntegerBitSet(0), StaticBitSet(0));
testing.expectEqual(IntegerBitSet(5), StaticBitSet(5));
testing.expectEqual(IntegerBitSet(@bitSizeOf(usize)), StaticBitSet(@bitSizeOf(usize)));
testing.expectEqual(ArrayBitSet(usize, @bitSizeOf(usize) + 1), StaticBitSet(@bitSizeOf(usize) + 1));
testing.expectEqual(ArrayBitSet(usize, 500), StaticBitSet(500));
try testing.expectEqual(IntegerBitSet(0), StaticBitSet(0));
try testing.expectEqual(IntegerBitSet(5), StaticBitSet(5));
try testing.expectEqual(IntegerBitSet(@bitSizeOf(usize)), StaticBitSet(@bitSizeOf(usize)));
try testing.expectEqual(ArrayBitSet(usize, @bitSizeOf(usize) + 1), StaticBitSet(@bitSizeOf(usize) + 1));
try testing.expectEqual(ArrayBitSet(usize, 500), StaticBitSet(500));
}

View File

@ -94,19 +94,19 @@ test "BufMap" {
defer bufmap.deinit();
try bufmap.set("x", "1");
testing.expect(mem.eql(u8, bufmap.get("x").?, "1"));
testing.expect(1 == bufmap.count());
try testing.expect(mem.eql(u8, bufmap.get("x").?, "1"));
try testing.expect(1 == bufmap.count());
try bufmap.set("x", "2");
testing.expect(mem.eql(u8, bufmap.get("x").?, "2"));
testing.expect(1 == bufmap.count());
try testing.expect(mem.eql(u8, bufmap.get("x").?, "2"));
try testing.expect(1 == bufmap.count());
try bufmap.set("x", "3");
testing.expect(mem.eql(u8, bufmap.get("x").?, "3"));
testing.expect(1 == bufmap.count());
try testing.expect(mem.eql(u8, bufmap.get("x").?, "3"));
try testing.expect(1 == bufmap.count());
bufmap.delete("x");
testing.expect(0 == bufmap.count());
try testing.expect(0 == bufmap.count());
try bufmap.setMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v1"));
try bufmap.setMove(try allocator.dupe(u8, "k"), try allocator.dupe(u8, "v2"));

View File

@ -73,9 +73,9 @@ test "BufSet" {
defer bufset.deinit();
try bufset.put("x");
testing.expect(bufset.count() == 1);
try testing.expect(bufset.count() == 1);
bufset.delete("x");
testing.expect(bufset.count() == 0);
try testing.expect(bufset.count() == 0);
try bufset.put("x");
try bufset.put("y");

View File

@ -3060,19 +3060,19 @@ test "Builder.dupePkg()" {
const dupe_deps = dupe.dependencies.?;
// probably the same top level package details
std.testing.expectEqualStrings(pkg_top.name, dupe.name);
try std.testing.expectEqualStrings(pkg_top.name, dupe.name);
// probably the same dependencies
std.testing.expectEqual(original_deps.len, dupe_deps.len);
std.testing.expectEqual(original_deps[0].name, pkg_dep.name);
try std.testing.expectEqual(original_deps.len, dupe_deps.len);
try std.testing.expectEqual(original_deps[0].name, pkg_dep.name);
// could segfault otherwise if pointers in duplicated package's fields are
// the same as those in stack allocated package's fields
std.testing.expect(dupe_deps.ptr != original_deps.ptr);
std.testing.expect(dupe.name.ptr != pkg_top.name.ptr);
std.testing.expect(dupe.path.ptr != pkg_top.path.ptr);
std.testing.expect(dupe_deps[0].name.ptr != pkg_dep.name.ptr);
std.testing.expect(dupe_deps[0].path.ptr != pkg_dep.path.ptr);
try std.testing.expect(dupe_deps.ptr != original_deps.ptr);
try std.testing.expect(dupe.name.ptr != pkg_top.name.ptr);
try std.testing.expect(dupe.path.ptr != pkg_top.path.ptr);
try std.testing.expect(dupe_deps[0].name.ptr != pkg_dep.name.ptr);
try std.testing.expect(dupe_deps[0].path.ptr != pkg_dep.path.ptr);
}
test "LibExeObjStep.addBuildOption" {
@ -3096,7 +3096,7 @@ test "LibExeObjStep.addBuildOption" {
exe.addBuildOption(?[]const u8, "optional_string", null);
exe.addBuildOption(std.SemanticVersion, "semantic_version", try std.SemanticVersion.parse("0.1.2-foo+bar"));
std.testing.expectEqualStrings(
try std.testing.expectEqualStrings(
\\pub const option1: usize = 1;
\\pub const option2: ?usize = null;
\\pub const string: []const u8 = "zigisthebest";
@ -3140,10 +3140,10 @@ test "LibExeObjStep.addPackage" {
var exe = builder.addExecutable("not_an_executable", "/not/an/executable.zig");
exe.addPackage(pkg_top);
std.testing.expectEqual(@as(usize, 1), exe.packages.items.len);
try std.testing.expectEqual(@as(usize, 1), exe.packages.items.len);
const dupe = exe.packages.items[0];
std.testing.expectEqualStrings(pkg_top.name, dupe.name);
try std.testing.expectEqualStrings(pkg_top.name, dupe.name);
}
test {

View File

@ -547,7 +547,7 @@ pub fn testVersionParse() !void {
const f = struct {
fn eql(text: []const u8, v1: u32, v2: u32, v3: u32) !void {
const v = try Version.parse(text);
std.testing.expect(v.major == v1 and v.minor == v2 and v.patch == v3);
try std.testing.expect(v.major == v1 and v.minor == v2 and v.patch == v3);
}
fn err(text: []const u8, expected_err: anyerror) !void {

View File

@ -1310,7 +1310,7 @@ pub const Tokenizer = struct {
};
test "operators" {
expectTokens(
try expectTokens(
\\ ! != | || |= = ==
\\ ( ) { } [ ] . .. ...
\\ ^ ^= + ++ += - -- -=
@ -1379,7 +1379,7 @@ test "operators" {
}
test "keywords" {
expectTokens(
try expectTokens(
\\auto break case char const continue default do
\\double else enum extern float for goto if int
\\long register return short signed sizeof static
@ -1442,7 +1442,7 @@ test "keywords" {
}
test "preprocessor keywords" {
expectTokens(
try expectTokens(
\\#include <test>
\\#define #include <1
\\#ifdef
@ -1478,7 +1478,7 @@ test "preprocessor keywords" {
}
test "line continuation" {
expectTokens(
try expectTokens(
\\#define foo \
\\ bar
\\"foo\
@ -1509,7 +1509,7 @@ test "line continuation" {
}
test "string prefix" {
expectTokens(
try expectTokens(
\\"foo"
\\u"foo"
\\u8"foo"
@ -1543,7 +1543,7 @@ test "string prefix" {
}
test "num suffixes" {
expectTokens(
try expectTokens(
\\ 1.0f 1.0L 1.0 .0 1.
\\ 0l 0lu 0ll 0llu 0
\\ 1u 1ul 1ull 1
@ -1573,7 +1573,7 @@ test "num suffixes" {
});
}
fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) void {
fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) !void {
var tokenizer = Tokenizer{
.buffer = source,
};
@ -1584,5 +1584,5 @@ fn expectTokens(source: []const u8, expected_tokens: []const Token.Id) void {
}
}
const last_token = tokenizer.next();
std.testing.expect(last_token.id == .Eof);
try std.testing.expect(last_token.id == .Eof);
}

View File

@ -1005,7 +1005,7 @@ test "createNullDelimitedEnvMap" {
defer arena.deinit();
const environ = try createNullDelimitedEnvMap(&arena.allocator, &envmap);
testing.expectEqual(@as(usize, 5), environ.len);
try testing.expectEqual(@as(usize, 5), environ.len);
inline for (.{
"HOME=/home/ifreund",
@ -1017,7 +1017,7 @@ test "createNullDelimitedEnvMap" {
for (environ) |variable| {
if (mem.eql(u8, mem.span(variable orelse continue), target)) break;
} else {
testing.expect(false); // Environment variable not found
try testing.expect(false); // Environment variable not found
}
}
}

View File

@ -669,5 +669,5 @@ test "lengths overflow" {
var inflate = inflateStream(reader, &window);
var buf: [1]u8 = undefined;
std.testing.expectError(error.InvalidLength, inflate.read(&buf));
try std.testing.expectError(error.InvalidLength, inflate.read(&buf));
}

View File

@ -172,17 +172,17 @@ fn testReader(data: []const u8, comptime expected: []const u8) !void {
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(buf, hash[0..], .{});
assertEqual(expected, &hash);
try assertEqual(expected, &hash);
}
// Assert `expected` == `input` where `input` is a bytestring.
pub fn assertEqual(comptime expected: []const u8, input: []const u8) void {
pub fn assertEqual(comptime expected: []const u8, input: []const u8) !void {
var expected_bytes: [expected.len / 2]u8 = undefined;
for (expected_bytes) |*r, i| {
r.* = std.fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
}
testing.expectEqualSlices(u8, &expected_bytes, input);
try testing.expectEqualSlices(u8, &expected_bytes, input);
}
// All the test cases are obtained by compressing the RFC1952 text
@ -198,12 +198,12 @@ test "compressed data" {
test "sanity checks" {
// Truncated header
testing.expectError(
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{ 0x1f, 0x8B }, ""),
);
// Wrong CM
testing.expectError(
try testing.expectError(
error.InvalidCompression,
testReader(&[_]u8{
0x1f, 0x8b, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -211,7 +211,7 @@ test "sanity checks" {
}, ""),
);
// Wrong checksum
testing.expectError(
try testing.expectError(
error.WrongChecksum,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -220,7 +220,7 @@ test "sanity checks" {
}, ""),
);
// Truncated checksum
testing.expectError(
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -228,7 +228,7 @@ test "sanity checks" {
}, ""),
);
// Wrong initial size
testing.expectError(
try testing.expectError(
error.CorruptedData,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,
@ -237,7 +237,7 @@ test "sanity checks" {
}, ""),
);
// Truncated initial size field
testing.expectError(
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00,

View File

@ -109,17 +109,17 @@ fn testReader(data: []const u8, comptime expected: []const u8) !void {
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(buf, hash[0..], .{});
assertEqual(expected, &hash);
try assertEqual(expected, &hash);
}
// Assert `expected` == `input` where `input` is a bytestring.
pub fn assertEqual(comptime expected: []const u8, input: []const u8) void {
pub fn assertEqual(comptime expected: []const u8, input: []const u8) !void {
var expected_bytes: [expected.len / 2]u8 = undefined;
for (expected_bytes) |*r, i| {
r.* = std.fmt.parseInt(u8, expected[2 * i .. 2 * i + 2], 16) catch unreachable;
}
testing.expectEqualSlices(u8, &expected_bytes, input);
try testing.expectEqualSlices(u8, &expected_bytes, input);
}
// All the test cases are obtained by compressing the RFC1950 text
@ -159,32 +159,32 @@ test "don't read past deflate stream's end" {
test "sanity checks" {
// Truncated header
testing.expectError(
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{0x78}, ""),
);
// Failed FCHECK check
testing.expectError(
try testing.expectError(
error.BadHeader,
testReader(&[_]u8{ 0x78, 0x9D }, ""),
);
// Wrong CM
testing.expectError(
try testing.expectError(
error.InvalidCompression,
testReader(&[_]u8{ 0x79, 0x94 }, ""),
);
// Wrong CINFO
testing.expectError(
try testing.expectError(
error.InvalidWindowSize,
testReader(&[_]u8{ 0x88, 0x98 }, ""),
);
// Wrong checksum
testing.expectError(
try testing.expectError(
error.WrongChecksum,
testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00 }, ""),
);
// Truncated checksum
testing.expectError(
try testing.expectError(
error.EndOfStream,
testReader(&[_]u8{ 0x78, 0xda, 0x03, 0x00, 0x00 }, ""),
);

View File

@ -95,7 +95,7 @@ test "ComptimeStringMap list literal of list literals" {
.{ "samelen", .E },
});
testMap(map);
try testMap(map);
}
test "ComptimeStringMap array of structs" {
@ -111,7 +111,7 @@ test "ComptimeStringMap array of structs" {
.{ .@"0" = "samelen", .@"1" = .E },
});
testMap(map);
try testMap(map);
}
test "ComptimeStringMap slice of structs" {
@ -128,18 +128,18 @@ test "ComptimeStringMap slice of structs" {
};
const map = ComptimeStringMap(TestEnum, slice);
testMap(map);
try testMap(map);
}
fn testMap(comptime map: anytype) void {
std.testing.expectEqual(TestEnum.A, map.get("have").?);
std.testing.expectEqual(TestEnum.B, map.get("nothing").?);
std.testing.expect(null == map.get("missing"));
std.testing.expectEqual(TestEnum.D, map.get("these").?);
std.testing.expectEqual(TestEnum.E, map.get("samelen").?);
fn testMap(comptime map: anytype) !void {
try std.testing.expectEqual(TestEnum.A, map.get("have").?);
try std.testing.expectEqual(TestEnum.B, map.get("nothing").?);
try std.testing.expect(null == map.get("missing"));
try std.testing.expectEqual(TestEnum.D, map.get("these").?);
try std.testing.expectEqual(TestEnum.E, map.get("samelen").?);
std.testing.expect(!map.has("missing"));
std.testing.expect(map.has("these"));
try std.testing.expect(!map.has("missing"));
try std.testing.expect(map.has("these"));
}
test "ComptimeStringMap void value type, slice of structs" {
@ -155,7 +155,7 @@ test "ComptimeStringMap void value type, slice of structs" {
};
const map = ComptimeStringMap(void, slice);
testSet(map);
try testSet(map);
}
test "ComptimeStringMap void value type, list literal of list literals" {
@ -167,16 +167,16 @@ test "ComptimeStringMap void value type, list literal of list literals" {
.{"samelen"},
});
testSet(map);
try testSet(map);
}
fn testSet(comptime map: anytype) void {
std.testing.expectEqual({}, map.get("have").?);
std.testing.expectEqual({}, map.get("nothing").?);
std.testing.expect(null == map.get("missing"));
std.testing.expectEqual({}, map.get("these").?);
std.testing.expectEqual({}, map.get("samelen").?);
fn testSet(comptime map: anytype) !void {
try std.testing.expectEqual({}, map.get("have").?);
try std.testing.expectEqual({}, map.get("nothing").?);
try std.testing.expect(null == map.get("missing"));
try std.testing.expectEqual({}, map.get("these").?);
try std.testing.expectEqual({}, map.get("samelen").?);
std.testing.expect(!map.has("missing"));
std.testing.expect(map.has("these"));
try std.testing.expect(!map.has("missing"));
try std.testing.expect(map.has("these"));
}

View File

@ -188,7 +188,7 @@ test "CSPRNG" {
const a = random.int(u64);
const b = random.int(u64);
const c = random.int(u64);
std.testing.expect(a ^ b ^ c != 0);
try std.testing.expect(a ^ b ^ c != 0);
}
test "issue #4532: no index out of bounds" {
@ -226,6 +226,6 @@ test "issue #4532: no index out of bounds" {
h.update(block[1..]);
h.final(&out2);
std.testing.expectEqual(out1, out2);
try std.testing.expectEqual(out1, out2);
}
}

View File

@ -120,13 +120,13 @@ test "curve25519" {
const p = try Curve25519.basePoint.clampedMul(s);
try p.rejectIdentity();
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E6F2A4D1C28EE5C7AD0329268255A468AD407D2672824C0C0EB30EA6EF450145");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E6F2A4D1C28EE5C7AD0329268255A468AD407D2672824C0C0EB30EA6EF450145");
const q = try p.clampedMul(s);
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "3614E119FFE55EC55B87D6B19971A9F4CBC78EFE80BEC55B96392BABCC712537");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "3614E119FFE55EC55B87D6B19971A9F4CBC78EFE80BEC55B96392BABCC712537");
try Curve25519.rejectNonCanonical(s);
s[31] |= 0x80;
std.testing.expectError(error.NonCanonical, Curve25519.rejectNonCanonical(s));
try std.testing.expectError(error.NonCanonical, Curve25519.rejectNonCanonical(s));
}
test "curve25519 small order check" {
@ -155,13 +155,13 @@ test "curve25519 small order check" {
},
};
for (small_order_ss) |small_order_s| {
std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(small_order_s).mul(s));
try std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(small_order_s).mul(s));
var extra = small_order_s;
extra[31] ^= 0x80;
std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(extra).mul(s));
try std.testing.expectError(error.WeakPublicKey, Curve25519.fromBytes(extra).mul(s));
var valid = small_order_s;
valid[31] = 0x40;
s[0] = 0;
std.testing.expectError(error.IdentityElement, Curve25519.fromBytes(valid).mul(s));
try std.testing.expectError(error.IdentityElement, Curve25519.fromBytes(valid).mul(s));
}
}

View File

@ -219,8 +219,8 @@ test "ed25519 key pair creation" {
_ = try fmt.hexToBytes(seed[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166");
const key_pair = try Ed25519.KeyPair.create(seed);
var buf: [256]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key)}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083");
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key)}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.secret_key)}), "8052030376D47112BE7F73ED7A019293DD12AD910B654455798B4667D73DE1662D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&key_pair.public_key)}), "2D6F7455D97B4A3A10D7293909D1A4F2058CB9A370E43FA8154BB280DB839083");
}
test "ed25519 signature" {
@ -230,9 +230,9 @@ test "ed25519 signature" {
const sig = try Ed25519.sign("test", key_pair, null);
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig)}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&sig)}), "10A442B4A80CC4225B154F43BEF28D2472CA80221951262EB8E0DF9091575E2687CC486E77263C3418C757522D54F84B0359236ABBBD4ACD20DC297FDCA66808");
try Ed25519.verify(sig, "test", key_pair.public_key);
std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verify(sig, "TEST", key_pair.public_key));
try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verify(sig, "TEST", key_pair.public_key));
}
test "ed25519 batch verification" {
@ -260,7 +260,7 @@ test "ed25519 batch verification" {
try Ed25519.verifyBatch(2, signature_batch);
signature_batch[1].sig = sig1;
std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(signature_batch.len, signature_batch));
try std.testing.expectError(error.SignatureVerificationFailed, Ed25519.verifyBatch(signature_batch.len, signature_batch));
}
}
@ -354,7 +354,7 @@ test "ed25519 test vectors" {
var sig: [64]u8 = undefined;
_ = try fmt.hexToBytes(&sig, entry.sig_hex);
if (entry.expected) |error_type| {
std.testing.expectError(error_type, Ed25519.verify(sig, &msg, public_key));
try std.testing.expectError(error_type, Ed25519.verify(sig, &msg, public_key));
} else {
try Ed25519.verify(sig, &msg, public_key);
}

View File

@ -491,7 +491,7 @@ test "edwards25519 packing/unpacking" {
var b = Edwards25519.basePoint;
const pk = try b.mul(s);
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&pk.toBytes())}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&pk.toBytes())}), "074BC7E0FCBD587FDBC0969444245FADC562809C8F6E97E949AF62484B5B81A6");
const small_order_ss: [7][32]u8 = .{
.{
@ -518,7 +518,7 @@ test "edwards25519 packing/unpacking" {
};
for (small_order_ss) |small_order_s| {
const small_p = try Edwards25519.fromBytes(small_order_s);
std.testing.expectError(error.WeakPublicKey, small_p.mul(s));
try std.testing.expectError(error.WeakPublicKey, small_p.mul(s));
}
}
@ -531,26 +531,26 @@ test "edwards25519 point addition/substraction" {
const q = try Edwards25519.basePoint.clampedMul(s2);
const r = p.add(q).add(q).sub(q).sub(q);
try r.rejectIdentity();
std.testing.expectError(error.IdentityElement, r.sub(p).rejectIdentity());
std.testing.expectError(error.IdentityElement, p.sub(p).rejectIdentity());
std.testing.expectError(error.IdentityElement, p.sub(q).add(q).sub(p).rejectIdentity());
try std.testing.expectError(error.IdentityElement, r.sub(p).rejectIdentity());
try std.testing.expectError(error.IdentityElement, p.sub(p).rejectIdentity());
try std.testing.expectError(error.IdentityElement, p.sub(q).add(q).sub(p).rejectIdentity());
}
test "edwards25519 uniform-to-point" {
var r = [32]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
var p = Edwards25519.fromUniform(r);
htest.assertEqual("0691eee3cf70a0056df6bfa03120635636581b5c4ea571dfc680f78c7e0b4137", p.toBytes()[0..]);
try htest.assertEqual("0691eee3cf70a0056df6bfa03120635636581b5c4ea571dfc680f78c7e0b4137", p.toBytes()[0..]);
r[31] = 0xff;
p = Edwards25519.fromUniform(r);
htest.assertEqual("f70718e68ef42d90ca1d936bb2d7e159be6c01d8095d39bd70487c82fe5c973a", p.toBytes()[0..]);
try htest.assertEqual("f70718e68ef42d90ca1d936bb2d7e159be6c01d8095d39bd70487c82fe5c973a", p.toBytes()[0..]);
}
// Test vectors from draft-irtf-cfrg-hash-to-curve-10
test "edwards25519 hash-to-curve operation" {
var p = Edwards25519.fromString(true, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_RO_", "abc");
htest.assertEqual("31558a26887f23fb8218f143e69d5f0af2e7831130bd5b432ef23883b895831a", p.toBytes()[0..]);
try htest.assertEqual("31558a26887f23fb8218f143e69d5f0af2e7831130bd5b432ef23883b895831a", p.toBytes()[0..]);
p = Edwards25519.fromString(false, "QUUX-V01-CS02-with-edwards25519_XMD:SHA-512_ELL2_NU_", "abc");
htest.assertEqual("42fa27c8f5a1ae0aa38bb59d5938e5145622ba5dedd11d11736fa2f9502d73e7", p.toBytes()[0..]);
try htest.assertEqual("42fa27c8f5a1ae0aa38bb59d5938e5145622ba5dedd11d11736fa2f9502d73e7", p.toBytes()[0..]);
}

View File

@ -175,21 +175,21 @@ pub const Ristretto255 = struct {
test "ristretto255" {
const p = Ristretto255.basePoint;
var buf: [256]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E2F2AE0A6ABC4E71A884A961C500515F58E30B6AA582DD8DB6A65945E08D2D76");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&p.toBytes())}), "E2F2AE0A6ABC4E71A884A961C500515F58E30B6AA582DD8DB6A65945E08D2D76");
var r: [Ristretto255.encoded_length]u8 = undefined;
_ = try fmt.hexToBytes(r[0..], "6a493210f7499cd17fecb510ae0cea23a110e8d5b901f8acadd3095c73a3b919");
var q = try Ristretto255.fromBytes(r);
q = q.dbl().add(p);
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "E882B131016B52C1D3337080187CF768423EFCCBB517BB495AB812C4160FF44E");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&q.toBytes())}), "E882B131016B52C1D3337080187CF768423EFCCBB517BB495AB812C4160FF44E");
const s = [_]u8{15} ++ [_]u8{0} ** 31;
const w = try p.mul(s);
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&w.toBytes())}), "E0C418F7C8D9C4CDD7395B93EA124F3AD99021BB681DFC3302A9D99A2E53E64E");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&w.toBytes())}), "E0C418F7C8D9C4CDD7395B93EA124F3AD99021BB681DFC3302A9D99A2E53E64E");
std.testing.expect(p.dbl().dbl().dbl().dbl().equivalent(w.add(p)));
try std.testing.expect(p.dbl().dbl().dbl().dbl().equivalent(w.add(p)));
const h = [_]u8{69} ** 32 ++ [_]u8{42} ** 32;
const ph = Ristretto255.fromUniform(h);
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&ph.toBytes())}), "DCCA54E037A4311EFBEEF413ACD21D35276518970B7A61DC88F8587B493D5E19");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&ph.toBytes())}), "DCCA54E037A4311EFBEEF413ACD21D35276518970B7A61DC88F8587B493D5E19");
}

View File

@ -773,15 +773,15 @@ test "scalar25519" {
var y = x.toBytes();
try rejectNonCanonical(y);
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&y)}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&y)}), "1E979B917937F3DE71D18077F961F6CEFF01030405060708010203040506070F");
const reduced = reduce(field_size);
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&reduced)}), "0000000000000000000000000000000000000000000000000000000000000000");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&reduced)}), "0000000000000000000000000000000000000000000000000000000000000000");
}
test "non-canonical scalar25519" {
const too_targe: [32]u8 = .{ 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 };
std.testing.expectError(error.NonCanonical, rejectNonCanonical(too_targe));
try std.testing.expectError(error.NonCanonical, rejectNonCanonical(too_targe));
}
test "mulAdd overflow check" {
@ -790,5 +790,5 @@ test "mulAdd overflow check" {
const c: [32]u8 = [_]u8{0xff} ** 32;
const x = mulAdd(a, b, c);
var buf: [128]u8 = undefined;
std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&x)}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903");
try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&x)}), "D14DF91389432C25AD60FF9791B9FD1D67BEF517D273ECCE3D9A307C1B419903");
}

View File

@ -92,7 +92,7 @@ test "x25519 public key calculation from secret key" {
_ = try fmt.hexToBytes(sk[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166");
_ = try fmt.hexToBytes(pk_expected[0..], "f1814f0e8ff1043d8a44d25babff3cedcae6c22c3edaa48f857ae70de2baae50");
const pk_calculated = try X25519.recoverPublicKey(sk);
std.testing.expectEqual(pk_calculated, pk_expected);
try std.testing.expectEqual(pk_calculated, pk_expected);
}
test "x25519 rfc7748 vector1" {
@ -102,7 +102,7 @@ test "x25519 rfc7748 vector1" {
const expected_output = [32]u8{ 0xc3, 0xda, 0x55, 0x37, 0x9d, 0xe9, 0xc6, 0x90, 0x8e, 0x94, 0xea, 0x4d, 0xf2, 0x8d, 0x08, 0x4f, 0x32, 0xec, 0xcf, 0x03, 0x49, 0x1c, 0x71, 0xf7, 0x54, 0xb4, 0x07, 0x55, 0x77, 0xa2, 0x85, 0x52 };
const output = try X25519.scalarmult(secret_key, public_key);
std.testing.expectEqual(output, expected_output);
try std.testing.expectEqual(output, expected_output);
}
test "x25519 rfc7748 vector2" {
@ -112,7 +112,7 @@ test "x25519 rfc7748 vector2" {
const expected_output = [32]u8{ 0x95, 0xcb, 0xde, 0x94, 0x76, 0xe8, 0x90, 0x7d, 0x7a, 0xad, 0xe4, 0x5c, 0xb4, 0xb8, 0x73, 0xf8, 0x8b, 0x59, 0x5a, 0x68, 0x79, 0x9f, 0xa1, 0x52, 0xe6, 0xf8, 0xf7, 0x64, 0x7a, 0xac, 0x79, 0x57 };
const output = try X25519.scalarmult(secret_key, public_key);
std.testing.expectEqual(output, expected_output);
try std.testing.expectEqual(output, expected_output);
}
test "x25519 rfc7748 one iteration" {
@ -129,7 +129,7 @@ test "x25519 rfc7748 one iteration" {
mem.copy(u8, k[0..], output[0..]);
}
std.testing.expectEqual(k, expected_output);
try std.testing.expectEqual(k, expected_output);
}
test "x25519 rfc7748 1,000 iterations" {
@ -151,7 +151,7 @@ test "x25519 rfc7748 1,000 iterations" {
mem.copy(u8, k[0..], output[0..]);
}
std.testing.expectEqual(k, expected_output);
try std.testing.expectEqual(k, expected_output);
}
test "x25519 rfc7748 1,000,000 iterations" {
@ -172,12 +172,12 @@ test "x25519 rfc7748 1,000,000 iterations" {
mem.copy(u8, k[0..], output[0..]);
}
std.testing.expectEqual(k[0..], expected_output);
try std.testing.expectEqual(k[0..], expected_output);
}
test "edwards25519 -> curve25519 map" {
const ed_kp = try crypto.sign.Ed25519.KeyPair.create([_]u8{0x42} ** 32);
const mont_kp = try X25519.KeyPair.fromEd25519(ed_kp);
htest.assertEqual("90e7595fc89e52fdfddce9c6a43d74dbf6047025ee0462d2d172e8b6a2841d6e", &mont_kp.secret_key);
htest.assertEqual("cc4f2cdb695dd766f34118eb67b98652fed1d8bc49c330b119bbfa8a64989378", &mont_kp.public_key);
try htest.assertEqual("90e7595fc89e52fdfddce9c6a43d74dbf6047025ee0462d2d172e8b6a2841d6e", &mont_kp.secret_key);
try htest.assertEqual("cc4f2cdb695dd766f34118eb67b98652fed1d8bc49c330b119bbfa8a64989378", &mont_kp.public_key);
}

View File

@ -352,16 +352,16 @@ test "Aegis128L test vector 1" {
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("79d94593d8c2119d7e8fd9b8fc77845c5c077a05b2528b6ac54b563aed8efe84", &c);
htest.assertEqual("cc6f3372f6aa1bb82388d695c3962d9a", &tag);
try htest.assertEqual("79d94593d8c2119d7e8fd9b8fc77845c5c077a05b2528b6ac54b563aed8efe84", &c);
try htest.assertEqual("cc6f3372f6aa1bb82388d695c3962d9a", &tag);
c[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
try testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
try testing.expectError(error.AuthenticationFailed, Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis128L test vector 2" {
@ -375,10 +375,10 @@ test "Aegis128L test vector 2" {
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("41de9000a7b5e40e2d68bb64d99ebb19", &c);
htest.assertEqual("f4d997cc9b94227ada4fe4165422b1c8", &tag);
try htest.assertEqual("41de9000a7b5e40e2d68bb64d99ebb19", &c);
try htest.assertEqual("f4d997cc9b94227ada4fe4165422b1c8", &tag);
}
test "Aegis128L test vector 3" {
@ -392,9 +392,9 @@ test "Aegis128L test vector 3" {
Aegis128L.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis128L.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("83cc600dc4e3e7e62d4055826174f149", &tag);
try htest.assertEqual("83cc600dc4e3e7e62d4055826174f149", &tag);
}
test "Aegis256 test vector 1" {
@ -408,16 +408,16 @@ test "Aegis256 test vector 1" {
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("f373079ed84b2709faee373584585d60accd191db310ef5d8b11833df9dec711", &c);
htest.assertEqual("8d86f91ee606e9ff26a01b64ccbdd91d", &tag);
try htest.assertEqual("f373079ed84b2709faee373584585d60accd191db310ef5d8b11833df9dec711", &c);
try htest.assertEqual("8d86f91ee606e9ff26a01b64ccbdd91d", &tag);
c[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
try testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
c[0] -%= 1;
tag[0] +%= 1;
testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
try testing.expectError(error.AuthenticationFailed, Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key));
}
test "Aegis256 test vector 2" {
@ -431,10 +431,10 @@ test "Aegis256 test vector 2" {
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("b98f03a947807713d75a4fff9fc277a6", &c);
htest.assertEqual("478f3b50dc478ef7d5cf2d0f7cc13180", &tag);
try htest.assertEqual("b98f03a947807713d75a4fff9fc277a6", &c);
try htest.assertEqual("478f3b50dc478ef7d5cf2d0f7cc13180", &tag);
}
test "Aegis256 test vector 3" {
@ -448,7 +448,7 @@ test "Aegis256 test vector 3" {
Aegis256.encrypt(&c, &tag, &m, &ad, nonce, key);
try Aegis256.decrypt(&m2, &c, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &m, &m2);
try testing.expectEqualSlices(u8, &m, &m2);
htest.assertEqual("f7a0878f68bd083e8065354071fc27c3", &tag);
try htest.assertEqual("f7a0878f68bd083e8065354071fc27c3", &tag);
}

View File

@ -48,7 +48,7 @@ test "ctr" {
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initEnc(key);
ctr(AesEncryptCtx(Aes128), ctx, out[0..], in[0..], iv, builtin.Endian.Big);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
test "encrypt" {
@ -61,7 +61,7 @@ test "encrypt" {
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initEnc(key);
ctx.encrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
@ -76,7 +76,7 @@ test "encrypt" {
var out: [exp_out.len]u8 = undefined;
var ctx = Aes256.initEnc(key);
ctx.encrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
@ -90,7 +90,7 @@ test "decrypt" {
var out: [exp_out.len]u8 = undefined;
var ctx = Aes128.initDec(key);
ctx.decrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
// Appendix C.3
@ -105,7 +105,7 @@ test "decrypt" {
var out: [exp_out.len]u8 = undefined;
var ctx = Aes256.initDec(key);
ctx.decrypt(out[0..], in[0..]);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
@ -123,11 +123,11 @@ test "expand 128-bit key" {
for (enc.key_schedule.round_keys) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_enc[i]);
testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
for (enc.key_schedule.round_keys) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_dec[i]);
testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
}
@ -145,10 +145,10 @@ test "expand 256-bit key" {
for (enc.key_schedule.round_keys) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_enc[i]);
testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
for (dec.key_schedule.round_keys) |round_key, i| {
_ = try std.fmt.hexToBytes(&exp, exp_dec[i]);
testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
try testing.expectEqualSlices(u8, &exp, &round_key.toBytes());
}
}

View File

@ -118,7 +118,7 @@ test "Aes256Gcm - Empty message and no associated data" {
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
htest.assertEqual("6b6ff610a16fa4cd59f1fb7903154e92", &tag);
try htest.assertEqual("6b6ff610a16fa4cd59f1fb7903154e92", &tag);
}
test "Aes256Gcm - Associated data only" {
@ -130,7 +130,7 @@ test "Aes256Gcm - Associated data only" {
var tag: [Aes256Gcm.tag_length]u8 = undefined;
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
htest.assertEqual("262ed164c2dfb26e080a9d108dd9dd4c", &tag);
try htest.assertEqual("262ed164c2dfb26e080a9d108dd9dd4c", &tag);
}
test "Aes256Gcm - Message only" {
@ -144,10 +144,10 @@ test "Aes256Gcm - Message only" {
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key);
testing.expectEqualSlices(u8, m[0..], m2[0..]);
try testing.expectEqualSlices(u8, m[0..], m2[0..]);
htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01d539472f7c", &c);
htest.assertEqual("07cd7fc9103e2f9e9bf2dfaa319caff4", &tag);
try htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01d539472f7c", &c);
try htest.assertEqual("07cd7fc9103e2f9e9bf2dfaa319caff4", &tag);
}
test "Aes256Gcm - Message and associated data" {
@ -161,8 +161,8 @@ test "Aes256Gcm - Message and associated data" {
Aes256Gcm.encrypt(&c, &tag, m, ad, nonce, key);
try Aes256Gcm.decrypt(&m2, &c, tag, ad, nonce, key);
testing.expectEqualSlices(u8, m[0..], m2[0..]);
try testing.expectEqualSlices(u8, m[0..], m2[0..]);
htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01", &c);
htest.assertEqual("64accec679d444e2373bd9f6796c0d2c", &tag);
try htest.assertEqual("5ca1642d90009fea33d01f78cf6eefaf01", &c);
try htest.assertEqual("64accec679d444e2373bd9f6796c0d2c", &tag);
}

View File

@ -281,13 +281,13 @@ test "bcrypt codec" {
Codec.encode(salt_str[0..], salt[0..]);
var salt2: [salt_length]u8 = undefined;
try Codec.decode(salt2[0..], salt_str[0..]);
testing.expectEqualSlices(u8, salt[0..], salt2[0..]);
try testing.expectEqualSlices(u8, salt[0..], salt2[0..]);
}
test "bcrypt" {
const s = try strHash("password", 5);
try strVerify(s, "password");
testing.expectError(error.PasswordVerificationFailed, strVerify(s, "invalid password"));
try testing.expectError(error.PasswordVerificationFailed, strVerify(s, "invalid password"));
const long_s = try strHash("password" ** 100, 5);
try strVerify(long_s, "password" ** 100);

View File

@ -194,16 +194,16 @@ pub fn Blake2s(comptime out_bits: usize) type {
test "blake2s160 single" {
const h1 = "354c9c33f735962418bdacb9479873429c34916f";
htest.assertEqualHash(Blake2s160, h1, "");
try htest.assertEqualHash(Blake2s160, h1, "");
const h2 = "5ae3b99be29b01834c3b508521ede60438f8de17";
htest.assertEqualHash(Blake2s160, h2, "abc");
try htest.assertEqualHash(Blake2s160, h2, "abc");
const h3 = "5a604fec9713c369e84b0ed68daed7d7504ef240";
htest.assertEqualHash(Blake2s160, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2s160, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "b60c4dc60e2681e58fbc24e77f07e02c69e72ed0";
htest.assertEqualHash(Blake2s160, h4, "a" ** 32 ++ "b" ** 32);
try htest.assertEqualHash(Blake2s160, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s160 streaming" {
@ -213,21 +213,21 @@ test "blake2s160 streaming" {
const h1 = "354c9c33f735962418bdacb9479873429c34916f";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "5ae3b99be29b01834c3b508521ede60438f8de17";
h = Blake2s160.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s160.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "b60c4dc60e2681e58fbc24e77f07e02c69e72ed0";
@ -235,12 +235,12 @@ test "blake2s160 streaming" {
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s160.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "4667fd60791a7fe41f939bca646b4529e296bd68";
@ -248,12 +248,12 @@ test "blake2s160 streaming" {
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2s160.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2s160" {
@ -265,28 +265,28 @@ test "comptime blake2s160" {
const h1 = "2c56ad9d0b2c8b474aafa93ab307db2f0940105f";
htest.assertEqualHash(Blake2s160, h1, block[0..]);
try htest.assertEqualHash(Blake2s160, h1, block[0..]);
var h = Blake2s160.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2s224 single" {
const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4";
htest.assertEqualHash(Blake2s224, h1, "");
try htest.assertEqualHash(Blake2s224, h1, "");
const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55";
htest.assertEqualHash(Blake2s224, h2, "abc");
try htest.assertEqualHash(Blake2s224, h2, "abc");
const h3 = "e4e5cb6c7cae41982b397bf7b7d2d9d1949823ae78435326e8db4912";
htest.assertEqualHash(Blake2s224, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2s224, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01";
htest.assertEqualHash(Blake2s224, h4, "a" ** 32 ++ "b" ** 32);
try htest.assertEqualHash(Blake2s224, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s224 streaming" {
@ -296,21 +296,21 @@ test "blake2s224 streaming" {
const h1 = "1fa1291e65248b37b3433475b2a0dd63d54a11ecc4e3e034e7bc1ef4";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "0b033fc226df7abde29f67a05d3dc62cf271ef3dfea4d387407fbd55";
h = Blake2s224.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "557381a78facd2b298640f4e32113e58967d61420af1aa939d0cfe01";
@ -318,12 +318,12 @@ test "blake2s224 streaming" {
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s224.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "a4d6a9d253441b80e5dfd60a04db169ffab77aec56a2855c402828c3";
@ -331,12 +331,12 @@ test "blake2s224 streaming" {
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2s224.init(.{ .context = [_]u8{0x69} ** 8, .salt = [_]u8{0x42} ** 8 });
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2s224" {
@ -347,28 +347,28 @@ test "comptime blake2s224" {
const h1 = "86b7611563293f8c73627df7a6d6ba25ca0548c2a6481f7d116ee576";
htest.assertEqualHash(Blake2s224, h1, block[0..]);
try htest.assertEqualHash(Blake2s224, h1, block[0..]);
var h = Blake2s224.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2s256 single" {
const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9";
htest.assertEqualHash(Blake2s256, h1, "");
try htest.assertEqualHash(Blake2s256, h1, "");
const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982";
htest.assertEqualHash(Blake2s256, h2, "abc");
try htest.assertEqualHash(Blake2s256, h2, "abc");
const h3 = "606beeec743ccbeff6cbcdf5d5302aa855c256c29b88c8ed331ea1a6bf3c8812";
htest.assertEqualHash(Blake2s256, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2s256, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977";
htest.assertEqualHash(Blake2s256, h4, "a" ** 32 ++ "b" ** 32);
try htest.assertEqualHash(Blake2s256, h4, "a" ** 32 ++ "b" ** 32);
}
test "blake2s256 streaming" {
@ -378,21 +378,21 @@ test "blake2s256 streaming" {
const h1 = "69217a3079908094e11121d042354a7c1f55b6482ca1a51e1b250dfd1ed0eef9";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "508c5e8c327c14e2e1a72ba34eeb452f37458b209ed63a294d999b4c86675982";
h = Blake2s256.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2s256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "8d8711dade07a6b92b9a3ea1f40bee9b2c53ff3edd2a273dec170b0163568977";
@ -400,12 +400,12 @@ test "blake2s256 streaming" {
h.update("a" ** 32);
h.update("b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2s256.init(.{});
h.update("a" ** 32 ++ "b" ** 32);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
}
test "blake2s256 keyed" {
@ -415,20 +415,20 @@ test "blake2s256 keyed" {
const key = "secret_key";
Blake2s256.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key });
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
var h = Blake2s256.init(.{ .key = key });
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
h = Blake2s256.init(.{ .key = key });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
test "comptime blake2s256" {
@ -439,13 +439,13 @@ test "comptime blake2s256" {
const h1 = "ae09db7cd54f42b490ef09b6bc541af688e4959bb8c53f359a6f56e38ab454a3";
htest.assertEqualHash(Blake2s256, h1, block[0..]);
try htest.assertEqualHash(Blake2s256, h1, block[0..]);
var h = Blake2s256.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
@ -617,16 +617,16 @@ pub fn Blake2b(comptime out_bits: usize) type {
test "blake2b160 single" {
const h1 = "3345524abf6bbe1809449224b5972c41790b6cf2";
htest.assertEqualHash(Blake2b160, h1, "");
try htest.assertEqualHash(Blake2b160, h1, "");
const h2 = "384264f676f39536840523f284921cdc68b6846b";
htest.assertEqualHash(Blake2b160, h2, "abc");
try htest.assertEqualHash(Blake2b160, h2, "abc");
const h3 = "3c523ed102ab45a37d54f5610d5a983162fde84f";
htest.assertEqualHash(Blake2b160, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2b160, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "43758f5de1740f651f1ae39de92260fe8bd5a11f";
htest.assertEqualHash(Blake2b160, h4, "a" ** 64 ++ "b" ** 64);
try htest.assertEqualHash(Blake2b160, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b160 streaming" {
@ -636,40 +636,40 @@ test "blake2b160 streaming" {
const h1 = "3345524abf6bbe1809449224b5972c41790b6cf2";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "384264f676f39536840523f284921cdc68b6846b";
h = Blake2b160.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b160.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "43758f5de1740f651f1ae39de92260fe8bd5a11f";
h = Blake2b160.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b160.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b160.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "72328f8a8200663752fc302d372b5dd9b49dd8dc";
@ -677,13 +677,13 @@ test "blake2b160 streaming" {
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2b160.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2b160" {
@ -694,28 +694,28 @@ test "comptime blake2b160" {
const h1 = "8d26f158f564e3293b42f5e3d34263cb173aa9c9";
htest.assertEqualHash(Blake2b160, h1, block[0..]);
try htest.assertEqualHash(Blake2b160, h1, block[0..]);
var h = Blake2b160.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2b384 single" {
const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100";
htest.assertEqualHash(Blake2b384, h1, "");
try htest.assertEqualHash(Blake2b384, h1, "");
const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4";
htest.assertEqualHash(Blake2b384, h2, "abc");
try htest.assertEqualHash(Blake2b384, h2, "abc");
const h3 = "b7c81b228b6bd912930e8f0b5387989691c1cee1e65aade4da3b86a3c9f678fc8018f6ed9e2906720c8d2a3aeda9c03d";
htest.assertEqualHash(Blake2b384, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2b384, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c";
htest.assertEqualHash(Blake2b384, h4, "a" ** 64 ++ "b" ** 64);
try htest.assertEqualHash(Blake2b384, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b384 streaming" {
@ -725,40 +725,40 @@ test "blake2b384 streaming" {
const h1 = "b32811423377f52d7862286ee1a72ee540524380fda1724a6f25d7978c6fd3244a6caf0498812673c5e05ef583825100";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "6f56a82c8e7ef526dfe182eb5212f7db9df1317e57815dbda46083fc30f54ee6c66ba83be64b302d7cba6ce15bb556f4";
h = Blake2b384.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "b7283f0172fecbbd7eca32ce10d8a6c06b453cb3cf675b33eb4246f0da2bb94a6c0bdd6eec0b5fd71ec4fd51be80bf4c";
h = Blake2b384.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b384.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b384.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
const h4 = "934c48fcb197031c71f583d92f98703510805e72142e0b46f5752d1e971bc86c355d556035613ff7a4154b4de09dac5c";
@ -766,13 +766,13 @@ test "blake2b384 streaming" {
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
h = Blake2b384.init(.{ .context = [_]u8{0x69} ** 16, .salt = [_]u8{0x42} ** 16 });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h4, out[0..]);
try htest.assertEqual(h4, out[0..]);
}
test "comptime blake2b384" {
@ -783,28 +783,28 @@ test "comptime blake2b384" {
const h1 = "e8aa1931ea0422e4446fecdd25c16cf35c240b10cb4659dd5c776eddcaa4d922397a589404b46eb2e53d78132d05fd7d";
htest.assertEqualHash(Blake2b384, h1, block[0..]);
try htest.assertEqualHash(Blake2b384, h1, block[0..]);
var h = Blake2b384.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}
test "blake2b512 single" {
const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce";
htest.assertEqualHash(Blake2b512, h1, "");
try htest.assertEqualHash(Blake2b512, h1, "");
const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
htest.assertEqualHash(Blake2b512, h2, "abc");
try htest.assertEqualHash(Blake2b512, h2, "abc");
const h3 = "a8add4bdddfd93e4877d2746e62817b116364a1fa7bc148d95090bc7333b3673f82401cf7aa2e4cb1ecd90296e3f14cb5413f8ed77be73045b13914cdcd6a918";
htest.assertEqualHash(Blake2b512, h3, "The quick brown fox jumps over the lazy dog");
try htest.assertEqualHash(Blake2b512, h3, "The quick brown fox jumps over the lazy dog");
const h4 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920";
htest.assertEqualHash(Blake2b512, h4, "a" ** 64 ++ "b" ** 64);
try htest.assertEqualHash(Blake2b512, h4, "a" ** 64 ++ "b" ** 64);
}
test "blake2b512 streaming" {
@ -814,34 +814,34 @@ test "blake2b512 streaming" {
const h1 = "786a02f742015903c6c6fd852552d272912f4740e15847618a86e217f71f5419d25e1031afee585313896444934eb04b903a685b1448b755d56f701afe9be2ce";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ba80a53f981c4d0d6a2797b69f12f6e94c212f14685ac4b74b12bb6fdbffa2d17d87c5392aab792dc252d5de4533cc9518d38aa8dbf1925ab92386edd4009923";
h = Blake2b512.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Blake2b512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
const h3 = "049980af04d6a2cf16b4b49793c3ed7e40732073788806f2c989ebe9547bda0541d63abe298ec8955d08af48ae731f2e8a0bd6d201655a5473b4aa79d211b920";
h = Blake2b512.init(.{});
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
h = Blake2b512.init(.{});
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h3, out[0..]);
try htest.assertEqual(h3, out[0..]);
}
test "blake2b512 keyed" {
@ -851,20 +851,20 @@ test "blake2b512 keyed" {
const key = "secret_key";
Blake2b512.hash("a" ** 64 ++ "b" ** 64, &out, .{ .key = key });
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
var h = Blake2b512.init(.{ .key = key });
h.update("a" ** 64 ++ "b" ** 64);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
h = Blake2b512.init(.{ .key = key });
h.update("a" ** 64);
h.update("b" ** 64);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
test "comptime blake2b512" {
@ -875,12 +875,12 @@ test "comptime blake2b512" {
const h1 = "865939e120e6805438478841afb739ae4250cf372653078a065cdcfffca4caf798e6d462b65d658fc165782640eded70963449ae1500fb0f24981d7727e22c41";
htest.assertEqualHash(Blake2b512, h1, block[0..]);
try htest.assertEqualHash(Blake2b512, h1, block[0..]);
var h = Blake2b512.init(.{});
h.update(&block);
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
}
}

View File

@ -641,7 +641,7 @@ const reference_test = ReferenceTest{
},
};
fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) void {
fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) !void {
// Save initial state
const initial_state = hasher.*;
@ -664,7 +664,7 @@ fn testBlake3(hasher: *Blake3, input_len: usize, expected_hex: [262]u8) void {
// Compare to expected value
var expected_bytes: [expected_hex.len / 2]u8 = undefined;
_ = fmt.hexToBytes(expected_bytes[0..], expected_hex[0..]) catch unreachable;
testing.expectEqual(actual_bytes, expected_bytes);
try testing.expectEqual(actual_bytes, expected_bytes);
// Restore initial state
hasher.* = initial_state;
@ -676,8 +676,8 @@ test "BLAKE3 reference test cases" {
var derive_key = &Blake3.initKdf(reference_test.context_string, .{});
for (reference_test.cases) |t| {
testBlake3(hash, t.input_len, t.hash.*);
testBlake3(keyed_hash, t.input_len, t.keyed_hash.*);
testBlake3(derive_key, t.input_len, t.derive_key.*);
try testBlake3(hash, t.input_len, t.hash.*);
try testBlake3(keyed_hash, t.input_len, t.keyed_hash.*);
try testBlake3(derive_key, t.input_len, t.derive_key.*);
}
}

View File

@ -604,9 +604,9 @@ test "chacha20 AEAD API" {
aead.encrypt(c[0..], tag[0..], m, ad, nonce, key);
try aead.decrypt(out[0..], c[0..], tag, ad[0..], nonce, key);
testing.expectEqualSlices(u8, out[0..], m);
try testing.expectEqualSlices(u8, out[0..], m);
c[0] += 1;
testing.expectError(error.AuthenticationFailed, aead.decrypt(out[0..], c[0..], tag, ad[0..], nonce, key));
try testing.expectError(error.AuthenticationFailed, aead.decrypt(out[0..], c[0..], tag, ad[0..], nonce, key));
}
}
@ -644,11 +644,11 @@ test "crypto.chacha20 test vector sunscreen" {
};
ChaCha20IETF.xor(result[0..], m[0..], 1, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
var m2: [114]u8 = undefined;
ChaCha20IETF.xor(m2[0..], result[0..], 1, key, nonce);
testing.expect(mem.order(u8, m, &m2) == .eq);
try testing.expect(mem.order(u8, m, &m2) == .eq);
}
// https://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-7
@ -683,7 +683,7 @@ test "crypto.chacha20 test vector 1" {
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 2" {
@ -717,7 +717,7 @@ test "crypto.chacha20 test vector 2" {
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 3" {
@ -751,7 +751,7 @@ test "crypto.chacha20 test vector 3" {
const nonce = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 1 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 4" {
@ -785,7 +785,7 @@ test "crypto.chacha20 test vector 4" {
const nonce = [_]u8{ 1, 0, 0, 0, 0, 0, 0, 0 };
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "crypto.chacha20 test vector 5" {
@ -857,7 +857,7 @@ test "crypto.chacha20 test vector 5" {
};
ChaCha20With64BitNonce.xor(result[0..], m[0..], 0, key, nonce);
testing.expectEqualSlices(u8, &expected_result, &result);
try testing.expectEqualSlices(u8, &expected_result, &result);
}
test "seal" {
@ -873,7 +873,7 @@ test "seal" {
var out: [exp_out.len]u8 = undefined;
ChaCha20Poly1305.encrypt(out[0..m.len], out[m.len..], m, ad, nonce, key);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
{
const m = [_]u8{
@ -906,7 +906,7 @@ test "seal" {
var out: [exp_out.len]u8 = undefined;
ChaCha20Poly1305.encrypt(out[0..m.len], out[m.len..], m[0..], ad[0..], nonce, key);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
}
@ -923,7 +923,7 @@ test "open" {
var out: [exp_out.len]u8 = undefined;
try ChaCha20Poly1305.decrypt(out[0..], c[0..exp_out.len], c[exp_out.len..].*, ad[0..], nonce, key);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
}
{
const c = [_]u8{
@ -956,21 +956,21 @@ test "open" {
var out: [exp_out.len]u8 = undefined;
try ChaCha20Poly1305.decrypt(out[0..], c[0..exp_out.len], c[exp_out.len..].*, ad[0..], nonce, key);
testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
try testing.expectEqualSlices(u8, exp_out[0..], out[0..]);
// corrupting the ciphertext, data, key, or nonce should cause a failure
var bad_c = c;
bad_c[0] ^= 1;
testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], bad_c[0..out.len], bad_c[out.len..].*, ad[0..], nonce, key));
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], bad_c[0..out.len], bad_c[out.len..].*, ad[0..], nonce, key));
var bad_ad = ad;
bad_ad[0] ^= 1;
testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, bad_ad[0..], nonce, key));
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, bad_ad[0..], nonce, key));
var bad_key = key;
bad_key[0] ^= 1;
testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], nonce, bad_key));
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], nonce, bad_key));
var bad_nonce = nonce;
bad_nonce[0] ^= 1;
testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], bad_nonce, key));
try testing.expectError(error.AuthenticationFailed, ChaCha20Poly1305.decrypt(out[0..], c[0..out.len], c[out.len..].*, ad[0..], bad_nonce, key));
}
}
@ -982,7 +982,7 @@ test "crypto.xchacha20" {
var c: [m.len]u8 = undefined;
XChaCha20IETF.xor(c[0..], m[0..], 0, key, nonce);
var buf: [2 * c.len]u8 = undefined;
testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE167C240D");
try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "E0A1BCF939654AFDBDC1746EC49832647C19D891F0D1A81FC0C1703B4514BDEA584B512F6908C2C5E9DD18D5CBC1805DE5803FE3B9CA5F193FB8359E91FAB0C3BB40309A292EB1CF49685C65C4A3ADF4F11DB0CD2B6B67FBC174BC2E860E8F769FD3565BBFAD1C845E05A0FED9BE167C240D");
}
{
const ad = "Additional data";
@ -991,9 +991,9 @@ test "crypto.xchacha20" {
var out: [m.len]u8 = undefined;
try XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key);
var buf: [2 * c.len]u8 = undefined;
testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234");
testing.expectEqualSlices(u8, out[0..], m);
try testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{s}", .{std.fmt.fmtSliceHexUpper(&c)}), "994D2DD32333F48E53650C02C7A2ABB8E018B0836D7175AEC779F52E961780768F815C58F1AA52D211498DB89B9216763F569C9433A6BBFCEFB4D4A49387A4C5207FBB3B5A92B5941294DF30588C6740D39DC16FA1F0E634F7246CF7CDCB978E44347D89381B7A74EB7084F754B90BDE9AAF5A94B8F2A85EFD0B50692AE2D425E234");
try testing.expectEqualSlices(u8, out[0..], m);
c[0] += 1;
testing.expectError(error.AuthenticationFailed, XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key));
try testing.expectError(error.AuthenticationFailed, XChaCha20Poly1305.decrypt(out[0..], c[0..m.len], c[m.len..].*, ad, nonce, key));
}
}

View File

@ -326,11 +326,11 @@ test "ghash" {
st.update(&m);
var out: [16]u8 = undefined;
st.final(&out);
htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
try htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
st = Ghash.init(&key);
st.update(m[0..100]);
st.update(m[100..]);
st.final(&out);
htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
try htest.assertEqual("889295fa746e8b174bf4ec80a65dea41", &out);
}

View File

@ -205,7 +205,7 @@ test "permute" {
while (i < 12) : (i += 1) {
mem.writeIntLittle(u32, expected_output[i * 4 ..][0..4], tv_output[i / 4][i % 4]);
}
testing.expectEqualSlices(u8, state.toSliceConst(), expected_output[0..]);
try testing.expectEqualSlices(u8, state.toSliceConst(), expected_output[0..]);
}
pub const Hash = struct {
@ -274,7 +274,7 @@ test "hash" {
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
htest.assertEqual("1C9A03DC6A5DDC5444CFC6F4B154CFF5CF081633B2CEA4D7D0AE7CCFED5AAA44", &md);
try htest.assertEqual("1C9A03DC6A5DDC5444CFC6F4B154CFF5CF081633B2CEA4D7D0AE7CCFED5AAA44", &md);
}
test "hash test vector 17" {
@ -282,7 +282,7 @@ test "hash test vector 17" {
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
htest.assertEqual("404C130AF1B9023A7908200919F690FFBB756D5176E056FFDE320016A37C7282", &md);
try htest.assertEqual("404C130AF1B9023A7908200919F690FFBB756D5176E056FFDE320016A37C7282", &md);
}
test "hash test vector 33" {
@ -290,7 +290,7 @@ test "hash test vector 33" {
_ = try std.fmt.hexToBytes(&msg, "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F");
var md: [32]u8 = undefined;
hash(&md, &msg, .{});
htest.assertEqual("A8F4FA28708BDA7EFB4C1914CA4AFA9E475B82D588D36504F87DBB0ED9AB3C4B", &md);
try htest.assertEqual("A8F4FA28708BDA7EFB4C1914CA4AFA9E475B82D588D36504F87DBB0ED9AB3C4B", &md);
}
pub const Aead = struct {
@ -447,12 +447,12 @@ test "cipher" {
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
htest.assertEqual("", &ct);
htest.assertEqual("14DA9BB7120BF58B985A8E00FDEBA15B", &tag);
try htest.assertEqual("", &ct);
try htest.assertEqual("14DA9BB7120BF58B985A8E00FDEBA15B", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &pt, &pt2);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (34) from NIST KAT submission.
const ad: [0]u8 = undefined;
@ -462,12 +462,12 @@ test "cipher" {
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
htest.assertEqual("7F", &ct);
htest.assertEqual("80492C317B1CD58A1EDC3A0D3E9876FC", &tag);
try htest.assertEqual("7F", &ct);
try htest.assertEqual("80492C317B1CD58A1EDC3A0D3E9876FC", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &pt, &pt2);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (106) from NIST KAT submission.
var ad: [12 / 2]u8 = undefined;
@ -478,12 +478,12 @@ test "cipher" {
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
htest.assertEqual("484D35", &ct);
htest.assertEqual("030BBEA23B61C00CED60A923BDCF9147", &tag);
try htest.assertEqual("484D35", &ct);
try htest.assertEqual("030BBEA23B61C00CED60A923BDCF9147", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &pt, &pt2);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (790) from NIST KAT submission.
var ad: [60 / 2]u8 = undefined;
@ -494,12 +494,12 @@ test "cipher" {
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
htest.assertEqual("6815B4A0ECDAD01596EAD87D9E690697475D234C6A13D1", &ct);
htest.assertEqual("DFE23F1642508290D68245279558B2FB", &tag);
try htest.assertEqual("6815B4A0ECDAD01596EAD87D9E690697475D234C6A13D1", &ct);
try htest.assertEqual("DFE23F1642508290D68245279558B2FB", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &pt, &pt2);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
{ // test vector (1057) from NIST KAT submission.
const ad: [0]u8 = undefined;
@ -509,11 +509,11 @@ test "cipher" {
var ct: [pt.len]u8 = undefined;
var tag: [16]u8 = undefined;
Aead.encrypt(&ct, &tag, &pt, &ad, nonce, key);
htest.assertEqual("7F8A2CF4F52AA4D6B2E74105C30A2777B9D0C8AEFDD555DE35861BD3011F652F", &ct);
htest.assertEqual("7256456FA935AC34BBF55AE135F33257", &tag);
try htest.assertEqual("7F8A2CF4F52AA4D6B2E74105C30A2777B9D0C8AEFDD555DE35861BD3011F652F", &ct);
try htest.assertEqual("7256456FA935AC34BBF55AE135F33257", &tag);
var pt2: [pt.len]u8 = undefined;
try Aead.decrypt(&pt2, &ct, tag, &ad, nonce, key);
testing.expectEqualSlices(u8, &pt, &pt2);
try testing.expectEqualSlices(u8, &pt, &pt2);
}
}

View File

@ -65,8 +65,8 @@ test "Hkdf" {
const context = [_]u8{ 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
const kdf = HkdfSha256;
const prk = kdf.extract(&salt, &ikm);
htest.assertEqual("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", &prk);
try htest.assertEqual("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5", &prk);
var out: [42]u8 = undefined;
kdf.expand(&out, &context, prk);
htest.assertEqual("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", &out);
try htest.assertEqual("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865", &out);
}

View File

@ -84,26 +84,26 @@ const htest = @import("test.zig");
test "hmac md5" {
var out: [HmacMd5.mac_length]u8 = undefined;
HmacMd5.create(out[0..], "", "");
htest.assertEqual("74e6f7298a9c2d168935f58c001bad88", out[0..]);
try htest.assertEqual("74e6f7298a9c2d168935f58c001bad88", out[0..]);
HmacMd5.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
htest.assertEqual("80070713463e7749b90c2dc24911e275", out[0..]);
try htest.assertEqual("80070713463e7749b90c2dc24911e275", out[0..]);
}
test "hmac sha1" {
var out: [HmacSha1.mac_length]u8 = undefined;
HmacSha1.create(out[0..], "", "");
htest.assertEqual("fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", out[0..]);
try htest.assertEqual("fbdb1d1b18aa6c08324b7d64b71fb76370690e1d", out[0..]);
HmacSha1.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
htest.assertEqual("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", out[0..]);
try htest.assertEqual("de7c9b85b8b78aa6bc8a7a36f70a90701c9db4d9", out[0..]);
}
test "hmac sha256" {
var out: [sha2.HmacSha256.mac_length]u8 = undefined;
sha2.HmacSha256.create(out[0..], "", "");
htest.assertEqual("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", out[0..]);
try htest.assertEqual("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad", out[0..]);
sha2.HmacSha256.create(out[0..], "The quick brown fox jumps over the lazy dog", "key");
htest.assertEqual("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", out[0..]);
try htest.assertEqual("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8", out[0..]);
}

View File

@ -240,8 +240,8 @@ test "ISAP" {
var msg = "test";
var c: [msg.len]u8 = undefined;
IsapA128A.encrypt(c[0..], &tag, msg[0..], ad, n, k);
testing.expect(mem.eql(u8, &[_]u8{ 0x8f, 0x68, 0x03, 0x8d }, c[0..]));
testing.expect(mem.eql(u8, &[_]u8{ 0x6c, 0x25, 0xe8, 0xe2, 0xe1, 0x1f, 0x38, 0xe9, 0x80, 0x75, 0xde, 0xd5, 0x2d, 0xb2, 0x31, 0x82 }, tag[0..]));
try testing.expect(mem.eql(u8, &[_]u8{ 0x8f, 0x68, 0x03, 0x8d }, c[0..]));
try testing.expect(mem.eql(u8, &[_]u8{ 0x6c, 0x25, 0xe8, 0xe2, 0xe1, 0x1f, 0x38, 0xe9, 0x80, 0x75, 0xde, 0xd5, 0x2d, 0xb2, 0x31, 0x82 }, tag[0..]));
try IsapA128A.decrypt(c[0..], c[0..], tag, ad, n, k);
testing.expect(mem.eql(u8, msg, c[0..]));
try testing.expect(mem.eql(u8, msg, c[0..]));
}

View File

@ -241,13 +241,13 @@ pub const Md5 = struct {
const htest = @import("test.zig");
test "md5 single" {
htest.assertEqualHash(Md5, "d41d8cd98f00b204e9800998ecf8427e", "");
htest.assertEqualHash(Md5, "0cc175b9c0f1b6a831c399e269772661", "a");
htest.assertEqualHash(Md5, "900150983cd24fb0d6963f7d28e17f72", "abc");
htest.assertEqualHash(Md5, "f96b697d7cb7938d525a2f31aaf161d0", "message digest");
htest.assertEqualHash(Md5, "c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz");
htest.assertEqualHash(Md5, "d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
htest.assertEqualHash(Md5, "57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890123456789012345678901234567890123456789012345678901234567890");
try htest.assertEqualHash(Md5, "d41d8cd98f00b204e9800998ecf8427e", "");
try htest.assertEqualHash(Md5, "0cc175b9c0f1b6a831c399e269772661", "a");
try htest.assertEqualHash(Md5, "900150983cd24fb0d6963f7d28e17f72", "abc");
try htest.assertEqualHash(Md5, "f96b697d7cb7938d525a2f31aaf161d0", "message digest");
try htest.assertEqualHash(Md5, "c3fcd3d76192e4007dfb496cca67e13b", "abcdefghijklmnopqrstuvwxyz");
try htest.assertEqualHash(Md5, "d174ab98d277d9f5a5611c2c9f419d9f", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
try htest.assertEqualHash(Md5, "57edf4a22be3c955ac49da2e2107b67a", "12345678901234567890123456789012345678901234567890123456789012345678901234567890");
}
test "md5 streaming" {
@ -255,12 +255,12 @@ test "md5 streaming" {
var out: [16]u8 = undefined;
h.final(out[0..]);
htest.assertEqual("d41d8cd98f00b204e9800998ecf8427e", out[0..]);
try htest.assertEqual("d41d8cd98f00b204e9800998ecf8427e", out[0..]);
h = Md5.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
try htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
h = Md5.init(.{});
h.update("a");
@ -268,7 +268,7 @@ test "md5 streaming" {
h.update("c");
h.final(out[0..]);
htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
try htest.assertEqual("900150983cd24fb0d6963f7d28e17f72", out[0..]);
}
test "md5 aligned final" {

View File

@ -168,7 +168,7 @@ test "RFC 6070 one iteration" {
const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 two iterations" {
@ -183,7 +183,7 @@ test "RFC 6070 two iterations" {
const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 4096 iterations" {
@ -198,7 +198,7 @@ test "RFC 6070 4096 iterations" {
const expected = "4b007901b765489abead49d926f721d065a429c1";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 16,777,216 iterations" {
@ -218,7 +218,7 @@ test "RFC 6070 16,777,216 iterations" {
const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 multi-block salt and password" {
@ -233,7 +233,7 @@ test "RFC 6070 multi-block salt and password" {
const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "RFC 6070 embedded NUL" {
@ -248,7 +248,7 @@ test "RFC 6070 embedded NUL" {
const expected = "56fa6aa75548099dcc37d7f03425e0c3";
htest.assertEqual(expected, dk[0..]);
try htest.assertEqual(expected, dk[0..]);
}
test "Very large dk_len" {

View File

@ -17,7 +17,7 @@ test "p256 ECDH key exchange" {
const dhB = try P256.basePoint.mul(dhb, .Little);
const shareda = try dhA.mul(dhb, .Little);
const sharedb = try dhB.mul(dha, .Little);
testing.expect(shareda.equivalent(sharedb));
try testing.expect(shareda.equivalent(sharedb));
}
test "p256 point from affine coordinates" {
@ -28,7 +28,7 @@ test "p256 point from affine coordinates" {
var ys: [32]u8 = undefined;
_ = try fmt.hexToBytes(&ys, yh);
var p = try P256.fromSerializedAffineCoordinates(xs, ys, .Big);
testing.expect(p.equivalent(P256.basePoint));
try testing.expect(p.equivalent(P256.basePoint));
}
test "p256 test vectors" {
@ -50,7 +50,7 @@ test "p256 test vectors" {
p = p.add(P256.basePoint);
var xs: [32]u8 = undefined;
_ = try fmt.hexToBytes(&xs, xh);
testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
}
}
@ -67,7 +67,7 @@ test "p256 test vectors - doubling" {
p = p.dbl();
var xs: [32]u8 = undefined;
_ = try fmt.hexToBytes(&xs, xh);
testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
try testing.expectEqualSlices(u8, &x.toBytes(.Big), &xs);
}
}
@ -75,29 +75,29 @@ test "p256 compressed sec1 encoding/decoding" {
const p = P256.random();
const s = p.toCompressedSec1();
const q = try P256.fromSec1(&s);
testing.expect(p.equivalent(q));
try testing.expect(p.equivalent(q));
}
test "p256 uncompressed sec1 encoding/decoding" {
const p = P256.random();
const s = p.toUncompressedSec1();
const q = try P256.fromSec1(&s);
testing.expect(p.equivalent(q));
try testing.expect(p.equivalent(q));
}
test "p256 public key is the neutral element" {
const n = P256.scalar.Scalar.zero.toBytes(.Little);
const p = P256.random();
testing.expectError(error.IdentityElement, p.mul(n, .Little));
try testing.expectError(error.IdentityElement, p.mul(n, .Little));
}
test "p256 public key is the neutral element (public verification)" {
const n = P256.scalar.Scalar.zero.toBytes(.Little);
const p = P256.random();
testing.expectError(error.IdentityElement, p.mulPublic(n, .Little));
try testing.expectError(error.IdentityElement, p.mulPublic(n, .Little));
}
test "p256 field element non-canonical encoding" {
const s = [_]u8{0xff} ** 32;
testing.expectError(error.NonCanonical, P256.Fe.fromBytes(s, .Little));
try testing.expectError(error.NonCanonical, P256.Fe.fromBytes(s, .Little));
}

View File

@ -216,5 +216,5 @@ test "poly1305 rfc7439 vector1" {
var mac: [16]u8 = undefined;
Poly1305.create(mac[0..], msg, key);
std.testing.expectEqualSlices(u8, expected_mac, &mac);
try std.testing.expectEqualSlices(u8, expected_mac, &mac);
}

View File

@ -561,11 +561,11 @@ test "(x)salsa20" {
var c: [msg.len]u8 = undefined;
Salsa20.xor(&c, msg[0..], 0, key, nonce);
htest.assertEqual("30ff9933aa6534ff5207142593cd1fca4b23bdd8", c[0..]);
try htest.assertEqual("30ff9933aa6534ff5207142593cd1fca4b23bdd8", c[0..]);
const extended_nonce = [_]u8{0x42} ** 24;
XSalsa20.xor(&c, msg[0..], 0, key, extended_nonce);
htest.assertEqual("b4ab7d82e750ec07644fa3281bce6cd91d4243f9", c[0..]);
try htest.assertEqual("b4ab7d82e750ec07644fa3281bce6cd91d4243f9", c[0..]);
}
test "xsalsa20poly1305" {
@ -628,5 +628,5 @@ test "secretbox twoblocks" {
const msg = [_]u8{'a'} ** 97;
var ciphertext: [msg.len + SecretBox.tag_length]u8 = undefined;
SecretBox.seal(&ciphertext, &msg, nonce, key);
htest.assertEqual("b05760e217288ba079caa2fd57fd3701784974ffcfda20fe523b89211ad8af065a6eb37cdb29d51aca5bd75dafdd21d18b044c54bb7c526cf576c94ee8900f911ceab0147e82b667a28c52d58ceb29554ff45471224d37b03256b01c119b89ff6d36855de8138d103386dbc9d971f52261", &ciphertext);
try htest.assertEqual("b05760e217288ba079caa2fd57fd3701784974ffcfda20fe523b89211ad8af065a6eb37cdb29d51aca5bd75dafdd21d18b044c54bb7c526cf576c94ee8900f911ceab0147e82b667a28c52d58ceb29554ff45471224d37b03256b01c119b89ff6d36855de8138d103386dbc9d971f52261", &ciphertext);
}

View File

@ -265,9 +265,9 @@ pub const Sha1 = struct {
const htest = @import("test.zig");
test "sha1 single" {
htest.assertEqualHash(Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709", "");
htest.assertEqualHash(Sha1, "a9993e364706816aba3e25717850c26c9cd0d89d", "abc");
htest.assertEqualHash(Sha1, "a49b2446a02c645bf419f995b67091253a04a259", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha1, "da39a3ee5e6b4b0d3255bfef95601890afd80709", "");
try htest.assertEqualHash(Sha1, "a9993e364706816aba3e25717850c26c9cd0d89d", "abc");
try htest.assertEqualHash(Sha1, "a49b2446a02c645bf419f995b67091253a04a259", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha1 streaming" {
@ -275,19 +275,19 @@ test "sha1 streaming" {
var out: [20]u8 = undefined;
h.final(&out);
htest.assertEqual("da39a3ee5e6b4b0d3255bfef95601890afd80709", out[0..]);
try htest.assertEqual("da39a3ee5e6b4b0d3255bfef95601890afd80709", out[0..]);
h = Sha1.init(.{});
h.update("abc");
h.final(&out);
htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
try htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
h = Sha1.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(&out);
htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
try htest.assertEqual("a9993e364706816aba3e25717850c26c9cd0d89d", out[0..]);
}
test "sha1 aligned final" {

View File

@ -285,9 +285,9 @@ fn Sha2x32(comptime params: Sha2Params32) type {
}
test "sha224 single" {
htest.assertEqualHash(Sha224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", "");
htest.assertEqualHash(Sha224, "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "abc");
htest.assertEqualHash(Sha224, "c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", "");
try htest.assertEqualHash(Sha224, "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "abc");
try htest.assertEqualHash(Sha224, "c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha224 streaming" {
@ -295,25 +295,25 @@ test "sha224 streaming" {
var out: [28]u8 = undefined;
h.final(out[0..]);
htest.assertEqual("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", out[0..]);
try htest.assertEqual("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", out[0..]);
h = Sha224.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
try htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
h = Sha224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
try htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]);
}
test "sha256 single" {
htest.assertEqualHash(Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "");
htest.assertEqualHash(Sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc");
htest.assertEqualHash(Sha256, "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", "");
try htest.assertEqualHash(Sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc");
try htest.assertEqualHash(Sha256, "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha256 streaming" {
@ -321,19 +321,19 @@ test "sha256 streaming" {
var out: [32]u8 = undefined;
h.final(out[0..]);
htest.assertEqual("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", out[0..]);
try htest.assertEqual("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", out[0..]);
h = Sha256.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
try htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
h = Sha256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
try htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]);
}
test "sha256 aligned final" {
@ -675,13 +675,13 @@ fn Sha2x64(comptime params: Sha2Params64) type {
test "sha384 single" {
const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b";
htest.assertEqualHash(Sha384, h1, "");
try htest.assertEqualHash(Sha384, h1, "");
const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7";
htest.assertEqualHash(Sha384, h2, "abc");
try htest.assertEqualHash(Sha384, h2, "abc");
const h3 = "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039";
htest.assertEqualHash(Sha384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha384 streaming" {
@ -690,32 +690,32 @@ test "sha384 streaming" {
const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7";
h = Sha384.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha512 single" {
const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
htest.assertEqualHash(Sha512, h1, "");
try htest.assertEqualHash(Sha512, h1, "");
const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
htest.assertEqualHash(Sha512, h2, "abc");
try htest.assertEqualHash(Sha512, h2, "abc");
const h3 = "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909";
htest.assertEqualHash(Sha512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha512 streaming" {
@ -724,21 +724,21 @@ test "sha512 streaming" {
const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
h = Sha512.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha512 aligned final" {

View File

@ -169,9 +169,9 @@ fn keccakF(comptime F: usize, d: *[F / 8]u8) void {
}
test "sha3-224 single" {
htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", "");
htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc");
htest.assertEqualHash(Sha3_224, "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", "");
try htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc");
try htest.assertEqualHash(Sha3_224, "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-224 streaming" {
@ -179,25 +179,25 @@ test "sha3-224 streaming" {
var out: [28]u8 = undefined;
h.final(out[0..]);
htest.assertEqual("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", out[0..]);
try htest.assertEqual("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", out[0..]);
h = Sha3_224.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
try htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
h = Sha3_224.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
try htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]);
}
test "sha3-256 single" {
htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", "");
htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc");
htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", "");
try htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc");
try htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-256 streaming" {
@ -205,19 +205,19 @@ test "sha3-256 streaming" {
var out: [32]u8 = undefined;
h.final(out[0..]);
htest.assertEqual("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", out[0..]);
try htest.assertEqual("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", out[0..]);
h = Sha3_256.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
try htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
h = Sha3_256.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
try htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]);
}
test "sha3-256 aligned final" {
@ -231,11 +231,11 @@ test "sha3-256 aligned final" {
test "sha3-384 single" {
const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004";
htest.assertEqualHash(Sha3_384, h1, "");
try htest.assertEqualHash(Sha3_384, h1, "");
const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25";
htest.assertEqualHash(Sha3_384, h2, "abc");
try htest.assertEqualHash(Sha3_384, h2, "abc");
const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7";
htest.assertEqualHash(Sha3_384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha3_384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-384 streaming" {
@ -244,29 +244,29 @@ test "sha3-384 streaming" {
const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25";
h = Sha3_384.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha3_384.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha3-512 single" {
const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26";
htest.assertEqualHash(Sha3_512, h1, "");
try htest.assertEqualHash(Sha3_512, h1, "");
const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
htest.assertEqualHash(Sha3_512, h2, "abc");
try htest.assertEqualHash(Sha3_512, h2, "abc");
const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185";
htest.assertEqualHash(Sha3_512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Sha3_512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "sha3-512 streaming" {
@ -275,20 +275,20 @@ test "sha3-512 streaming" {
const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26";
h.final(out[0..]);
htest.assertEqual(h1, out[0..]);
try htest.assertEqual(h1, out[0..]);
const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0";
h = Sha3_512.init(.{});
h.update("abc");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
h = Sha3_512.init(.{});
h.update("a");
h.update("b");
h.update("c");
h.final(out[0..]);
htest.assertEqual(h2, out[0..]);
try htest.assertEqual(h2, out[0..]);
}
test "sha3-512 aligned final" {
@ -301,13 +301,13 @@ test "sha3-512 aligned final" {
}
test "keccak-256 single" {
htest.assertEqualHash(Keccak_256, "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "");
htest.assertEqualHash(Keccak_256, "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45", "abc");
htest.assertEqualHash(Keccak_256, "f519747ed599024f3882238e5ab43960132572b7345fbeb9a90769dafd21ad67", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Keccak_256, "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", "");
try htest.assertEqualHash(Keccak_256, "4e03657aea45a94fc7d47ba826c8d667c0d1e6e33a64a036ec44f58fa12d6c45", "abc");
try htest.assertEqualHash(Keccak_256, "f519747ed599024f3882238e5ab43960132572b7345fbeb9a90769dafd21ad67", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}
test "keccak-512 single" {
htest.assertEqualHash(Keccak_512, "0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e", "");
htest.assertEqualHash(Keccak_512, "18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96", "abc");
htest.assertEqualHash(Keccak_512, "ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
try htest.assertEqualHash(Keccak_512, "0eab42de4c3ceb9235fc91acffe746b29c29a8c366b7c60e4e67c466f36a4304c00fa9caf9d87976ba469bcbe06713b435f091ef2769fb160cdab33d3670680e", "");
try htest.assertEqualHash(Keccak_512, "18587dc2ea106b9a1563e32b3312421ca164c7f1f07bc922a9c83d77cea3a1e5d0c69910739025372dc14ac9642629379540c17e2a65b19d77aa511a9d00bb96", "abc");
try htest.assertEqualHash(Keccak_512, "ac2fb35251825d3aa48468a9948c0a91b8256f6d97d8fa4160faff2dd9dfcc24f3f1db7a983dad13d53439ccac0b37e24037e7b95f80f59f37a2f683c4ba4682", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu");
}

View File

@ -319,7 +319,7 @@ test "siphash64-2-4 sanity" {
var out: [siphash.mac_length]u8 = undefined;
siphash.create(&out, buffer[0..i], test_key);
testing.expectEqual(out, vector);
try testing.expectEqual(out, vector);
}
}
@ -399,7 +399,7 @@ test "siphash128-2-4 sanity" {
var out: [siphash.mac_length]u8 = undefined;
siphash.create(&out, buffer[0..i], test_key[0..]);
testing.expectEqual(out, vector);
try testing.expectEqual(out, vector);
}
}
@ -423,6 +423,6 @@ test "iterative non-divisible update" {
}
const iterative_hash = siphash.finalInt();
std.testing.expectEqual(iterative_hash, non_iterative_hash);
try std.testing.expectEqual(iterative_hash, non_iterative_hash);
}
}

View File

@ -8,19 +8,19 @@ const testing = std.testing;
const fmt = std.fmt;
// Hash using the specified hasher `H` asserting `expected == H(input)`.
pub fn assertEqualHash(comptime Hasher: anytype, comptime expected_hex: *const [Hasher.digest_length * 2:0]u8, input: []const u8) void {
pub fn assertEqualHash(comptime Hasher: anytype, comptime expected_hex: *const [Hasher.digest_length * 2:0]u8, input: []const u8) !void {
var h: [Hasher.digest_length]u8 = undefined;
Hasher.hash(input, &h, .{});
assertEqual(expected_hex, &h);
try assertEqual(expected_hex, &h);
}
// Assert `expected` == hex(`input`) where `input` is a bytestring
pub fn assertEqual(comptime expected_hex: [:0]const u8, input: []const u8) void {
pub fn assertEqual(comptime expected_hex: [:0]const u8, input: []const u8) !void {
var expected_bytes: [expected_hex.len / 2]u8 = undefined;
for (expected_bytes) |*r, i| {
r.* = fmt.parseInt(u8, expected_hex[2 * i .. 2 * i + 2], 16) catch unreachable;
}
testing.expectEqualSlices(u8, &expected_bytes, input);
try testing.expectEqualSlices(u8, &expected_bytes, input);
}

View File

@ -92,9 +92,9 @@ test "crypto.utils.timingSafeEql" {
var b: [100]u8 = undefined;
std.crypto.random.bytes(a[0..]);
std.crypto.random.bytes(b[0..]);
testing.expect(!timingSafeEql([100]u8, a, b));
try testing.expect(!timingSafeEql([100]u8, a, b));
mem.copy(u8, a[0..], b[0..]);
testing.expect(timingSafeEql([100]u8, a, b));
try testing.expect(timingSafeEql([100]u8, a, b));
}
test "crypto.utils.timingSafeEql (vectors)" {
@ -104,22 +104,22 @@ test "crypto.utils.timingSafeEql (vectors)" {
std.crypto.random.bytes(b[0..]);
const v1: std.meta.Vector(100, u8) = a;
const v2: std.meta.Vector(100, u8) = b;
testing.expect(!timingSafeEql(std.meta.Vector(100, u8), v1, v2));
try testing.expect(!timingSafeEql(std.meta.Vector(100, u8), v1, v2));
const v3: std.meta.Vector(100, u8) = a;
testing.expect(timingSafeEql(std.meta.Vector(100, u8), v1, v3));
try testing.expect(timingSafeEql(std.meta.Vector(100, u8), v1, v3));
}
test "crypto.utils.timingSafeCompare" {
var a = [_]u8{10} ** 32;
var b = [_]u8{10} ** 32;
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .eq);
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .eq);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .eq);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .eq);
a[31] = 1;
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .lt);
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .lt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
a[0] = 20;
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .gt);
testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Big), .gt);
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .Little), .lt);
}
test "crypto.utils.secureZero" {
@ -129,5 +129,5 @@ test "crypto.utils.secureZero" {
mem.set(u8, a[0..], 0);
secureZero(u8, b[0..]);
testing.expectEqualSlices(u8, a[0..], b[0..]);
try testing.expectEqualSlices(u8, a[0..], b[0..]);
}

View File

@ -27,13 +27,13 @@ pub fn cmp(a: [*:0]const u8, b: [*:0]const u8) i8 {
}
test "cstr fns" {
comptime testCStrFnsImpl();
testCStrFnsImpl();
comptime try testCStrFnsImpl();
try testCStrFnsImpl();
}
fn testCStrFnsImpl() void {
testing.expect(cmp("aoeu", "aoez") == -1);
testing.expect(mem.len("123456789") == 9);
fn testCStrFnsImpl() !void {
try testing.expect(cmp("aoeu", "aoez") == -1);
try testing.expect(mem.len("123456789") == 9);
}
/// Returns a mutable, null-terminated slice with the same length as `slice`.
@ -48,8 +48,8 @@ pub fn addNullByte(allocator: *mem.Allocator, slice: []const u8) ![:0]u8 {
test "addNullByte" {
const slice = try addNullByte(std.testing.allocator, "hello"[0..4]);
defer std.testing.allocator.free(slice);
testing.expect(slice.len == 4);
testing.expect(slice[4] == 0);
try testing.expect(slice.len == 4);
try testing.expect(slice[4] == 0);
}
pub const NullTerminated2DArray = struct {

View File

@ -408,7 +408,7 @@ test "dynamic_library" {
};
const dynlib = DynLib.open(libname) catch |err| {
testing.expect(err == error.FileNotFound);
try testing.expect(err == error.FileNotFound);
return;
};
}

View File

@ -565,7 +565,7 @@ test "bswapAllFields" {
.ch_addralign = 0x12124242,
};
bswapAllFields(Elf32_Chdr, &s);
std.testing.expectEqual(Elf32_Chdr{
try std.testing.expectEqual(Elf32_Chdr{
.ch_type = 0x34123412,
.ch_size = 0x78567856,
.ch_addralign = 0x42421212,

View File

@ -119,10 +119,10 @@ test "std.enums.directEnumArray" {
.c = true,
});
testing.expectEqual([7]bool, @TypeOf(array));
testing.expectEqual(true, array[4]);
testing.expectEqual(false, array[6]);
testing.expectEqual(true, array[2]);
try testing.expectEqual([7]bool, @TypeOf(array));
try testing.expectEqual(true, array[4]);
try testing.expectEqual(false, array[6]);
try testing.expectEqual(true, array[2]);
}
/// Initializes an array of Data which can be indexed by
@ -160,10 +160,10 @@ test "std.enums.directEnumArrayDefault" {
.b = runtime_false,
});
testing.expectEqual([7]bool, @TypeOf(array));
testing.expectEqual(true, array[4]);
testing.expectEqual(false, array[6]);
testing.expectEqual(false, array[2]);
try testing.expectEqual([7]bool, @TypeOf(array));
try testing.expectEqual(true, array[4]);
try testing.expectEqual(false, array[6]);
try testing.expectEqual(false, array[2]);
}
/// Cast an enum literal, value, or string to the enum value of type E
@ -190,23 +190,23 @@ pub fn nameCast(comptime E: type, comptime value: anytype) E {
test "std.enums.nameCast" {
const A = enum(u1) { a = 0, b = 1 };
const B = enum(u1) { a = 1, b = 0 };
testing.expectEqual(A.a, nameCast(A, .a));
testing.expectEqual(A.a, nameCast(A, A.a));
testing.expectEqual(A.a, nameCast(A, B.a));
testing.expectEqual(A.a, nameCast(A, "a"));
testing.expectEqual(A.a, nameCast(A, @as(*const [1]u8, "a")));
testing.expectEqual(A.a, nameCast(A, @as([:0]const u8, "a")));
testing.expectEqual(A.a, nameCast(A, @as([]const u8, "a")));
try testing.expectEqual(A.a, nameCast(A, .a));
try testing.expectEqual(A.a, nameCast(A, A.a));
try testing.expectEqual(A.a, nameCast(A, B.a));
try testing.expectEqual(A.a, nameCast(A, "a"));
try testing.expectEqual(A.a, nameCast(A, @as(*const [1]u8, "a")));
try testing.expectEqual(A.a, nameCast(A, @as([:0]const u8, "a")));
try testing.expectEqual(A.a, nameCast(A, @as([]const u8, "a")));
testing.expectEqual(B.a, nameCast(B, .a));
testing.expectEqual(B.a, nameCast(B, A.a));
testing.expectEqual(B.a, nameCast(B, B.a));
testing.expectEqual(B.a, nameCast(B, "a"));
try testing.expectEqual(B.a, nameCast(B, .a));
try testing.expectEqual(B.a, nameCast(B, A.a));
try testing.expectEqual(B.a, nameCast(B, B.a));
try testing.expectEqual(B.a, nameCast(B, "a"));
testing.expectEqual(B.b, nameCast(B, .b));
testing.expectEqual(B.b, nameCast(B, A.b));
testing.expectEqual(B.b, nameCast(B, B.b));
testing.expectEqual(B.b, nameCast(B, "b"));
try testing.expectEqual(B.b, nameCast(B, .b));
try testing.expectEqual(B.b, nameCast(B, A.b));
try testing.expectEqual(B.b, nameCast(B, B.b));
try testing.expectEqual(B.b, nameCast(B, "b"));
}
/// A set of enum elements, backed by a bitfield. If the enum
@ -791,62 +791,62 @@ test "std.enums.EnumIndexer dense zeroed" {
const E = enum(u2) { b = 1, a = 0, c = 2 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
testing.expectEqual(E, Indexer.Key);
testing.expectEqual(@as(usize, 3), Indexer.count);
try testing.expectEqual(E, Indexer.Key);
try testing.expectEqual(@as(usize, 3), Indexer.count);
testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
testing.expectEqual(E.a, Indexer.keyForIndex(0));
testing.expectEqual(E.b, Indexer.keyForIndex(1));
testing.expectEqual(E.c, Indexer.keyForIndex(2));
try testing.expectEqual(E.a, Indexer.keyForIndex(0));
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}
test "std.enums.EnumIndexer dense positive" {
const E = enum(u4) { c = 6, a = 4, b = 5 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
testing.expectEqual(E, Indexer.Key);
testing.expectEqual(@as(usize, 3), Indexer.count);
try testing.expectEqual(E, Indexer.Key);
try testing.expectEqual(@as(usize, 3), Indexer.count);
testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
testing.expectEqual(E.a, Indexer.keyForIndex(0));
testing.expectEqual(E.b, Indexer.keyForIndex(1));
testing.expectEqual(E.c, Indexer.keyForIndex(2));
try testing.expectEqual(E.a, Indexer.keyForIndex(0));
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}
test "std.enums.EnumIndexer dense negative" {
const E = enum(i4) { a = -6, c = -4, b = -5 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
testing.expectEqual(E, Indexer.Key);
testing.expectEqual(@as(usize, 3), Indexer.count);
try testing.expectEqual(E, Indexer.Key);
try testing.expectEqual(@as(usize, 3), Indexer.count);
testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
testing.expectEqual(E.a, Indexer.keyForIndex(0));
testing.expectEqual(E.b, Indexer.keyForIndex(1));
testing.expectEqual(E.c, Indexer.keyForIndex(2));
try testing.expectEqual(E.a, Indexer.keyForIndex(0));
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}
test "std.enums.EnumIndexer sparse" {
const E = enum(i4) { a = -2, c = 6, b = 4 };
const Indexer = EnumIndexer(E);
ensureIndexer(Indexer);
testing.expectEqual(E, Indexer.Key);
testing.expectEqual(@as(usize, 3), Indexer.count);
try testing.expectEqual(E, Indexer.Key);
try testing.expectEqual(@as(usize, 3), Indexer.count);
testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
try testing.expectEqual(@as(usize, 0), Indexer.indexOf(.a));
try testing.expectEqual(@as(usize, 1), Indexer.indexOf(.b));
try testing.expectEqual(@as(usize, 2), Indexer.indexOf(.c));
testing.expectEqual(E.a, Indexer.keyForIndex(0));
testing.expectEqual(E.b, Indexer.keyForIndex(1));
testing.expectEqual(E.c, Indexer.keyForIndex(2));
try testing.expectEqual(E.a, Indexer.keyForIndex(0));
try testing.expectEqual(E.b, Indexer.keyForIndex(1));
try testing.expectEqual(E.c, Indexer.keyForIndex(2));
}

View File

@ -119,12 +119,12 @@ test "std.event.Batch" {
batch.add(&async sleepALittle(&count));
batch.add(&async increaseByTen(&count));
batch.wait();
testing.expect(count == 11);
try testing.expect(count == 11);
var another = Batch(anyerror!void, 2, .auto_async).init();
another.add(&async somethingElse());
another.add(&async doSomethingThatFails());
testing.expectError(error.ItBroke, another.wait());
try testing.expectError(error.ItBroke, another.wait());
}
fn sleepALittle(count: *usize) void {

View File

@ -310,25 +310,25 @@ test "std.event.Channel wraparound" {
// the buffer wraps around, make sure it doesn't crash.
var result: i32 = undefined;
channel.put(5);
testing.expectEqual(@as(i32, 5), channel.get());
try testing.expectEqual(@as(i32, 5), channel.get());
channel.put(6);
testing.expectEqual(@as(i32, 6), channel.get());
try testing.expectEqual(@as(i32, 6), channel.get());
channel.put(7);
testing.expectEqual(@as(i32, 7), channel.get());
try testing.expectEqual(@as(i32, 7), channel.get());
}
fn testChannelGetter(channel: *Channel(i32)) callconv(.Async) void {
const value1 = channel.get();
testing.expect(value1 == 1234);
try testing.expect(value1 == 1234);
const value2 = channel.get();
testing.expect(value2 == 4567);
try testing.expect(value2 == 4567);
const value3 = channel.getOrNull();
testing.expect(value3 == null);
try testing.expect(value3 == null);
var last_put = async testPut(channel, 4444);
const value4 = channel.getOrNull();
testing.expect(value4.? == 4444);
try testing.expect(value4.? == 4444);
await last_put;
}
fn testChannelPutter(channel: *Channel(i32)) callconv(.Async) void {

View File

@ -107,7 +107,7 @@ fn testFuture() void {
const result = (await a) + (await b);
testing.expect(result == 12);
try testing.expect(result == 12);
}
fn waitOnFuture(future: *Future(i32)) i32 {

View File

@ -140,14 +140,14 @@ fn testGroup(allocator: *Allocator) callconv(.Async) void {
var increase_by_ten_frame = async increaseByTen(&count);
group.add(&increase_by_ten_frame) catch @panic("memory");
group.wait();
testing.expect(count == 11);
try testing.expect(count == 11);
var another = Group(anyerror!void).init(allocator);
var something_else_frame = async somethingElse();
another.add(&something_else_frame) catch @panic("memory");
var something_that_fails_frame = async doSomethingThatFails();
another.add(&something_that_fails_frame) catch @panic("memory");
testing.expectError(error.ItBroke, another.wait());
try testing.expectError(error.ItBroke, another.wait());
}
fn sleepALittle(count: *usize) callconv(.Async) void {
std.time.sleep(1 * std.time.ns_per_ms);

View File

@ -136,7 +136,7 @@ test "std.event.Lock" {
testLock(&lock);
const expected_result = [1]i32{3 * @intCast(i32, shared_test_data.len)} ** shared_test_data.len;
testing.expectEqualSlices(i32, &expected_result, &shared_test_data);
try testing.expectEqualSlices(i32, &expected_result, &shared_test_data);
}
fn testLock(lock: *Lock) void {
var handle1 = async lockRunner(lock);

View File

@ -1655,7 +1655,7 @@ fn testEventLoop() i32 {
fn testEventLoop2(h: anyframe->i32, did_it: *bool) void {
const value = await h;
testing.expect(value == 1234);
try testing.expect(value == 1234);
did_it.* = true;
}
@ -1682,7 +1682,7 @@ test "std.event.Loop - runDetached" {
// with the previous runDetached.
loop.run();
testing.expect(testRunDetachedData == 1);
try testing.expect(testRunDetachedData == 1);
}
fn testRunDetached() void {
@ -1705,7 +1705,7 @@ test "std.event.Loop - sleep" {
for (frames) |*frame|
await frame;
testing.expect(sleep_count == frames.len);
try testing.expect(sleep_count == frames.len);
}
fn testSleep(wait_ns: u64, sleep_count: *usize) void {

View File

@ -228,7 +228,7 @@ test "std.event.RwLock" {
const handle = testLock(std.heap.page_allocator, &lock);
const expected_result = [1]i32{shared_it_count * @intCast(i32, shared_test_data.len)} ** shared_test_data.len;
testing.expectEqualSlices(i32, expected_result, shared_test_data);
try testing.expectEqualSlices(i32, expected_result, shared_test_data);
}
fn testLock(allocator: *Allocator, lock: *RwLock) callconv(.Async) void {
var read_nodes: [100]Loop.NextTickNode = undefined;
@ -290,7 +290,7 @@ fn readRunner(lock: *RwLock) callconv(.Async) void {
const handle = await lock_promise;
defer handle.release();
testing.expect(shared_test_index == 0);
testing.expect(shared_test_data[i] == @intCast(i32, shared_count));
try testing.expect(shared_test_index == 0);
try testing.expect(shared_test_data[i] == @intCast(i32, shared_count));
}
}

View File

@ -402,59 +402,59 @@ test "LinearFifo(u8, .Dynamic)" {
defer fifo.deinit();
try fifo.write("HELLO");
testing.expectEqual(@as(usize, 5), fifo.readableLength());
testing.expectEqualSlices(u8, "HELLO", fifo.readableSlice(0));
try testing.expectEqual(@as(usize, 5), fifo.readableLength());
try testing.expectEqualSlices(u8, "HELLO", fifo.readableSlice(0));
{
var i: usize = 0;
while (i < 5) : (i += 1) {
try fifo.write(&[_]u8{fifo.peekItem(i)});
}
testing.expectEqual(@as(usize, 10), fifo.readableLength());
testing.expectEqualSlices(u8, "HELLOHELLO", fifo.readableSlice(0));
try testing.expectEqual(@as(usize, 10), fifo.readableLength());
try testing.expectEqualSlices(u8, "HELLOHELLO", fifo.readableSlice(0));
}
{
testing.expectEqual(@as(u8, 'H'), fifo.readItem().?);
testing.expectEqual(@as(u8, 'E'), fifo.readItem().?);
testing.expectEqual(@as(u8, 'L'), fifo.readItem().?);
testing.expectEqual(@as(u8, 'L'), fifo.readItem().?);
testing.expectEqual(@as(u8, 'O'), fifo.readItem().?);
try testing.expectEqual(@as(u8, 'H'), fifo.readItem().?);
try testing.expectEqual(@as(u8, 'E'), fifo.readItem().?);
try testing.expectEqual(@as(u8, 'L'), fifo.readItem().?);
try testing.expectEqual(@as(u8, 'L'), fifo.readItem().?);
try testing.expectEqual(@as(u8, 'O'), fifo.readItem().?);
}
testing.expectEqual(@as(usize, 5), fifo.readableLength());
try testing.expectEqual(@as(usize, 5), fifo.readableLength());
{ // Writes that wrap around
testing.expectEqual(@as(usize, 11), fifo.writableLength());
testing.expectEqual(@as(usize, 6), fifo.writableSlice(0).len);
try testing.expectEqual(@as(usize, 11), fifo.writableLength());
try testing.expectEqual(@as(usize, 6), fifo.writableSlice(0).len);
fifo.writeAssumeCapacity("6<chars<11");
testing.expectEqualSlices(u8, "HELLO6<char", fifo.readableSlice(0));
testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(11));
testing.expectEqualSlices(u8, "11", fifo.readableSlice(13));
testing.expectEqualSlices(u8, "", fifo.readableSlice(15));
try testing.expectEqualSlices(u8, "HELLO6<char", fifo.readableSlice(0));
try testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(11));
try testing.expectEqualSlices(u8, "11", fifo.readableSlice(13));
try testing.expectEqualSlices(u8, "", fifo.readableSlice(15));
fifo.discard(11);
testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(0));
try testing.expectEqualSlices(u8, "s<11", fifo.readableSlice(0));
fifo.discard(4);
testing.expectEqual(@as(usize, 0), fifo.readableLength());
try testing.expectEqual(@as(usize, 0), fifo.readableLength());
}
{
const buf = try fifo.writableWithSize(12);
testing.expectEqual(@as(usize, 12), buf.len);
try testing.expectEqual(@as(usize, 12), buf.len);
var i: u8 = 0;
while (i < 10) : (i += 1) {
buf[i] = i + 'a';
}
fifo.update(10);
testing.expectEqualSlices(u8, "abcdefghij", fifo.readableSlice(0));
try testing.expectEqualSlices(u8, "abcdefghij", fifo.readableSlice(0));
}
{
try fifo.unget("prependedstring");
var result: [30]u8 = undefined;
testing.expectEqualSlices(u8, "prependedstringabcdefghij", result[0..fifo.read(&result)]);
try testing.expectEqualSlices(u8, "prependedstringabcdefghij", result[0..fifo.read(&result)]);
try fifo.unget("b");
try fifo.unget("a");
testing.expectEqualSlices(u8, "ab", result[0..fifo.read(&result)]);
try testing.expectEqualSlices(u8, "ab", result[0..fifo.read(&result)]);
}
fifo.shrink(0);
@ -462,17 +462,17 @@ test "LinearFifo(u8, .Dynamic)" {
{
try fifo.writer().print("{s}, {s}!", .{ "Hello", "World" });
var result: [30]u8 = undefined;
testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);
testing.expectEqual(@as(usize, 0), fifo.readableLength());
try testing.expectEqualSlices(u8, "Hello, World!", result[0..fifo.read(&result)]);
try testing.expectEqual(@as(usize, 0), fifo.readableLength());
}
{
try fifo.writer().writeAll("This is a test");
var result: [30]u8 = undefined;
testing.expectEqualSlices(u8, "This", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
testing.expectEqualSlices(u8, "is", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
testing.expectEqualSlices(u8, "a", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
testing.expectEqualSlices(u8, "test", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
try testing.expectEqualSlices(u8, "This", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
try testing.expectEqualSlices(u8, "is", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
try testing.expectEqualSlices(u8, "a", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
try testing.expectEqualSlices(u8, "test", (try fifo.reader().readUntilDelimiterOrEof(&result, ' ')).?);
}
{
@ -481,7 +481,7 @@ test "LinearFifo(u8, .Dynamic)" {
var out_buf: [50]u8 = undefined;
var out_fbs = std.io.fixedBufferStream(&out_buf);
try fifo.pump(in_fbs.reader(), out_fbs.writer());
testing.expectEqualSlices(u8, in_fbs.buffer, out_fbs.getWritten());
try testing.expectEqualSlices(u8, in_fbs.buffer, out_fbs.getWritten());
}
}
@ -498,28 +498,28 @@ test "LinearFifo" {
defer fifo.deinit();
try fifo.write(&[_]T{ 0, 1, 1, 0, 1 });
testing.expectEqual(@as(usize, 5), fifo.readableLength());
try testing.expectEqual(@as(usize, 5), fifo.readableLength());
{
testing.expectEqual(@as(T, 0), fifo.readItem().?);
testing.expectEqual(@as(T, 1), fifo.readItem().?);
testing.expectEqual(@as(T, 1), fifo.readItem().?);
testing.expectEqual(@as(T, 0), fifo.readItem().?);
testing.expectEqual(@as(T, 1), fifo.readItem().?);
testing.expectEqual(@as(usize, 0), fifo.readableLength());
try testing.expectEqual(@as(T, 0), fifo.readItem().?);
try testing.expectEqual(@as(T, 1), fifo.readItem().?);
try testing.expectEqual(@as(T, 1), fifo.readItem().?);
try testing.expectEqual(@as(T, 0), fifo.readItem().?);
try testing.expectEqual(@as(T, 1), fifo.readItem().?);
try testing.expectEqual(@as(usize, 0), fifo.readableLength());
}
{
try fifo.writeItem(1);
try fifo.writeItem(1);
try fifo.writeItem(1);
testing.expectEqual(@as(usize, 3), fifo.readableLength());
try testing.expectEqual(@as(usize, 3), fifo.readableLength());
}
{
var readBuf: [3]T = undefined;
const n = fifo.read(&readBuf);
testing.expectEqual(@as(usize, 3), n); // NOTE: It should be the number of items.
try testing.expectEqual(@as(usize, 3), n); // NOTE: It should be the number of items.
}
}
}

View File

@ -1422,7 +1422,7 @@ test "fmtDuration" {
.{ .s = "1y1m999ns", .d = 365 * std.time.ns_per_day + std.time.ns_per_min + 999 },
}) |tc| {
const slice = try bufPrint(&buf, "{}", .{fmtDuration(tc.d)});
std.testing.expectEqualStrings(tc.s, slice);
try std.testing.expectEqualStrings(tc.s, slice);
}
}
@ -1479,54 +1479,54 @@ pub fn parseInt(comptime T: type, buf: []const u8, radix: u8) ParseIntError!T {
}
test "parseInt" {
std.testing.expect((try parseInt(i32, "-10", 10)) == -10);
std.testing.expect((try parseInt(i32, "+10", 10)) == 10);
std.testing.expect((try parseInt(u32, "+10", 10)) == 10);
std.testing.expectError(error.Overflow, parseInt(u32, "-10", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, " 10", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "10 ", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "_10_", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10_", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x10_", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10", 10));
std.testing.expect((try parseInt(u8, "255", 10)) == 255);
std.testing.expectError(error.Overflow, parseInt(u8, "256", 10));
try std.testing.expect((try parseInt(i32, "-10", 10)) == -10);
try std.testing.expect((try parseInt(i32, "+10", 10)) == 10);
try std.testing.expect((try parseInt(u32, "+10", 10)) == 10);
try std.testing.expectError(error.Overflow, parseInt(u32, "-10", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, " 10", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "10 ", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "_10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x10_", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x_10", 10));
try std.testing.expect((try parseInt(u8, "255", 10)) == 255);
try std.testing.expectError(error.Overflow, parseInt(u8, "256", 10));
// +0 and -0 should work for unsigned
std.testing.expect((try parseInt(u8, "-0", 10)) == 0);
std.testing.expect((try parseInt(u8, "+0", 10)) == 0);
try std.testing.expect((try parseInt(u8, "-0", 10)) == 0);
try std.testing.expect((try parseInt(u8, "+0", 10)) == 0);
// ensure minInt is parsed correctly
std.testing.expect((try parseInt(i8, "-128", 10)) == math.minInt(i8));
std.testing.expect((try parseInt(i43, "-4398046511104", 10)) == math.minInt(i43));
try std.testing.expect((try parseInt(i8, "-128", 10)) == math.minInt(i8));
try std.testing.expect((try parseInt(i43, "-4398046511104", 10)) == math.minInt(i43));
// empty string or bare +- is invalid
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(i32, "", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "+", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(i32, "+", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "-", 10));
std.testing.expectError(error.InvalidCharacter, parseInt(i32, "-", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(i32, "", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "+", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(i32, "+", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "-", 10));
try std.testing.expectError(error.InvalidCharacter, parseInt(i32, "-", 10));
// autodectect the radix
std.testing.expect((try parseInt(i32, "111", 0)) == 111);
std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
std.testing.expect((try parseInt(i32, "+0b111", 0)) == 7);
std.testing.expect((try parseInt(i32, "+0b1_11", 0)) == 7);
std.testing.expect((try parseInt(i32, "+0o111", 0)) == 73);
std.testing.expect((try parseInt(i32, "+0o11_1", 0)) == 73);
std.testing.expect((try parseInt(i32, "+0x111", 0)) == 273);
std.testing.expect((try parseInt(i32, "-0b111", 0)) == -7);
std.testing.expect((try parseInt(i32, "-0b11_1", 0)) == -7);
std.testing.expect((try parseInt(i32, "-0o111", 0)) == -73);
std.testing.expect((try parseInt(i32, "-0x111", 0)) == -273);
std.testing.expect((try parseInt(i32, "-0x1_11", 0)) == -273);
try std.testing.expect((try parseInt(i32, "111", 0)) == 111);
try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
try std.testing.expect((try parseInt(i32, "1_1_1", 0)) == 111);
try std.testing.expect((try parseInt(i32, "+0b111", 0)) == 7);
try std.testing.expect((try parseInt(i32, "+0b1_11", 0)) == 7);
try std.testing.expect((try parseInt(i32, "+0o111", 0)) == 73);
try std.testing.expect((try parseInt(i32, "+0o11_1", 0)) == 73);
try std.testing.expect((try parseInt(i32, "+0x111", 0)) == 273);
try std.testing.expect((try parseInt(i32, "-0b111", 0)) == -7);
try std.testing.expect((try parseInt(i32, "-0b11_1", 0)) == -7);
try std.testing.expect((try parseInt(i32, "-0o111", 0)) == -73);
try std.testing.expect((try parseInt(i32, "-0x111", 0)) == -273);
try std.testing.expect((try parseInt(i32, "-0x1_11", 0)) == -273);
// bare binary/octal/decimal prefix is invalid
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0b", 0));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0o", 0));
std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x", 0));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0b", 0));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0o", 0));
try std.testing.expectError(error.InvalidCharacter, parseInt(u32, "0x", 0));
}
fn parseWithSign(
@ -1598,39 +1598,39 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, radix: u8) ParseIntError
}
test "parseUnsigned" {
std.testing.expect((try parseUnsigned(u16, "050124", 10)) == 50124);
std.testing.expect((try parseUnsigned(u16, "65535", 10)) == 65535);
std.testing.expect((try parseUnsigned(u16, "65_535", 10)) == 65535);
std.testing.expectError(error.Overflow, parseUnsigned(u16, "65536", 10));
try std.testing.expect((try parseUnsigned(u16, "050124", 10)) == 50124);
try std.testing.expect((try parseUnsigned(u16, "65535", 10)) == 65535);
try std.testing.expect((try parseUnsigned(u16, "65_535", 10)) == 65535);
try std.testing.expectError(error.Overflow, parseUnsigned(u16, "65536", 10));
std.testing.expect((try parseUnsigned(u64, "0ffffffffffffffff", 16)) == 0xffffffffffffffff);
std.testing.expect((try parseUnsigned(u64, "0f_fff_fff_fff_fff_fff", 16)) == 0xffffffffffffffff);
std.testing.expectError(error.Overflow, parseUnsigned(u64, "10000000000000000", 16));
try std.testing.expect((try parseUnsigned(u64, "0ffffffffffffffff", 16)) == 0xffffffffffffffff);
try std.testing.expect((try parseUnsigned(u64, "0f_fff_fff_fff_fff_fff", 16)) == 0xffffffffffffffff);
try std.testing.expectError(error.Overflow, parseUnsigned(u64, "10000000000000000", 16));
std.testing.expect((try parseUnsigned(u32, "DeadBeef", 16)) == 0xDEADBEEF);
try std.testing.expect((try parseUnsigned(u32, "DeadBeef", 16)) == 0xDEADBEEF);
std.testing.expect((try parseUnsigned(u7, "1", 10)) == 1);
std.testing.expect((try parseUnsigned(u7, "1000", 2)) == 8);
try std.testing.expect((try parseUnsigned(u7, "1", 10)) == 1);
try std.testing.expect((try parseUnsigned(u7, "1000", 2)) == 8);
std.testing.expectError(error.InvalidCharacter, parseUnsigned(u32, "f", 10));
std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "109", 8));
try std.testing.expectError(error.InvalidCharacter, parseUnsigned(u32, "f", 10));
try std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "109", 8));
std.testing.expect((try parseUnsigned(u32, "NUMBER", 36)) == 1442151747);
try std.testing.expect((try parseUnsigned(u32, "NUMBER", 36)) == 1442151747);
// these numbers should fit even though the radix itself doesn't fit in the destination type
std.testing.expect((try parseUnsigned(u1, "0", 10)) == 0);
std.testing.expect((try parseUnsigned(u1, "1", 10)) == 1);
std.testing.expectError(error.Overflow, parseUnsigned(u1, "2", 10));
std.testing.expect((try parseUnsigned(u1, "001", 16)) == 1);
std.testing.expect((try parseUnsigned(u2, "3", 16)) == 3);
std.testing.expectError(error.Overflow, parseUnsigned(u2, "4", 16));
try std.testing.expect((try parseUnsigned(u1, "0", 10)) == 0);
try std.testing.expect((try parseUnsigned(u1, "1", 10)) == 1);
try std.testing.expectError(error.Overflow, parseUnsigned(u1, "2", 10));
try std.testing.expect((try parseUnsigned(u1, "001", 16)) == 1);
try std.testing.expect((try parseUnsigned(u2, "3", 16)) == 3);
try std.testing.expectError(error.Overflow, parseUnsigned(u2, "4", 16));
// parseUnsigned does not expect a sign
std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "+0", 10));
std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "-0", 10));
try std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "+0", 10));
try std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "-0", 10));
// test empty string error
std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "", 10));
try std.testing.expectError(error.InvalidCharacter, parseUnsigned(u8, "", 10));
}
pub const parseFloat = @import("fmt/parse_float.zig").parseFloat;
@ -1709,21 +1709,21 @@ test "bufPrintInt" {
var buffer: [100]u8 = undefined;
const buf = buffer[0..];
std.testing.expectEqualSlices(u8, "-1", bufPrintIntToSlice(buf, @as(i1, -1), 10, false, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "-1", bufPrintIntToSlice(buf, @as(i1, -1), 10, false, FormatOptions{}));
std.testing.expectEqualSlices(u8, "-101111000110000101001110", bufPrintIntToSlice(buf, @as(i32, -12345678), 2, false, FormatOptions{}));
std.testing.expectEqualSlices(u8, "-12345678", bufPrintIntToSlice(buf, @as(i32, -12345678), 10, false, FormatOptions{}));
std.testing.expectEqualSlices(u8, "-bc614e", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, false, FormatOptions{}));
std.testing.expectEqualSlices(u8, "-BC614E", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, true, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "-101111000110000101001110", bufPrintIntToSlice(buf, @as(i32, -12345678), 2, false, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "-12345678", bufPrintIntToSlice(buf, @as(i32, -12345678), 10, false, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "-bc614e", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, false, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "-BC614E", bufPrintIntToSlice(buf, @as(i32, -12345678), 16, true, FormatOptions{}));
std.testing.expectEqualSlices(u8, "12345678", bufPrintIntToSlice(buf, @as(u32, 12345678), 10, true, FormatOptions{}));
try std.testing.expectEqualSlices(u8, "12345678", bufPrintIntToSlice(buf, @as(u32, 12345678), 10, true, FormatOptions{}));
std.testing.expectEqualSlices(u8, " 666", bufPrintIntToSlice(buf, @as(u32, 666), 10, false, FormatOptions{ .width = 6 }));
std.testing.expectEqualSlices(u8, " 1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 6 }));
std.testing.expectEqualSlices(u8, "1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 1 }));
try std.testing.expectEqualSlices(u8, " 666", bufPrintIntToSlice(buf, @as(u32, 666), 10, false, FormatOptions{ .width = 6 }));
try std.testing.expectEqualSlices(u8, " 1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 6 }));
try std.testing.expectEqualSlices(u8, "1234", bufPrintIntToSlice(buf, @as(u32, 0x1234), 16, false, FormatOptions{ .width = 1 }));
std.testing.expectEqualSlices(u8, "+42", bufPrintIntToSlice(buf, @as(i32, 42), 10, false, FormatOptions{ .width = 3 }));
std.testing.expectEqualSlices(u8, "-42", bufPrintIntToSlice(buf, @as(i32, -42), 10, false, FormatOptions{ .width = 3 }));
try std.testing.expectEqualSlices(u8, "+42", bufPrintIntToSlice(buf, @as(i32, 42), 10, false, FormatOptions{ .width = 3 }));
try std.testing.expectEqualSlices(u8, "-42", bufPrintIntToSlice(buf, @as(i32, -42), 10, false, FormatOptions{ .width = 3 }));
}
pub fn bufPrintIntToSlice(buf: []u8, value: anytype, base: u8, uppercase: bool, options: FormatOptions) []u8 {
@ -1741,8 +1741,8 @@ pub fn comptimePrint(comptime fmt: []const u8, args: anytype) *const [count(fmt,
test "comptimePrint" {
@setEvalBranchQuota(2000);
std.testing.expectEqual(*const [3:0]u8, @TypeOf(comptime comptimePrint("{}", .{100})));
std.testing.expectEqualSlices(u8, "100", comptime comptimePrint("{}", .{100}));
try std.testing.expectEqual(*const [3:0]u8, @TypeOf(comptime comptimePrint("{}", .{100})));
try std.testing.expectEqualSlices(u8, "100", comptime comptimePrint("{}", .{100}));
}
test "parse u64 digit too big" {
@ -1755,7 +1755,7 @@ test "parse u64 digit too big" {
test "parse unsigned comptime" {
comptime {
std.testing.expect((try parseUnsigned(usize, "2", 10)) == 2);
try std.testing.expect((try parseUnsigned(usize, "2", 10)) == 2);
}
}
@ -1852,15 +1852,15 @@ test "buffer" {
var buf1: [32]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf1);
try formatType(1234, "", FormatOptions{}, fbs.writer(), default_max_depth);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "1234"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "1234"));
fbs.reset();
try formatType('a', "c", FormatOptions{}, fbs.writer(), default_max_depth);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "a"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "a"));
fbs.reset();
try formatType(0b1100, "b", FormatOptions{}, fbs.writer(), default_max_depth);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "1100"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "1100"));
}
}
@ -2187,10 +2187,10 @@ test "union" {
var buf: [100]u8 = undefined;
const uu_result = try bufPrint(buf[0..], "{}", .{uu_inst});
std.testing.expect(mem.eql(u8, uu_result[0..3], "UU@"));
try std.testing.expect(mem.eql(u8, uu_result[0..3], "UU@"));
const eu_result = try bufPrint(buf[0..], "{}", .{eu_inst});
std.testing.expect(mem.eql(u8, uu_result[0..3], "EU@"));
try std.testing.expect(mem.eql(u8, uu_result[0..3], "EU@"));
}
test "enum" {
@ -2273,9 +2273,9 @@ test "hexToBytes" {
try expectFmt("90" ** 32, "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "90" ** 32))});
try expectFmt("ABCD", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "ABCD"))});
try expectFmt("", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, ""))});
std.testing.expectError(error.InvalidCharacter, hexToBytes(&buf, "012Z"));
std.testing.expectError(error.InvalidLength, hexToBytes(&buf, "AAA"));
std.testing.expectError(error.NoSpaceLeft, hexToBytes(buf[0..1], "ABAB"));
try std.testing.expectError(error.InvalidCharacter, hexToBytes(&buf, "012Z"));
try std.testing.expectError(error.InvalidLength, hexToBytes(&buf, "AAA"));
try std.testing.expectError(error.NoSpaceLeft, hexToBytes(buf[0..1], "ABAB"));
}
test "formatIntValue with comptime_int" {
@ -2284,7 +2284,7 @@ test "formatIntValue with comptime_int" {
var buf: [20]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try formatIntValue(value, "", FormatOptions{}, fbs.writer());
std.testing.expect(mem.eql(u8, fbs.getWritten(), "123456789123456789"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "123456789123456789"));
}
test "formatFloatValue with comptime_float" {
@ -2293,7 +2293,7 @@ test "formatFloatValue with comptime_float" {
var buf: [20]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try formatFloatValue(value, "", FormatOptions{}, fbs.writer());
std.testing.expect(mem.eql(u8, fbs.getWritten(), "1.0e+00"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "1.0e+00"));
try expectFmt("1.0e+00", "{}", .{value});
try expectFmt("1.0e+00", "{}", .{1.0});
@ -2349,19 +2349,19 @@ test "formatType max_depth" {
var buf: [1000]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buf);
try formatType(inst, "", FormatOptions{}, fbs.writer(), 0);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ ... }"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ ... }"));
fbs.reset();
try formatType(inst, "", FormatOptions{}, fbs.writer(), 1);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }"));
fbs.reset();
try formatType(inst, "", FormatOptions{}, fbs.writer(), 2);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }"));
fbs.reset();
try formatType(inst, "", FormatOptions{}, fbs.writer(), 3);
std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ .ptr = TU{ ... } } }, .e = E.Two, .vec = (10.200,2.220) }"));
try std.testing.expect(mem.eql(u8, fbs.getWritten(), "S{ .a = S{ .a = S{ .a = S{ ... }, .tu = TU{ ... }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ ... } }, .e = E.Two, .vec = (10.200,2.220) }, .tu = TU{ .ptr = TU{ .ptr = TU{ ... } } }, .e = E.Two, .vec = (10.200,2.220) }"));
}
test "positional" {

View File

@ -376,44 +376,44 @@ test "fmt.parseFloat" {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const Z = std.meta.Int(.unsigned, @typeInfo(T).Float.bits);
testing.expectError(error.InvalidCharacter, parseFloat(T, ""));
testing.expectError(error.InvalidCharacter, parseFloat(T, " 1"));
testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc"));
testing.expectError(error.InvalidCharacter, parseFloat(T, "+"));
testing.expectError(error.InvalidCharacter, parseFloat(T, "-"));
try testing.expectError(error.InvalidCharacter, parseFloat(T, ""));
try testing.expectError(error.InvalidCharacter, parseFloat(T, " 1"));
try testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc"));
try testing.expectError(error.InvalidCharacter, parseFloat(T, "+"));
try testing.expectError(error.InvalidCharacter, parseFloat(T, "-"));
expectEqual(try parseFloat(T, "0"), 0.0);
expectEqual(try parseFloat(T, "0"), 0.0);
expectEqual(try parseFloat(T, "+0"), 0.0);
expectEqual(try parseFloat(T, "-0"), 0.0);
try expectEqual(try parseFloat(T, "0"), 0.0);
try expectEqual(try parseFloat(T, "0"), 0.0);
try expectEqual(try parseFloat(T, "+0"), 0.0);
try expectEqual(try parseFloat(T, "-0"), 0.0);
expectEqual(try parseFloat(T, "0e0"), 0);
expectEqual(try parseFloat(T, "2e3"), 2000.0);
expectEqual(try parseFloat(T, "1e0"), 1.0);
expectEqual(try parseFloat(T, "-2e3"), -2000.0);
expectEqual(try parseFloat(T, "-1e0"), -1.0);
expectEqual(try parseFloat(T, "1.234e3"), 1234);
try expectEqual(try parseFloat(T, "0e0"), 0);
try expectEqual(try parseFloat(T, "2e3"), 2000.0);
try expectEqual(try parseFloat(T, "1e0"), 1.0);
try expectEqual(try parseFloat(T, "-2e3"), -2000.0);
try expectEqual(try parseFloat(T, "-1e0"), -1.0);
try expectEqual(try parseFloat(T, "1.234e3"), 1234);
expect(approxEqAbs(T, try parseFloat(T, "3.141"), 3.141, epsilon));
expect(approxEqAbs(T, try parseFloat(T, "-3.141"), -3.141, epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "3.141"), 3.141, epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "-3.141"), -3.141, epsilon));
expectEqual(try parseFloat(T, "1e-700"), 0);
expectEqual(try parseFloat(T, "1e+700"), std.math.inf(T));
try expectEqual(try parseFloat(T, "1e-700"), 0);
try expectEqual(try parseFloat(T, "1e+700"), std.math.inf(T));
expectEqual(@bitCast(Z, try parseFloat(T, "nAn")), @bitCast(Z, std.math.nan(T)));
expectEqual(try parseFloat(T, "inF"), std.math.inf(T));
expectEqual(try parseFloat(T, "-INF"), -std.math.inf(T));
try expectEqual(@bitCast(Z, try parseFloat(T, "nAn")), @bitCast(Z, std.math.nan(T)));
try expectEqual(try parseFloat(T, "inF"), std.math.inf(T));
try expectEqual(try parseFloat(T, "-INF"), -std.math.inf(T));
expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T));
try expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T));
if (T != f16) {
expect(approxEqAbs(T, try parseFloat(T, "1e-2"), 0.01, epsilon));
expect(approxEqAbs(T, try parseFloat(T, "1234e-2"), 12.34, epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "1e-2"), 0.01, epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "1234e-2"), 12.34, epsilon));
expect(approxEqAbs(T, try parseFloat(T, "123142.1"), 123142.1, epsilon));
expect(approxEqAbs(T, try parseFloat(T, "-123142.1124"), @as(T, -123142.1124), epsilon));
expect(approxEqAbs(T, try parseFloat(T, "0.7062146892655368"), @as(T, 0.7062146892655368), epsilon));
expect(approxEqAbs(T, try parseFloat(T, "2.71828182845904523536"), @as(T, 2.718281828459045), epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "123142.1"), 123142.1, epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "-123142.1124"), @as(T, -123142.1124), epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "0.7062146892655368"), @as(T, 0.7062146892655368), epsilon));
try expect(approxEqAbs(T, try parseFloat(T, "2.71828182845904523536"), @as(T, 2.718281828459045), epsilon));
}
}
}

View File

@ -247,17 +247,17 @@ pub fn parseHexFloat(comptime T: type, s: []const u8) !T {
}
test "special" {
testing.expect(math.isNan(try parseHexFloat(f32, "nAn")));
testing.expect(math.isPositiveInf(try parseHexFloat(f32, "iNf")));
testing.expect(math.isPositiveInf(try parseHexFloat(f32, "+Inf")));
testing.expect(math.isNegativeInf(try parseHexFloat(f32, "-iNf")));
try testing.expect(math.isNan(try parseHexFloat(f32, "nAn")));
try testing.expect(math.isPositiveInf(try parseHexFloat(f32, "iNf")));
try testing.expect(math.isPositiveInf(try parseHexFloat(f32, "+Inf")));
try testing.expect(math.isNegativeInf(try parseHexFloat(f32, "-iNf")));
}
test "zero" {
testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0"));
testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0"));
testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0p42"));
testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0.00000p42"));
testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0.00000p666"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0p42"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "-0x0.00000p42"));
try testing.expectEqual(@as(f32, 0.0), try parseHexFloat(f32, "0x0.00000p666"));
}
test "f16" {
@ -279,7 +279,7 @@ test "f16" {
};
for (cases) |case| {
testing.expectEqual(case.v, try parseHexFloat(f16, case.s));
try testing.expectEqual(case.v, try parseHexFloat(f16, case.s));
}
}
test "f32" {
@ -303,7 +303,7 @@ test "f32" {
};
for (cases) |case| {
testing.expectEqual(case.v, try parseHexFloat(f32, case.s));
try testing.expectEqual(case.v, try parseHexFloat(f32, case.s));
}
}
test "f64" {
@ -325,7 +325,7 @@ test "f64" {
};
for (cases) |case| {
testing.expectEqual(case.v, try parseHexFloat(f64, case.s));
try testing.expectEqual(case.v, try parseHexFloat(f64, case.s));
}
}
test "f128" {
@ -347,6 +347,6 @@ test "f128" {
};
for (cases) |case| {
testing.expectEqual(@bitCast(u128, case.v), @bitCast(u128, try parseHexFloat(f128, case.s)));
try testing.expectEqual(@bitCast(u128, case.v), @bitCast(u128, try parseHexFloat(f128, case.s)));
}
}

View File

@ -96,72 +96,72 @@ pub fn joinZ(allocator: *Allocator, paths: []const []const u8) ![:0]u8 {
return out[0 .. out.len - 1 :0];
}
fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) void {
fn testJoinMaybeZWindows(paths: []const []const u8, expected: []const u8, zero: bool) !void {
const windowsIsSep = struct {
fn isSep(byte: u8) bool {
return byte == '/' or byte == '\\';
}
}.isSep;
const actual = joinSepMaybeZ(testing.allocator, sep_windows, windowsIsSep, paths, zero) catch @panic("fail");
const actual = try joinSepMaybeZ(testing.allocator, sep_windows, windowsIsSep, paths, zero);
defer testing.allocator.free(actual);
testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
}
fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) void {
fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bool) !void {
const posixIsSep = struct {
fn isSep(byte: u8) bool {
return byte == '/';
}
}.isSep;
const actual = joinSepMaybeZ(testing.allocator, sep_posix, posixIsSep, paths, zero) catch @panic("fail");
const actual = try joinSepMaybeZ(testing.allocator, sep_posix, posixIsSep, paths, zero);
defer testing.allocator.free(actual);
testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
try testing.expectEqualSlices(u8, expected, if (zero) actual[0 .. actual.len - 1 :0] else actual);
}
test "join" {
{
const actual: []u8 = try join(testing.allocator, &[_][]const u8{});
defer testing.allocator.free(actual);
testing.expectEqualSlices(u8, "", actual);
try testing.expectEqualSlices(u8, "", actual);
}
{
const actual: [:0]u8 = try joinZ(testing.allocator, &[_][]const u8{});
defer testing.allocator.free(actual);
testing.expectEqualSlices(u8, "", actual);
try testing.expectEqualSlices(u8, "", actual);
}
for (&[_]bool{ false, true }) |zero| {
testJoinMaybeZWindows(&[_][]const u8{}, "", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "c" }, "c:\\a\\b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{}, "", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b", "c" }, "c:\\a\\b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\b\\", "c" }, "c:\\a\\b\\c", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b\\", "c" }, "c:\\a\\b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a\\", "b\\", "c" }, "c:\\a\\b\\c", zero);
testJoinMaybeZWindows(
try testJoinMaybeZWindows(
&[_][]const u8{ "c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std", "io.zig" },
"c:\\home\\andy\\dev\\zig\\build\\lib\\zig\\std\\io.zig",
zero,
);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero);
testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\", "a", "b/", "c" }, "c:\\a\\b/c", zero);
try testJoinMaybeZWindows(&[_][]const u8{ "c:\\a/", "b\\", "/c" }, "c:\\a/b\\c", zero);
testJoinMaybeZPosix(&[_][]const u8{}, "", zero);
testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero);
testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{}, "", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "/a/b", "c" }, "/a/b/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "/a/b/", "c" }, "/a/b/c", zero);
testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero);
testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "/", "a", "b/", "c" }, "/a/b/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "/a/", "b/", "c" }, "/a/b/c", zero);
testJoinMaybeZPosix(
try testJoinMaybeZPosix(
&[_][]const u8{ "/home/andy/dev/zig/build/lib/zig/std", "io.zig" },
"/home/andy/dev/zig/build/lib/zig/std/io.zig",
zero,
);
testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero);
testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "a", "/c" }, "a/c", zero);
try testJoinMaybeZPosix(&[_][]const u8{ "a/", "/c" }, "a/c", zero);
}
}
@ -235,42 +235,42 @@ pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool {
}
test "isAbsoluteWindows" {
testIsAbsoluteWindows("", false);
testIsAbsoluteWindows("/", true);
testIsAbsoluteWindows("//", true);
testIsAbsoluteWindows("//server", true);
testIsAbsoluteWindows("//server/file", true);
testIsAbsoluteWindows("\\\\server\\file", true);
testIsAbsoluteWindows("\\\\server", true);
testIsAbsoluteWindows("\\\\", true);
testIsAbsoluteWindows("c", false);
testIsAbsoluteWindows("c:", false);
testIsAbsoluteWindows("c:\\", true);
testIsAbsoluteWindows("c:/", true);
testIsAbsoluteWindows("c://", true);
testIsAbsoluteWindows("C:/Users/", true);
testIsAbsoluteWindows("C:\\Users\\", true);
testIsAbsoluteWindows("C:cwd/another", false);
testIsAbsoluteWindows("C:cwd\\another", false);
testIsAbsoluteWindows("directory/directory", false);
testIsAbsoluteWindows("directory\\directory", false);
testIsAbsoluteWindows("/usr/local", true);
try testIsAbsoluteWindows("", false);
try testIsAbsoluteWindows("/", true);
try testIsAbsoluteWindows("//", true);
try testIsAbsoluteWindows("//server", true);
try testIsAbsoluteWindows("//server/file", true);
try testIsAbsoluteWindows("\\\\server\\file", true);
try testIsAbsoluteWindows("\\\\server", true);
try testIsAbsoluteWindows("\\\\", true);
try testIsAbsoluteWindows("c", false);
try testIsAbsoluteWindows("c:", false);
try testIsAbsoluteWindows("c:\\", true);
try testIsAbsoluteWindows("c:/", true);
try testIsAbsoluteWindows("c://", true);
try testIsAbsoluteWindows("C:/Users/", true);
try testIsAbsoluteWindows("C:\\Users\\", true);
try testIsAbsoluteWindows("C:cwd/another", false);
try testIsAbsoluteWindows("C:cwd\\another", false);
try testIsAbsoluteWindows("directory/directory", false);
try testIsAbsoluteWindows("directory\\directory", false);
try testIsAbsoluteWindows("/usr/local", true);
}
test "isAbsolutePosix" {
testIsAbsolutePosix("", false);
testIsAbsolutePosix("/home/foo", true);
testIsAbsolutePosix("/home/foo/..", true);
testIsAbsolutePosix("bar/", false);
testIsAbsolutePosix("./baz", false);
try testIsAbsolutePosix("", false);
try testIsAbsolutePosix("/home/foo", true);
try testIsAbsolutePosix("/home/foo/..", true);
try testIsAbsolutePosix("bar/", false);
try testIsAbsolutePosix("./baz", false);
}
fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) void {
testing.expectEqual(expected_result, isAbsoluteWindows(path));
fn testIsAbsoluteWindows(path: []const u8, expected_result: bool) !void {
try testing.expectEqual(expected_result, isAbsoluteWindows(path));
}
fn testIsAbsolutePosix(path: []const u8, expected_result: bool) void {
testing.expectEqual(expected_result, isAbsolutePosix(path));
fn testIsAbsolutePosix(path: []const u8, expected_result: bool) !void {
try testing.expectEqual(expected_result, isAbsolutePosix(path));
}
pub const WindowsPath = struct {
@ -334,33 +334,33 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
test "windowsParsePath" {
{
const parsed = windowsParsePath("//a/b");
testing.expect(parsed.is_abs);
testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b"));
try testing.expect(parsed.is_abs);
try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
try testing.expect(mem.eql(u8, parsed.disk_designator, "//a/b"));
}
{
const parsed = windowsParsePath("\\\\a\\b");
testing.expect(parsed.is_abs);
testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b"));
try testing.expect(parsed.is_abs);
try testing.expect(parsed.kind == WindowsPath.Kind.NetworkShare);
try testing.expect(mem.eql(u8, parsed.disk_designator, "\\\\a\\b"));
}
{
const parsed = windowsParsePath("\\\\a\\");
testing.expect(!parsed.is_abs);
testing.expect(parsed.kind == WindowsPath.Kind.None);
testing.expect(mem.eql(u8, parsed.disk_designator, ""));
try testing.expect(!parsed.is_abs);
try testing.expect(parsed.kind == WindowsPath.Kind.None);
try testing.expect(mem.eql(u8, parsed.disk_designator, ""));
}
{
const parsed = windowsParsePath("/usr/local");
testing.expect(parsed.is_abs);
testing.expect(parsed.kind == WindowsPath.Kind.None);
testing.expect(mem.eql(u8, parsed.disk_designator, ""));
try testing.expect(parsed.is_abs);
try testing.expect(parsed.kind == WindowsPath.Kind.None);
try testing.expect(mem.eql(u8, parsed.disk_designator, ""));
}
{
const parsed = windowsParsePath("c:../");
testing.expect(!parsed.is_abs);
testing.expect(parsed.kind == WindowsPath.Kind.Drive);
testing.expect(mem.eql(u8, parsed.disk_designator, "c:"));
try testing.expect(!parsed.is_abs);
try testing.expect(parsed.kind == WindowsPath.Kind.Drive);
try testing.expect(mem.eql(u8, parsed.disk_designator, "c:"));
}
}
@ -772,13 +772,13 @@ test "resolvePosix" {
fn testResolveWindows(paths: []const []const u8, expected: []const u8) !void {
const actual = try resolveWindows(testing.allocator, paths);
defer testing.allocator.free(actual);
return testing.expect(mem.eql(u8, actual, expected));
try testing.expect(mem.eql(u8, actual, expected));
}
fn testResolvePosix(paths: []const []const u8, expected: []const u8) !void {
const actual = try resolvePosix(testing.allocator, paths);
defer testing.allocator.free(actual);
return testing.expect(mem.eql(u8, actual, expected));
try testing.expect(mem.eql(u8, actual, expected));
}
/// Strip the last component from a file path.
@ -856,68 +856,68 @@ pub fn dirnamePosix(path: []const u8) ?[]const u8 {
}
test "dirnamePosix" {
testDirnamePosix("/a/b/c", "/a/b");
testDirnamePosix("/a/b/c///", "/a/b");
testDirnamePosix("/a", "/");
testDirnamePosix("/", null);
testDirnamePosix("//", null);
testDirnamePosix("///", null);
testDirnamePosix("////", null);
testDirnamePosix("", null);
testDirnamePosix("a", null);
testDirnamePosix("a/", null);
testDirnamePosix("a//", null);
try testDirnamePosix("/a/b/c", "/a/b");
try testDirnamePosix("/a/b/c///", "/a/b");
try testDirnamePosix("/a", "/");
try testDirnamePosix("/", null);
try testDirnamePosix("//", null);
try testDirnamePosix("///", null);
try testDirnamePosix("////", null);
try testDirnamePosix("", null);
try testDirnamePosix("a", null);
try testDirnamePosix("a/", null);
try testDirnamePosix("a//", null);
}
test "dirnameWindows" {
testDirnameWindows("c:\\", null);
testDirnameWindows("c:\\foo", "c:\\");
testDirnameWindows("c:\\foo\\", "c:\\");
testDirnameWindows("c:\\foo\\bar", "c:\\foo");
testDirnameWindows("c:\\foo\\bar\\", "c:\\foo");
testDirnameWindows("c:\\foo\\bar\\baz", "c:\\foo\\bar");
testDirnameWindows("\\", null);
testDirnameWindows("\\foo", "\\");
testDirnameWindows("\\foo\\", "\\");
testDirnameWindows("\\foo\\bar", "\\foo");
testDirnameWindows("\\foo\\bar\\", "\\foo");
testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar");
testDirnameWindows("c:", null);
testDirnameWindows("c:foo", null);
testDirnameWindows("c:foo\\", null);
testDirnameWindows("c:foo\\bar", "c:foo");
testDirnameWindows("c:foo\\bar\\", "c:foo");
testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar");
testDirnameWindows("file:stream", null);
testDirnameWindows("dir\\file:stream", "dir");
testDirnameWindows("\\\\unc\\share", null);
testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\");
testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\");
testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo");
testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo");
testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar");
testDirnameWindows("/a/b/", "/a");
testDirnameWindows("/a/b", "/a");
testDirnameWindows("/a", "/");
testDirnameWindows("", null);
testDirnameWindows("/", null);
testDirnameWindows("////", null);
testDirnameWindows("foo", null);
try testDirnameWindows("c:\\", null);
try testDirnameWindows("c:\\foo", "c:\\");
try testDirnameWindows("c:\\foo\\", "c:\\");
try testDirnameWindows("c:\\foo\\bar", "c:\\foo");
try testDirnameWindows("c:\\foo\\bar\\", "c:\\foo");
try testDirnameWindows("c:\\foo\\bar\\baz", "c:\\foo\\bar");
try testDirnameWindows("\\", null);
try testDirnameWindows("\\foo", "\\");
try testDirnameWindows("\\foo\\", "\\");
try testDirnameWindows("\\foo\\bar", "\\foo");
try testDirnameWindows("\\foo\\bar\\", "\\foo");
try testDirnameWindows("\\foo\\bar\\baz", "\\foo\\bar");
try testDirnameWindows("c:", null);
try testDirnameWindows("c:foo", null);
try testDirnameWindows("c:foo\\", null);
try testDirnameWindows("c:foo\\bar", "c:foo");
try testDirnameWindows("c:foo\\bar\\", "c:foo");
try testDirnameWindows("c:foo\\bar\\baz", "c:foo\\bar");
try testDirnameWindows("file:stream", null);
try testDirnameWindows("dir\\file:stream", "dir");
try testDirnameWindows("\\\\unc\\share", null);
try testDirnameWindows("\\\\unc\\share\\foo", "\\\\unc\\share\\");
try testDirnameWindows("\\\\unc\\share\\foo\\", "\\\\unc\\share\\");
try testDirnameWindows("\\\\unc\\share\\foo\\bar", "\\\\unc\\share\\foo");
try testDirnameWindows("\\\\unc\\share\\foo\\bar\\", "\\\\unc\\share\\foo");
try testDirnameWindows("\\\\unc\\share\\foo\\bar\\baz", "\\\\unc\\share\\foo\\bar");
try testDirnameWindows("/a/b/", "/a");
try testDirnameWindows("/a/b", "/a");
try testDirnameWindows("/a", "/");
try testDirnameWindows("", null);
try testDirnameWindows("/", null);
try testDirnameWindows("////", null);
try testDirnameWindows("foo", null);
}
fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) void {
fn testDirnamePosix(input: []const u8, expected_output: ?[]const u8) !void {
if (dirnamePosix(input)) |output| {
testing.expect(mem.eql(u8, output, expected_output.?));
try testing.expect(mem.eql(u8, output, expected_output.?));
} else {
testing.expect(expected_output == null);
try testing.expect(expected_output == null);
}
}
fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) void {
fn testDirnameWindows(input: []const u8, expected_output: ?[]const u8) !void {
if (dirnameWindows(input)) |output| {
testing.expect(mem.eql(u8, output, expected_output.?));
try testing.expect(mem.eql(u8, output, expected_output.?));
} else {
testing.expect(expected_output == null);
try testing.expect(expected_output == null);
}
}
@ -983,54 +983,54 @@ pub fn basenameWindows(path: []const u8) []const u8 {
}
test "basename" {
testBasename("", "");
testBasename("/", "");
testBasename("/dir/basename.ext", "basename.ext");
testBasename("/basename.ext", "basename.ext");
testBasename("basename.ext", "basename.ext");
testBasename("basename.ext/", "basename.ext");
testBasename("basename.ext//", "basename.ext");
testBasename("/aaa/bbb", "bbb");
testBasename("/aaa/", "aaa");
testBasename("/aaa/b", "b");
testBasename("/a/b", "b");
testBasename("//a", "a");
try testBasename("", "");
try testBasename("/", "");
try testBasename("/dir/basename.ext", "basename.ext");
try testBasename("/basename.ext", "basename.ext");
try testBasename("basename.ext", "basename.ext");
try testBasename("basename.ext/", "basename.ext");
try testBasename("basename.ext//", "basename.ext");
try testBasename("/aaa/bbb", "bbb");
try testBasename("/aaa/", "aaa");
try testBasename("/aaa/b", "b");
try testBasename("/a/b", "b");
try testBasename("//a", "a");
testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext");
testBasenamePosix("\\basename.ext", "\\basename.ext");
testBasenamePosix("basename.ext", "basename.ext");
testBasenamePosix("basename.ext\\", "basename.ext\\");
testBasenamePosix("basename.ext\\\\", "basename.ext\\\\");
testBasenamePosix("foo", "foo");
try testBasenamePosix("\\dir\\basename.ext", "\\dir\\basename.ext");
try testBasenamePosix("\\basename.ext", "\\basename.ext");
try testBasenamePosix("basename.ext", "basename.ext");
try testBasenamePosix("basename.ext\\", "basename.ext\\");
try testBasenamePosix("basename.ext\\\\", "basename.ext\\\\");
try testBasenamePosix("foo", "foo");
testBasenameWindows("\\dir\\basename.ext", "basename.ext");
testBasenameWindows("\\basename.ext", "basename.ext");
testBasenameWindows("basename.ext", "basename.ext");
testBasenameWindows("basename.ext\\", "basename.ext");
testBasenameWindows("basename.ext\\\\", "basename.ext");
testBasenameWindows("foo", "foo");
testBasenameWindows("C:", "");
testBasenameWindows("C:.", ".");
testBasenameWindows("C:\\", "");
testBasenameWindows("C:\\dir\\base.ext", "base.ext");
testBasenameWindows("C:\\basename.ext", "basename.ext");
testBasenameWindows("C:basename.ext", "basename.ext");
testBasenameWindows("C:basename.ext\\", "basename.ext");
testBasenameWindows("C:basename.ext\\\\", "basename.ext");
testBasenameWindows("C:foo", "foo");
testBasenameWindows("file:stream", "file:stream");
try testBasenameWindows("\\dir\\basename.ext", "basename.ext");
try testBasenameWindows("\\basename.ext", "basename.ext");
try testBasenameWindows("basename.ext", "basename.ext");
try testBasenameWindows("basename.ext\\", "basename.ext");
try testBasenameWindows("basename.ext\\\\", "basename.ext");
try testBasenameWindows("foo", "foo");
try testBasenameWindows("C:", "");
try testBasenameWindows("C:.", ".");
try testBasenameWindows("C:\\", "");
try testBasenameWindows("C:\\dir\\base.ext", "base.ext");
try testBasenameWindows("C:\\basename.ext", "basename.ext");
try testBasenameWindows("C:basename.ext", "basename.ext");
try testBasenameWindows("C:basename.ext\\", "basename.ext");
try testBasenameWindows("C:basename.ext\\\\", "basename.ext");
try testBasenameWindows("C:foo", "foo");
try testBasenameWindows("file:stream", "file:stream");
}
fn testBasename(input: []const u8, expected_output: []const u8) void {
testing.expectEqualSlices(u8, expected_output, basename(input));
fn testBasename(input: []const u8, expected_output: []const u8) !void {
try testing.expectEqualSlices(u8, expected_output, basename(input));
}
fn testBasenamePosix(input: []const u8, expected_output: []const u8) void {
testing.expectEqualSlices(u8, expected_output, basenamePosix(input));
fn testBasenamePosix(input: []const u8, expected_output: []const u8) !void {
try testing.expectEqualSlices(u8, expected_output, basenamePosix(input));
}
fn testBasenameWindows(input: []const u8, expected_output: []const u8) void {
testing.expectEqualSlices(u8, expected_output, basenameWindows(input));
fn testBasenameWindows(input: []const u8, expected_output: []const u8) !void {
try testing.expectEqualSlices(u8, expected_output, basenameWindows(input));
}
/// Returns the relative path from `from` to `to`. If `from` and `to` each
@ -1212,13 +1212,13 @@ test "relative" {
fn testRelativePosix(from: []const u8, to: []const u8, expected_output: []const u8) !void {
const result = try relativePosix(testing.allocator, from, to);
defer testing.allocator.free(result);
testing.expectEqualSlices(u8, expected_output, result);
try testing.expectEqualSlices(u8, expected_output, result);
}
fn testRelativeWindows(from: []const u8, to: []const u8, expected_output: []const u8) !void {
const result = try relativeWindows(testing.allocator, from, to);
defer testing.allocator.free(result);
testing.expectEqualSlices(u8, expected_output, result);
try testing.expectEqualSlices(u8, expected_output, result);
}
/// Returns the extension of the file name (if any).
@ -1241,47 +1241,47 @@ pub fn extension(path: []const u8) []const u8 {
return filename[index..];
}
fn testExtension(path: []const u8, expected: []const u8) void {
std.testing.expectEqualStrings(expected, extension(path));
fn testExtension(path: []const u8, expected: []const u8) !void {
try std.testing.expectEqualStrings(expected, extension(path));
}
test "extension" {
testExtension("", "");
testExtension(".", "");
testExtension("a.", ".");
testExtension("abc.", ".");
testExtension(".a", "");
testExtension(".file", "");
testExtension(".gitignore", "");
testExtension("file.ext", ".ext");
testExtension("file.ext.", ".");
testExtension("very-long-file.bruh", ".bruh");
testExtension("a.b.c", ".c");
testExtension("a.b.c/", ".c");
try testExtension("", "");
try testExtension(".", "");
try testExtension("a.", ".");
try testExtension("abc.", ".");
try testExtension(".a", "");
try testExtension(".file", "");
try testExtension(".gitignore", "");
try testExtension("file.ext", ".ext");
try testExtension("file.ext.", ".");
try testExtension("very-long-file.bruh", ".bruh");
try testExtension("a.b.c", ".c");
try testExtension("a.b.c/", ".c");
testExtension("/", "");
testExtension("/.", "");
testExtension("/a.", ".");
testExtension("/abc.", ".");
testExtension("/.a", "");
testExtension("/.file", "");
testExtension("/.gitignore", "");
testExtension("/file.ext", ".ext");
testExtension("/file.ext.", ".");
testExtension("/very-long-file.bruh", ".bruh");
testExtension("/a.b.c", ".c");
testExtension("/a.b.c/", ".c");
try testExtension("/", "");
try testExtension("/.", "");
try testExtension("/a.", ".");
try testExtension("/abc.", ".");
try testExtension("/.a", "");
try testExtension("/.file", "");
try testExtension("/.gitignore", "");
try testExtension("/file.ext", ".ext");
try testExtension("/file.ext.", ".");
try testExtension("/very-long-file.bruh", ".bruh");
try testExtension("/a.b.c", ".c");
try testExtension("/a.b.c/", ".c");
testExtension("/foo/bar/bam/", "");
testExtension("/foo/bar/bam/.", "");
testExtension("/foo/bar/bam/a.", ".");
testExtension("/foo/bar/bam/abc.", ".");
testExtension("/foo/bar/bam/.a", "");
testExtension("/foo/bar/bam/.file", "");
testExtension("/foo/bar/bam/.gitignore", "");
testExtension("/foo/bar/bam/file.ext", ".ext");
testExtension("/foo/bar/bam/file.ext.", ".");
testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh");
testExtension("/foo/bar/bam/a.b.c", ".c");
testExtension("/foo/bar/bam/a.b.c/", ".c");
try testExtension("/foo/bar/bam/", "");
try testExtension("/foo/bar/bam/.", "");
try testExtension("/foo/bar/bam/a.", ".");
try testExtension("/foo/bar/bam/abc.", ".");
try testExtension("/foo/bar/bam/.a", "");
try testExtension("/foo/bar/bam/.file", "");
try testExtension("/foo/bar/bam/.gitignore", "");
try testExtension("/foo/bar/bam/file.ext", ".ext");
try testExtension("/foo/bar/bam/file.ext.", ".");
try testExtension("/foo/bar/bam/very-long-file.bruh", ".bruh");
try testExtension("/foo/bar/bam/a.b.c", ".c");
try testExtension("/foo/bar/bam/a.b.c/", ".c");
}

View File

@ -46,7 +46,7 @@ test "Dir.readLink" {
fn testReadLink(dir: Dir, target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
const given = try dir.readLink(symlink_path, buffer[0..]);
testing.expect(mem.eql(u8, target_path, given));
try testing.expect(mem.eql(u8, target_path, given));
}
test "accessAbsolute" {
@ -132,7 +132,7 @@ test "readLinkAbsolute" {
fn testReadLinkAbsolute(target_path: []const u8, symlink_path: []const u8) !void {
var buffer: [fs.MAX_PATH_BYTES]u8 = undefined;
const given = try fs.readLinkAbsolute(symlink_path, buffer[0..]);
testing.expect(mem.eql(u8, target_path, given));
try testing.expect(mem.eql(u8, target_path, given));
}
test "Dir.Iterator" {
@ -159,9 +159,9 @@ test "Dir.Iterator" {
try entries.append(Dir.Entry{ .name = name, .kind = entry.kind });
}
testing.expect(entries.items.len == 2); // note that the Iterator skips '.' and '..'
testing.expect(contains(&entries, Dir.Entry{ .name = "some_file", .kind = Dir.Entry.Kind.File }));
testing.expect(contains(&entries, Dir.Entry{ .name = "some_dir", .kind = Dir.Entry.Kind.Directory }));
try testing.expect(entries.items.len == 2); // note that the Iterator skips '.' and '..'
try testing.expect(contains(&entries, Dir.Entry{ .name = "some_file", .kind = Dir.Entry.Kind.File }));
try testing.expect(contains(&entries, Dir.Entry{ .name = "some_dir", .kind = Dir.Entry.Kind.Directory }));
}
fn entryEql(lhs: Dir.Entry, rhs: Dir.Entry) bool {
@ -203,7 +203,7 @@ test "Dir.realpath smoke test" {
const file_path = try tmp_dir.dir.realpath("test_file", buf1[0..]);
const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" });
testing.expect(mem.eql(u8, file_path, expected_path));
try testing.expect(mem.eql(u8, file_path, expected_path));
}
// Next, test alloc version
@ -211,7 +211,7 @@ test "Dir.realpath smoke test" {
const file_path = try tmp_dir.dir.realpathAlloc(&arena.allocator, "test_file");
const expected_path = try fs.path.join(&arena.allocator, &[_][]const u8{ base_path, "test_file" });
testing.expect(mem.eql(u8, file_path, expected_path));
try testing.expect(mem.eql(u8, file_path, expected_path));
}
}
@ -224,7 +224,7 @@ test "readAllAlloc" {
const buf1 = try file.readToEndAlloc(testing.allocator, 1024);
defer testing.allocator.free(buf1);
testing.expect(buf1.len == 0);
try testing.expect(buf1.len == 0);
const write_buf: []const u8 = "this is a test.\nthis is a test.\nthis is a test.\nthis is a test.\n";
try file.writeAll(write_buf);
@ -233,19 +233,19 @@ test "readAllAlloc" {
// max_bytes > file_size
const buf2 = try file.readToEndAlloc(testing.allocator, 1024);
defer testing.allocator.free(buf2);
testing.expectEqual(write_buf.len, buf2.len);
testing.expect(std.mem.eql(u8, write_buf, buf2));
try testing.expectEqual(write_buf.len, buf2.len);
try testing.expect(std.mem.eql(u8, write_buf, buf2));
try file.seekTo(0);
// max_bytes == file_size
const buf3 = try file.readToEndAlloc(testing.allocator, write_buf.len);
defer testing.allocator.free(buf3);
testing.expectEqual(write_buf.len, buf3.len);
testing.expect(std.mem.eql(u8, write_buf, buf3));
try testing.expectEqual(write_buf.len, buf3.len);
try testing.expect(std.mem.eql(u8, write_buf, buf3));
try file.seekTo(0);
// max_bytes < file_size
testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1));
try testing.expectError(error.FileTooBig, file.readToEndAlloc(testing.allocator, write_buf.len - 1));
}
test "directory operations on files" {
@ -257,22 +257,22 @@ test "directory operations on files" {
var file = try tmp_dir.dir.createFile(test_file_name, .{ .read = true });
file.close();
testing.expectError(error.PathAlreadyExists, tmp_dir.dir.makeDir(test_file_name));
testing.expectError(error.NotDir, tmp_dir.dir.openDir(test_file_name, .{}));
testing.expectError(error.NotDir, tmp_dir.dir.deleteDir(test_file_name));
try testing.expectError(error.PathAlreadyExists, tmp_dir.dir.makeDir(test_file_name));
try testing.expectError(error.NotDir, tmp_dir.dir.openDir(test_file_name, .{}));
try testing.expectError(error.NotDir, tmp_dir.dir.deleteDir(test_file_name));
if (builtin.os.tag != .wasi and builtin.os.tag != .freebsd and builtin.os.tag != .openbsd) {
const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_file_name);
defer testing.allocator.free(absolute_path);
testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(absolute_path));
testing.expectError(error.NotDir, fs.deleteDirAbsolute(absolute_path));
try testing.expectError(error.PathAlreadyExists, fs.makeDirAbsolute(absolute_path));
try testing.expectError(error.NotDir, fs.deleteDirAbsolute(absolute_path));
}
// ensure the file still exists and is a file as a sanity check
file = try tmp_dir.dir.openFile(test_file_name, .{});
const stat = try file.stat();
testing.expect(stat.kind == .File);
try testing.expect(stat.kind == .File);
file.close();
}
@ -287,23 +287,23 @@ test "file operations on directories" {
try tmp_dir.dir.makeDir(test_dir_name);
testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{}));
testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name));
try testing.expectError(error.IsDir, tmp_dir.dir.createFile(test_dir_name, .{}));
try testing.expectError(error.IsDir, tmp_dir.dir.deleteFile(test_dir_name));
// Currently, WASI will return error.Unexpected (via ENOTCAPABLE) when attempting fd_read on a directory handle.
// TODO: Re-enable on WASI once https://github.com/bytecodealliance/wasmtime/issues/1935 is resolved.
if (builtin.os.tag != .wasi) {
testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));
try testing.expectError(error.IsDir, tmp_dir.dir.readFileAlloc(testing.allocator, test_dir_name, std.math.maxInt(usize)));
}
// Note: The `.write = true` is necessary to ensure the error occurs on all platforms.
// TODO: Add a read-only test as well, see https://github.com/ziglang/zig/issues/5732
testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true }));
try testing.expectError(error.IsDir, tmp_dir.dir.openFile(test_dir_name, .{ .write = true }));
if (builtin.os.tag != .wasi and builtin.os.tag != .freebsd and builtin.os.tag != .openbsd) {
const absolute_path = try tmp_dir.dir.realpathAlloc(testing.allocator, test_dir_name);
defer testing.allocator.free(absolute_path);
testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{}));
testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path));
try testing.expectError(error.IsDir, fs.createFileAbsolute(absolute_path, .{}));
try testing.expectError(error.IsDir, fs.deleteFileAbsolute(absolute_path));
}
// ensure the directory still exists as a sanity check
@ -316,7 +316,7 @@ test "deleteDir" {
defer tmp_dir.cleanup();
// deleting a non-existent directory
testing.expectError(error.FileNotFound, tmp_dir.dir.deleteDir("test_dir"));
try testing.expectError(error.FileNotFound, tmp_dir.dir.deleteDir("test_dir"));
var dir = try tmp_dir.dir.makeOpenPath("test_dir", .{});
var file = try dir.createFile("test_file", .{});
@ -326,7 +326,7 @@ test "deleteDir" {
// deleting a non-empty directory
// TODO: Re-enable this check on Windows, see https://github.com/ziglang/zig/issues/5537
if (builtin.os.tag != .windows) {
testing.expectError(error.DirNotEmpty, tmp_dir.dir.deleteDir("test_dir"));
try testing.expectError(error.DirNotEmpty, tmp_dir.dir.deleteDir("test_dir"));
}
dir = try tmp_dir.dir.openDir("test_dir", .{});
@ -341,7 +341,7 @@ test "Dir.rename files" {
var tmp_dir = tmpDir(.{});
defer tmp_dir.cleanup();
testing.expectError(error.FileNotFound, tmp_dir.dir.rename("missing_file_name", "something_else"));
try testing.expectError(error.FileNotFound, tmp_dir.dir.rename("missing_file_name", "something_else"));
// Renaming files
const test_file_name = "test_file";
@ -351,7 +351,7 @@ test "Dir.rename files" {
try tmp_dir.dir.rename(test_file_name, renamed_test_file_name);
// Ensure the file was renamed
testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{}));
file = try tmp_dir.dir.openFile(renamed_test_file_name, .{});
file.close();
@ -363,7 +363,7 @@ test "Dir.rename files" {
existing_file.close();
try tmp_dir.dir.rename(renamed_test_file_name, "existing_file");
testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(renamed_test_file_name, .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(renamed_test_file_name, .{}));
file = try tmp_dir.dir.openFile("existing_file", .{});
file.close();
}
@ -380,7 +380,7 @@ test "Dir.rename directories" {
try tmp_dir.dir.rename("test_dir", "test_dir_renamed");
// Ensure the directory was renamed
testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir", .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir", .{}));
var dir = try tmp_dir.dir.openDir("test_dir_renamed", .{});
// Put a file in the directory
@ -391,7 +391,7 @@ test "Dir.rename directories" {
try tmp_dir.dir.rename("test_dir_renamed", "test_dir_renamed_again");
// Ensure the directory was renamed and the file still exists in it
testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir_renamed", .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir("test_dir_renamed", .{}));
dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{});
file = try dir.openFile("test_file", .{});
file.close();
@ -402,7 +402,7 @@ test "Dir.rename directories" {
file = try target_dir.createFile("filler", .{ .read = true });
file.close();
testing.expectError(error.PathAlreadyExists, tmp_dir.dir.rename("test_dir_renamed_again", "non_empty_target_dir"));
try testing.expectError(error.PathAlreadyExists, tmp_dir.dir.rename("test_dir_renamed_again", "non_empty_target_dir"));
// Ensure the directory was not renamed
dir = try tmp_dir.dir.openDir("test_dir_renamed_again", .{});
@ -421,8 +421,8 @@ test "Dir.rename file <-> dir" {
var file = try tmp_dir.dir.createFile("test_file", .{ .read = true });
file.close();
try tmp_dir.dir.makeDir("test_dir");
testing.expectError(error.IsDir, tmp_dir.dir.rename("test_file", "test_dir"));
testing.expectError(error.NotDir, tmp_dir.dir.rename("test_dir", "test_file"));
try testing.expectError(error.IsDir, tmp_dir.dir.rename("test_file", "test_dir"));
try testing.expectError(error.NotDir, tmp_dir.dir.rename("test_dir", "test_file"));
}
test "rename" {
@ -440,7 +440,7 @@ test "rename" {
try fs.rename(tmp_dir1.dir, test_file_name, tmp_dir2.dir, renamed_test_file_name);
// ensure the file was renamed
testing.expectError(error.FileNotFound, tmp_dir1.dir.openFile(test_file_name, .{}));
try testing.expectError(error.FileNotFound, tmp_dir1.dir.openFile(test_file_name, .{}));
file = try tmp_dir2.dir.openFile(renamed_test_file_name, .{});
file.close();
}
@ -461,7 +461,7 @@ test "renameAbsolute" {
break :blk try fs.realpathAlloc(&arena.allocator, relative_path);
};
testing.expectError(error.FileNotFound, fs.renameAbsolute(
try testing.expectError(error.FileNotFound, fs.renameAbsolute(
try fs.path.join(allocator, &[_][]const u8{ base_path, "missing_file_name" }),
try fs.path.join(allocator, &[_][]const u8{ base_path, "something_else" }),
));
@ -477,10 +477,10 @@ test "renameAbsolute" {
);
// ensure the file was renamed
testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openFile(test_file_name, .{}));
file = try tmp_dir.dir.openFile(renamed_test_file_name, .{});
const stat = try file.stat();
testing.expect(stat.kind == .File);
try testing.expect(stat.kind == .File);
file.close();
// Renaming directories
@ -493,7 +493,7 @@ test "renameAbsolute" {
);
// ensure the directory was renamed
testing.expectError(error.FileNotFound, tmp_dir.dir.openDir(test_dir_name, .{}));
try testing.expectError(error.FileNotFound, tmp_dir.dir.openDir(test_dir_name, .{}));
var dir = try tmp_dir.dir.openDir(renamed_test_dir_name, .{});
dir.close();
}
@ -516,7 +516,7 @@ test "makePath, put some files in it, deleteTree" {
if (tmp.dir.openDir("os_test_tmp", .{})) |dir| {
@panic("expected error");
} else |err| {
testing.expect(err == error.FileNotFound);
try testing.expect(err == error.FileNotFound);
}
}
@ -530,7 +530,7 @@ test "access file" {
if (tmp.dir.access("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", .{})) |ok| {
@panic("expected error");
} else |err| {
testing.expect(err == error.FileNotFound);
try testing.expect(err == error.FileNotFound);
}
try tmp.dir.writeFile("os_test_tmp" ++ fs.path.sep_str ++ "file.txt", "");
@ -600,7 +600,7 @@ test "sendfile" {
.header_count = 2,
});
const amt = try dest_file.preadAll(&written_buf, 0);
testing.expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n"));
try testing.expect(mem.eql(u8, written_buf[0..amt], "header1\nsecond header\nine1\nsecontrailer1\nsecond trailer\n"));
}
test "copyRangeAll" {
@ -626,7 +626,7 @@ test "copyRangeAll" {
_ = try src_file.copyRangeAll(0, dest_file, 0, data.len);
const amt = try dest_file.preadAll(&written_buf, 0);
testing.expect(mem.eql(u8, written_buf[0..amt], data));
try testing.expect(mem.eql(u8, written_buf[0..amt], data));
}
test "fs.copyFile" {
@ -655,7 +655,7 @@ fn expectFileContents(dir: Dir, file_path: []const u8, data: []const u8) !void {
const contents = try dir.readFileAlloc(testing.allocator, file_path, 1000);
defer testing.allocator.free(contents);
testing.expectEqualSlices(u8, data, contents);
try testing.expectEqualSlices(u8, data, contents);
}
test "AtomicFile" {
@ -676,7 +676,7 @@ test "AtomicFile" {
}
const content = try tmp.dir.readFileAlloc(testing.allocator, test_out_file, 9999);
defer testing.allocator.free(content);
testing.expect(mem.eql(u8, content, test_content));
try testing.expect(mem.eql(u8, content, test_content));
try tmp.dir.deleteFile(test_out_file);
}
@ -685,7 +685,7 @@ test "realpath" {
if (builtin.os.tag == .wasi) return error.SkipZigTest;
var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined;
testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf));
try testing.expectError(error.FileNotFound, fs.realpath("definitely_bogus_does_not_exist1234", &buf));
}
test "open file with exclusive nonblocking lock twice" {
@ -700,7 +700,7 @@ test "open file with exclusive nonblocking lock twice" {
defer file1.close();
const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
testing.expectError(error.WouldBlock, file2);
try testing.expectError(error.WouldBlock, file2);
}
test "open file with shared and exclusive nonblocking lock" {
@ -715,7 +715,7 @@ test "open file with shared and exclusive nonblocking lock" {
defer file1.close();
const file2 = tmp.dir.createFile(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
testing.expectError(error.WouldBlock, file2);
try testing.expectError(error.WouldBlock, file2);
}
test "open file with exclusive and shared nonblocking lock" {
@ -730,7 +730,7 @@ test "open file with exclusive and shared nonblocking lock" {
defer file1.close();
const file2 = tmp.dir.createFile(filename, .{ .lock = .Shared, .lock_nonblocking = true });
testing.expectError(error.WouldBlock, file2);
try testing.expectError(error.WouldBlock, file2);
}
test "open file with exclusive lock twice, make sure it waits" {
@ -790,7 +790,7 @@ test "open file with exclusive nonblocking lock twice (absolute paths)" {
const file2 = fs.createFileAbsolute(filename, .{ .lock = .Exclusive, .lock_nonblocking = true });
file1.close();
testing.expectError(error.WouldBlock, file2);
try testing.expectError(error.WouldBlock, file2);
try fs.deleteFileAbsolute(filename);
}
@ -830,6 +830,6 @@ test "walker" {
try fs.path.join(allocator, &[_][]const u8{ expected_dir_name, name });
var entry = (try walker.next()).?;
testing.expectEqualStrings(expected_dir_name, try fs.path.relative(allocator, tmp_path, entry.path));
try testing.expectEqualStrings(expected_dir_name, try fs.path.relative(allocator, tmp_path, entry.path));
}
}

View File

@ -174,8 +174,8 @@ test "extracting WASI preopens" {
try preopens.populate();
std.testing.expectEqual(@as(usize, 1), preopens.asSlice().len);
try std.testing.expectEqual(@as(usize, 1), preopens.asSlice().len);
const preopen = preopens.find(PreopenType{ .Dir = "." }) orelse unreachable;
std.testing.expect(preopen.@"type".eql(PreopenType{ .Dir = "." }));
std.testing.expectEqual(@as(usize, 3), preopen.fd);
try std.testing.expect(preopen.@"type".eql(PreopenType{ .Dir = "." }));
try std.testing.expectEqual(@as(usize, 3), preopen.fd);
}

View File

@ -662,13 +662,13 @@ fn testWriteWatchWriteDelete(allocator: *Allocator) !void {
const read_contents = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024);
defer allocator.free(read_contents);
testing.expectEqualSlices(u8, contents, read_contents);
try testing.expectEqualSlices(u8, contents, read_contents);
// now watch the file
var watch = try Watch(void).init(allocator, 0);
defer watch.deinit();
testing.expect((try watch.addFile(file_path, {})) == null);
try testing.expect((try watch.addFile(file_path, {})) == null);
var ev = async watch.channel.get();
var ev_consumed = false;
@ -698,7 +698,7 @@ fn testWriteWatchWriteDelete(allocator: *Allocator) !void {
const contents_updated = try std.fs.cwd().readFileAlloc(allocator, file_path, 1024 * 1024);
defer allocator.free(contents_updated);
testing.expectEqualSlices(u8,
try testing.expectEqualSlices(u8,
\\line 1
\\lorem ipsum
, contents_updated);

View File

@ -99,21 +99,21 @@ pub const Adler32 = struct {
};
test "adler32 sanity" {
testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a"));
testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example"));
try testing.expectEqual(@as(u32, 0x620062), Adler32.hash("a"));
try testing.expectEqual(@as(u32, 0xbc002ed), Adler32.hash("example"));
}
test "adler32 long" {
const long1 = [_]u8{1} ** 1024;
testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..]));
try testing.expectEqual(@as(u32, 0x06780401), Adler32.hash(long1[0..]));
const long2 = [_]u8{1} ** 1025;
testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..]));
try testing.expectEqual(@as(u32, 0x0a7a0402), Adler32.hash(long2[0..]));
}
test "adler32 very long" {
const long = [_]u8{1} ** 5553;
testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..]));
try testing.expectEqual(@as(u32, 0x707f15b2), Adler32.hash(long[0..]));
}
test "adler32 very long with variation" {
@ -129,5 +129,5 @@ test "adler32 very long with variation" {
break :blk result;
};
testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..]));
try testing.expectEqual(@as(u32, 0x5af38d6e), std.hash.Adler32.hash(long[0..]));
}

View File

@ -239,18 +239,18 @@ fn testHashDeepRecursive(key: anytype) u64 {
test "typeContainsSlice" {
comptime {
testing.expect(!typeContainsSlice(meta.Tag(builtin.TypeInfo)));
try testing.expect(!typeContainsSlice(meta.Tag(builtin.TypeInfo)));
testing.expect(typeContainsSlice([]const u8));
testing.expect(!typeContainsSlice(u8));
try testing.expect(typeContainsSlice([]const u8));
try testing.expect(!typeContainsSlice(u8));
const A = struct { x: []const u8 };
const B = struct { a: A };
const C = struct { b: B };
const D = struct { x: u8 };
testing.expect(typeContainsSlice(A));
testing.expect(typeContainsSlice(B));
testing.expect(typeContainsSlice(C));
testing.expect(!typeContainsSlice(D));
try testing.expect(typeContainsSlice(A));
try testing.expect(typeContainsSlice(B));
try testing.expect(typeContainsSlice(C));
try testing.expect(!typeContainsSlice(D));
}
}
@ -261,17 +261,17 @@ test "hash pointer" {
const c = &array[2];
const d = a;
testing.expect(testHashShallow(a) == testHashShallow(d));
testing.expect(testHashShallow(a) != testHashShallow(c));
testing.expect(testHashShallow(a) != testHashShallow(b));
try testing.expect(testHashShallow(a) == testHashShallow(d));
try testing.expect(testHashShallow(a) != testHashShallow(c));
try testing.expect(testHashShallow(a) != testHashShallow(b));
testing.expect(testHashDeep(a) == testHashDeep(a));
testing.expect(testHashDeep(a) == testHashDeep(c));
testing.expect(testHashDeep(a) == testHashDeep(b));
try testing.expect(testHashDeep(a) == testHashDeep(a));
try testing.expect(testHashDeep(a) == testHashDeep(c));
try testing.expect(testHashDeep(a) == testHashDeep(b));
testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(a));
testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(c));
testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(b));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(a));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(c));
try testing.expect(testHashDeepRecursive(a) == testHashDeepRecursive(b));
}
test "hash slice shallow" {
@ -286,10 +286,10 @@ test "hash slice shallow" {
const a = array1[runtime_zero..];
const b = array2[runtime_zero..];
const c = array1[runtime_zero..3];
testing.expect(testHashShallow(a) == testHashShallow(a));
testing.expect(testHashShallow(a) != testHashShallow(array1));
testing.expect(testHashShallow(a) != testHashShallow(b));
testing.expect(testHashShallow(a) != testHashShallow(c));
try testing.expect(testHashShallow(a) == testHashShallow(a));
try testing.expect(testHashShallow(a) != testHashShallow(array1));
try testing.expect(testHashShallow(a) != testHashShallow(b));
try testing.expect(testHashShallow(a) != testHashShallow(c));
}
test "hash slice deep" {
@ -302,10 +302,10 @@ test "hash slice deep" {
const a = array1[0..];
const b = array2[0..];
const c = array1[0..3];
testing.expect(testHashDeep(a) == testHashDeep(a));
testing.expect(testHashDeep(a) == testHashDeep(array1));
testing.expect(testHashDeep(a) == testHashDeep(b));
testing.expect(testHashDeep(a) != testHashDeep(c));
try testing.expect(testHashDeep(a) == testHashDeep(a));
try testing.expect(testHashDeep(a) == testHashDeep(array1));
try testing.expect(testHashDeep(a) == testHashDeep(b));
try testing.expect(testHashDeep(a) != testHashDeep(c));
}
test "hash struct deep" {
@ -331,28 +331,28 @@ test "hash struct deep" {
defer allocator.destroy(bar.c);
defer allocator.destroy(baz.c);
testing.expect(testHashDeep(foo) == testHashDeep(bar));
testing.expect(testHashDeep(foo) != testHashDeep(baz));
testing.expect(testHashDeep(bar) != testHashDeep(baz));
try testing.expect(testHashDeep(foo) == testHashDeep(bar));
try testing.expect(testHashDeep(foo) != testHashDeep(baz));
try testing.expect(testHashDeep(bar) != testHashDeep(baz));
var hasher = Wyhash.init(0);
const h = testHashDeep(foo);
autoHash(&hasher, foo.a);
autoHash(&hasher, foo.b);
autoHash(&hasher, foo.c.*);
testing.expectEqual(h, hasher.final());
try testing.expectEqual(h, hasher.final());
const h2 = testHashDeepRecursive(&foo);
testing.expect(h2 != testHashDeep(&foo));
testing.expect(h2 == testHashDeep(foo));
try testing.expect(h2 != testHashDeep(&foo));
try testing.expect(h2 == testHashDeep(foo));
}
test "testHash optional" {
const a: ?u32 = 123;
const b: ?u32 = null;
testing.expectEqual(testHash(a), testHash(@as(u32, 123)));
testing.expect(testHash(a) != testHash(b));
testing.expectEqual(testHash(b), 0);
try testing.expectEqual(testHash(a), testHash(@as(u32, 123)));
try testing.expect(testHash(a) != testHash(b));
try testing.expectEqual(testHash(b), 0);
}
test "testHash array" {
@ -362,7 +362,7 @@ test "testHash array" {
autoHash(&hasher, @as(u32, 1));
autoHash(&hasher, @as(u32, 2));
autoHash(&hasher, @as(u32, 3));
testing.expectEqual(h, hasher.final());
try testing.expectEqual(h, hasher.final());
}
test "testHash struct" {
@ -377,7 +377,7 @@ test "testHash struct" {
autoHash(&hasher, @as(u32, 1));
autoHash(&hasher, @as(u32, 2));
autoHash(&hasher, @as(u32, 3));
testing.expectEqual(h, hasher.final());
try testing.expectEqual(h, hasher.final());
}
test "testHash union" {
@ -390,12 +390,12 @@ test "testHash union" {
const a = Foo{ .A = 18 };
var b = Foo{ .B = true };
const c = Foo{ .C = 18 };
testing.expect(testHash(a) == testHash(a));
testing.expect(testHash(a) != testHash(b));
testing.expect(testHash(a) != testHash(c));
try testing.expect(testHash(a) == testHash(a));
try testing.expect(testHash(a) != testHash(b));
try testing.expect(testHash(a) != testHash(c));
b = Foo{ .A = 18 };
testing.expect(testHash(a) == testHash(b));
try testing.expect(testHash(a) == testHash(b));
}
test "testHash vector" {
@ -404,13 +404,13 @@ test "testHash vector" {
const a: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 4 };
const b: meta.Vector(4, u32) = [_]u32{ 1, 2, 3, 5 };
testing.expect(testHash(a) == testHash(a));
testing.expect(testHash(a) != testHash(b));
try testing.expect(testHash(a) == testHash(a));
try testing.expect(testHash(a) != testHash(b));
const c: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 4 };
const d: meta.Vector(4, u31) = [_]u31{ 1, 2, 3, 5 };
testing.expect(testHash(c) == testHash(c));
testing.expect(testHash(c) != testHash(d));
try testing.expect(testHash(c) == testHash(c));
try testing.expect(testHash(c) != testHash(d));
}
test "testHash error union" {
@ -422,7 +422,7 @@ test "testHash error union" {
};
const f = Foo{};
const g: Errors!Foo = Errors.Test;
testing.expect(testHash(f) != testHash(g));
testing.expect(testHash(f) == testHash(Foo{}));
testing.expect(testHash(g) == testHash(Errors.Test));
try testing.expect(testHash(f) != testHash(g));
try testing.expect(testHash(f) == testHash(Foo{}));
try testing.expect(testHash(g) == testHash(Errors.Test));
}

View File

@ -381,14 +381,14 @@ fn CityHash32hashIgnoreSeed(str: []const u8, seed: u32) u32 {
test "cityhash32" {
const Test = struct {
fn doTest() void {
fn doTest() !void {
// Note: SMHasher doesn't provide a 32bit version of the algorithm.
// Note: The implementation was verified against the Google Abseil version.
std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
try std.testing.expectEqual(SMHasherTest(CityHash32hashIgnoreSeed), 0x68254F81);
}
};
Test.doTest();
try Test.doTest();
// TODO This is uncommented to prevent OOM on the CI server. Re-enable this test
// case once we ship stage2.
//@setEvalBranchQuota(50000);
@ -397,13 +397,13 @@ test "cityhash32" {
test "cityhash64" {
const Test = struct {
fn doTest() void {
fn doTest() !void {
// Note: This is not compliant with the SMHasher implementation of CityHash64!
// Note: The implementation was verified against the Google Abseil version.
std.testing.expectEqual(SMHasherTest(CityHash64.hashWithSeed), 0x5FABC5C5);
try std.testing.expectEqual(SMHasherTest(CityHash64.hashWithSeed), 0x5FABC5C5);
}
};
Test.doTest();
try Test.doTest();
// TODO This is uncommented to prevent OOM on the CI server. Re-enable this test
// case once we ship stage2.
//@setEvalBranchQuota(50000);

View File

@ -109,9 +109,9 @@ test "crc32 ieee" {
const Crc32Ieee = Crc32WithPoly(.IEEE);
testing.expect(Crc32Ieee.hash("") == 0x00000000);
testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
try testing.expect(Crc32Ieee.hash("") == 0x00000000);
try testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
try testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
}
test "crc32 castagnoli" {
@ -119,9 +119,9 @@ test "crc32 castagnoli" {
const Crc32Castagnoli = Crc32WithPoly(.Castagnoli);
testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
try testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
try testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
try testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
}
// half-byte lookup table implementation.
@ -177,9 +177,9 @@ test "small crc32 ieee" {
const Crc32Ieee = Crc32SmallWithPoly(.IEEE);
testing.expect(Crc32Ieee.hash("") == 0x00000000);
testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
try testing.expect(Crc32Ieee.hash("") == 0x00000000);
try testing.expect(Crc32Ieee.hash("a") == 0xe8b7be43);
try testing.expect(Crc32Ieee.hash("abc") == 0x352441c2);
}
test "small crc32 castagnoli" {
@ -187,7 +187,7 @@ test "small crc32 castagnoli" {
const Crc32Castagnoli = Crc32SmallWithPoly(.Castagnoli);
testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
try testing.expect(Crc32Castagnoli.hash("") == 0x00000000);
try testing.expect(Crc32Castagnoli.hash("a") == 0xc1d04330);
try testing.expect(Crc32Castagnoli.hash("abc") == 0x364b3fb7);
}

View File

@ -46,18 +46,18 @@ fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type {
}
test "fnv1a-32" {
testing.expect(Fnv1a_32.hash("") == 0x811c9dc5);
testing.expect(Fnv1a_32.hash("a") == 0xe40c292c);
testing.expect(Fnv1a_32.hash("foobar") == 0xbf9cf968);
try testing.expect(Fnv1a_32.hash("") == 0x811c9dc5);
try testing.expect(Fnv1a_32.hash("a") == 0xe40c292c);
try testing.expect(Fnv1a_32.hash("foobar") == 0xbf9cf968);
}
test "fnv1a-64" {
testing.expect(Fnv1a_64.hash("") == 0xcbf29ce484222325);
testing.expect(Fnv1a_64.hash("a") == 0xaf63dc4c8601ec8c);
testing.expect(Fnv1a_64.hash("foobar") == 0x85944171f73967e8);
try testing.expect(Fnv1a_64.hash("") == 0xcbf29ce484222325);
try testing.expect(Fnv1a_64.hash("a") == 0xaf63dc4c8601ec8c);
try testing.expect(Fnv1a_64.hash("foobar") == 0x85944171f73967e8);
}
test "fnv1a-128" {
testing.expect(Fnv1a_128.hash("") == 0x6c62272e07bb014262b821756295c58d);
testing.expect(Fnv1a_128.hash("a") == 0xd228cb696f1a8caf78912b704e4a8964);
try testing.expect(Fnv1a_128.hash("") == 0x6c62272e07bb014262b821756295c58d);
try testing.expect(Fnv1a_128.hash("a") == 0xd228cb696f1a8caf78912b704e4a8964);
}

View File

@ -308,7 +308,7 @@ fn SMHasherTest(comptime hash_fn: anytype, comptime hashbits: u32) u32 {
}
test "murmur2_32" {
testing.expectEqual(SMHasherTest(Murmur2_32.hashWithSeed, 32), 0x27864C1E);
try testing.expectEqual(SMHasherTest(Murmur2_32.hashWithSeed, 32), 0x27864C1E);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
@ -317,12 +317,12 @@ test "murmur2_32" {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}
testing.expectEqual(Murmur2_32.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur2_32.hashUint32(v0));
testing.expectEqual(Murmur2_32.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur2_32.hashUint64(v1));
try testing.expectEqual(Murmur2_32.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur2_32.hashUint32(v0));
try testing.expectEqual(Murmur2_32.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur2_32.hashUint64(v1));
}
test "murmur2_64" {
std.testing.expectEqual(SMHasherTest(Murmur2_64.hashWithSeed, 64), 0x1F0D3804);
try std.testing.expectEqual(SMHasherTest(Murmur2_64.hashWithSeed, 64), 0x1F0D3804);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
@ -331,12 +331,12 @@ test "murmur2_64" {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}
testing.expectEqual(Murmur2_64.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur2_64.hashUint32(v0));
testing.expectEqual(Murmur2_64.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur2_64.hashUint64(v1));
try testing.expectEqual(Murmur2_64.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur2_64.hashUint32(v0));
try testing.expectEqual(Murmur2_64.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur2_64.hashUint64(v1));
}
test "murmur3_32" {
std.testing.expectEqual(SMHasherTest(Murmur3_32.hashWithSeed, 32), 0xB0F57EE3);
try std.testing.expectEqual(SMHasherTest(Murmur3_32.hashWithSeed, 32), 0xB0F57EE3);
var v0: u32 = 0x12345678;
var v1: u64 = 0x1234567812345678;
var v0le: u32 = v0;
@ -345,6 +345,6 @@ test "murmur3_32" {
v0le = @byteSwap(u32, v0le);
v1le = @byteSwap(u64, v1le);
}
testing.expectEqual(Murmur3_32.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur3_32.hashUint32(v0));
testing.expectEqual(Murmur3_32.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur3_32.hashUint64(v1));
try testing.expectEqual(Murmur3_32.hash(@ptrCast([*]u8, &v0le)[0..4]), Murmur3_32.hashUint32(v0));
try testing.expectEqual(Murmur3_32.hash(@ptrCast([*]u8, &v1le)[0..8]), Murmur3_32.hashUint64(v1));
}

View File

@ -183,13 +183,13 @@ const expectEqual = std.testing.expectEqual;
test "test vectors" {
const hash = Wyhash.hash;
expectEqual(hash(0, ""), 0x0);
expectEqual(hash(1, "a"), 0xbed235177f41d328);
expectEqual(hash(2, "abc"), 0xbe348debe59b27c3);
expectEqual(hash(3, "message digest"), 0x37320f657213a290);
expectEqual(hash(4, "abcdefghijklmnopqrstuvwxyz"), 0xd0b270e1d8a7019c);
expectEqual(hash(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0x602a1894d3bbfe7f);
expectEqual(hash(6, "12345678901234567890123456789012345678901234567890123456789012345678901234567890"), 0x829e9c148b75970e);
try expectEqual(hash(0, ""), 0x0);
try expectEqual(hash(1, "a"), 0xbed235177f41d328);
try expectEqual(hash(2, "abc"), 0xbe348debe59b27c3);
try expectEqual(hash(3, "message digest"), 0x37320f657213a290);
try expectEqual(hash(4, "abcdefghijklmnopqrstuvwxyz"), 0xd0b270e1d8a7019c);
try expectEqual(hash(5, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), 0x602a1894d3bbfe7f);
try expectEqual(hash(6, "12345678901234567890123456789012345678901234567890123456789012345678901234567890"), 0x829e9c148b75970e);
}
test "test vectors streaming" {
@ -197,19 +197,19 @@ test "test vectors streaming" {
for ("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") |e| {
wh.update(mem.asBytes(&e));
}
expectEqual(wh.final(), 0x602a1894d3bbfe7f);
try expectEqual(wh.final(), 0x602a1894d3bbfe7f);
const pattern = "1234567890";
const count = 8;
const result = 0x829e9c148b75970e;
expectEqual(Wyhash.hash(6, pattern ** 8), result);
try expectEqual(Wyhash.hash(6, pattern ** 8), result);
wh = Wyhash.init(6);
var i: u32 = 0;
while (i < count) : (i += 1) {
wh.update(pattern);
}
expectEqual(wh.final(), result);
try expectEqual(wh.final(), result);
}
test "iterative non-divisible update" {
@ -231,6 +231,6 @@ test "iterative non-divisible update" {
}
const iterative_hash = wy.final();
std.testing.expectEqual(iterative_hash, non_iterative_hash);
try std.testing.expectEqual(iterative_hash, non_iterative_hash);
}
}

View File

@ -823,15 +823,15 @@ test "std.hash_map basic usage" {
while (it.next()) |kv| {
sum += kv.key;
}
expect(sum == total);
try expect(sum == total);
i = 0;
sum = 0;
while (i < count) : (i += 1) {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
sum += map.get(i).?;
}
expectEqual(total, sum);
try expectEqual(total, sum);
}
test "std.hash_map ensureCapacity" {
@ -840,13 +840,13 @@ test "std.hash_map ensureCapacity" {
try map.ensureCapacity(20);
const initial_capacity = map.capacity();
testing.expect(initial_capacity >= 20);
try testing.expect(initial_capacity >= 20);
var i: i32 = 0;
while (i < 20) : (i += 1) {
testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
try testing.expect(map.fetchPutAssumeCapacity(i, i + 10) == null);
}
// shouldn't resize from putAssumeCapacity
testing.expect(initial_capacity == map.capacity());
try testing.expect(initial_capacity == map.capacity());
}
test "std.hash_map ensureCapacity with tombstones" {
@ -869,22 +869,22 @@ test "std.hash_map clearRetainingCapacity" {
map.clearRetainingCapacity();
try map.put(1, 1);
expectEqual(map.get(1).?, 1);
expectEqual(map.count(), 1);
try expectEqual(map.get(1).?, 1);
try expectEqual(map.count(), 1);
map.clearRetainingCapacity();
map.putAssumeCapacity(1, 1);
expectEqual(map.get(1).?, 1);
expectEqual(map.count(), 1);
try expectEqual(map.get(1).?, 1);
try expectEqual(map.count(), 1);
const cap = map.capacity();
expect(cap > 0);
try expect(cap > 0);
map.clearRetainingCapacity();
map.clearRetainingCapacity();
expectEqual(map.count(), 0);
expectEqual(map.capacity(), cap);
expect(!map.contains(1));
try expectEqual(map.count(), 0);
try expectEqual(map.capacity(), cap);
try expect(!map.contains(1));
}
test "std.hash_map grow" {
@ -897,19 +897,19 @@ test "std.hash_map grow" {
while (i < growTo) : (i += 1) {
try map.put(i, i);
}
expectEqual(map.count(), growTo);
try expectEqual(map.count(), growTo);
i = 0;
var it = map.iterator();
while (it.next()) |kv| {
expectEqual(kv.key, kv.value);
try expectEqual(kv.key, kv.value);
i += 1;
}
expectEqual(i, growTo);
try expectEqual(i, growTo);
i = 0;
while (i < growTo) : (i += 1) {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
}
}
@ -920,7 +920,7 @@ test "std.hash_map clone" {
var a = try map.clone();
defer a.deinit();
expectEqual(a.count(), 0);
try expectEqual(a.count(), 0);
try a.put(1, 1);
try a.put(2, 2);
@ -929,10 +929,10 @@ test "std.hash_map clone" {
var b = try a.clone();
defer b.deinit();
expectEqual(b.count(), 3);
expectEqual(b.get(1), 1);
expectEqual(b.get(2), 2);
expectEqual(b.get(3), 3);
try expectEqual(b.count(), 3);
try expectEqual(b.get(1), 1);
try expectEqual(b.get(2), 2);
try expectEqual(b.get(3), 3);
}
test "std.hash_map ensureCapacity with existing elements" {
@ -940,12 +940,12 @@ test "std.hash_map ensureCapacity with existing elements" {
defer map.deinit();
try map.put(0, 0);
expectEqual(map.count(), 1);
expectEqual(map.capacity(), @TypeOf(map).Unmanaged.minimal_capacity);
try expectEqual(map.count(), 1);
try expectEqual(map.capacity(), @TypeOf(map).Unmanaged.minimal_capacity);
try map.ensureCapacity(65);
expectEqual(map.count(), 1);
expectEqual(map.capacity(), 128);
try expectEqual(map.count(), 1);
try expectEqual(map.capacity(), 128);
}
test "std.hash_map ensureCapacity satisfies max load factor" {
@ -953,7 +953,7 @@ test "std.hash_map ensureCapacity satisfies max load factor" {
defer map.deinit();
try map.ensureCapacity(127);
expectEqual(map.capacity(), 256);
try expectEqual(map.capacity(), 256);
}
test "std.hash_map remove" {
@ -971,19 +971,19 @@ test "std.hash_map remove" {
_ = map.remove(i);
}
}
expectEqual(map.count(), 10);
try expectEqual(map.count(), 10);
var it = map.iterator();
while (it.next()) |kv| {
expectEqual(kv.key, kv.value);
expect(kv.key % 3 != 0);
try expectEqual(kv.key, kv.value);
try expect(kv.key % 3 != 0);
}
i = 0;
while (i < 16) : (i += 1) {
if (i % 3 == 0) {
expect(!map.contains(i));
try expect(!map.contains(i));
} else {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
}
}
}
@ -1000,14 +1000,14 @@ test "std.hash_map reverse removes" {
i = 16;
while (i > 0) : (i -= 1) {
_ = map.remove(i - 1);
expect(!map.contains(i - 1));
try expect(!map.contains(i - 1));
var j: u32 = 0;
while (j < i - 1) : (j += 1) {
expectEqual(map.get(j).?, j);
try expectEqual(map.get(j).?, j);
}
}
expectEqual(map.count(), 0);
try expectEqual(map.count(), 0);
}
test "std.hash_map multiple removes on same metadata" {
@ -1023,17 +1023,17 @@ test "std.hash_map multiple removes on same metadata" {
_ = map.remove(15);
_ = map.remove(14);
_ = map.remove(13);
expect(!map.contains(7));
expect(!map.contains(15));
expect(!map.contains(14));
expect(!map.contains(13));
try expect(!map.contains(7));
try expect(!map.contains(15));
try expect(!map.contains(14));
try expect(!map.contains(13));
i = 0;
while (i < 13) : (i += 1) {
if (i == 7) {
expect(!map.contains(i));
try expect(!map.contains(i));
} else {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
}
}
@ -1043,7 +1043,7 @@ test "std.hash_map multiple removes on same metadata" {
try map.put(7, 7);
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
}
}
@ -1069,12 +1069,12 @@ test "std.hash_map put and remove loop in random order" {
for (keys.items) |key| {
try map.put(key, key);
}
expectEqual(map.count(), size);
try expectEqual(map.count(), size);
for (keys.items) |key| {
_ = map.remove(key);
}
expectEqual(map.count(), 0);
try expectEqual(map.count(), 0);
}
}
@ -1118,7 +1118,7 @@ test "std.hash_map put" {
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i);
try expectEqual(map.get(i).?, i);
}
i = 0;
@ -1128,7 +1128,7 @@ test "std.hash_map put" {
i = 0;
while (i < 16) : (i += 1) {
expectEqual(map.get(i).?, i * 16 + 1);
try expectEqual(map.get(i).?, i * 16 + 1);
}
}
@ -1147,7 +1147,7 @@ test "std.hash_map putAssumeCapacity" {
while (i < 20) : (i += 1) {
sum += map.get(i).?;
}
expectEqual(sum, 190);
try expectEqual(sum, 190);
i = 0;
while (i < 20) : (i += 1) {
@ -1159,7 +1159,7 @@ test "std.hash_map putAssumeCapacity" {
while (i < 20) : (i += 1) {
sum += map.get(i).?;
}
expectEqual(sum, 20);
try expectEqual(sum, 20);
}
test "std.hash_map getOrPut" {
@ -1182,49 +1182,49 @@ test "std.hash_map getOrPut" {
sum += map.get(i).?;
}
expectEqual(sum, 30);
try expectEqual(sum, 30);
}
test "std.hash_map basic hash map usage" {
var map = AutoHashMap(i32, i32).init(std.testing.allocator);
defer map.deinit();
testing.expect((try map.fetchPut(1, 11)) == null);
testing.expect((try map.fetchPut(2, 22)) == null);
testing.expect((try map.fetchPut(3, 33)) == null);
testing.expect((try map.fetchPut(4, 44)) == null);
try testing.expect((try map.fetchPut(1, 11)) == null);
try testing.expect((try map.fetchPut(2, 22)) == null);
try testing.expect((try map.fetchPut(3, 33)) == null);
try testing.expect((try map.fetchPut(4, 44)) == null);
try map.putNoClobber(5, 55);
testing.expect((try map.fetchPut(5, 66)).?.value == 55);
testing.expect((try map.fetchPut(5, 55)).?.value == 66);
try testing.expect((try map.fetchPut(5, 66)).?.value == 55);
try testing.expect((try map.fetchPut(5, 55)).?.value == 66);
const gop1 = try map.getOrPut(5);
testing.expect(gop1.found_existing == true);
testing.expect(gop1.entry.value == 55);
try testing.expect(gop1.found_existing == true);
try testing.expect(gop1.entry.value == 55);
gop1.entry.value = 77;
testing.expect(map.getEntry(5).?.value == 77);
try testing.expect(map.getEntry(5).?.value == 77);
const gop2 = try map.getOrPut(99);
testing.expect(gop2.found_existing == false);
try testing.expect(gop2.found_existing == false);
gop2.entry.value = 42;
testing.expect(map.getEntry(99).?.value == 42);
try testing.expect(map.getEntry(99).?.value == 42);
const gop3 = try map.getOrPutValue(5, 5);
testing.expect(gop3.value == 77);
try testing.expect(gop3.value == 77);
const gop4 = try map.getOrPutValue(100, 41);
testing.expect(gop4.value == 41);
try testing.expect(gop4.value == 41);
testing.expect(map.contains(2));
testing.expect(map.getEntry(2).?.value == 22);
testing.expect(map.get(2).? == 22);
try testing.expect(map.contains(2));
try testing.expect(map.getEntry(2).?.value == 22);
try testing.expect(map.get(2).? == 22);
const rmv1 = map.remove(2);
testing.expect(rmv1.?.key == 2);
testing.expect(rmv1.?.value == 22);
testing.expect(map.remove(2) == null);
testing.expect(map.getEntry(2) == null);
testing.expect(map.get(2) == null);
try testing.expect(rmv1.?.key == 2);
try testing.expect(rmv1.?.value == 22);
try testing.expect(map.remove(2) == null);
try testing.expect(map.getEntry(2) == null);
try testing.expect(map.get(2) == null);
map.removeAssertDiscard(3);
}
@ -1243,6 +1243,6 @@ test "std.hash_map clone" {
i = 0;
while (i < 10) : (i += 1) {
testing.expect(copy.get(i).? == i * 10);
try testing.expect(copy.get(i).? == i * 10);
}
}

View File

@ -858,16 +858,16 @@ test "WasmPageAllocator internals" {
if (comptime std.Target.current.isWasm()) {
const conventional_memsize = WasmPageAllocator.conventional.totalPages() * mem.page_size;
const initial = try page_allocator.alloc(u8, mem.page_size);
testing.expect(@ptrToInt(initial.ptr) < conventional_memsize); // If this isn't conventional, the rest of these tests don't make sense. Also we have a serious memory leak in the test suite.
try testing.expect(@ptrToInt(initial.ptr) < conventional_memsize); // If this isn't conventional, the rest of these tests don't make sense. Also we have a serious memory leak in the test suite.
var inplace = try page_allocator.realloc(initial, 1);
testing.expectEqual(initial.ptr, inplace.ptr);
try testing.expectEqual(initial.ptr, inplace.ptr);
inplace = try page_allocator.realloc(inplace, 4);
testing.expectEqual(initial.ptr, inplace.ptr);
try testing.expectEqual(initial.ptr, inplace.ptr);
page_allocator.free(inplace);
const reuse = try page_allocator.alloc(u8, 1);
testing.expectEqual(initial.ptr, reuse.ptr);
try testing.expectEqual(initial.ptr, reuse.ptr);
page_allocator.free(reuse);
// This segment may span conventional and extended which has really complex rules so we're just ignoring it for now.
@ -875,18 +875,18 @@ test "WasmPageAllocator internals" {
page_allocator.free(padding);
const extended = try page_allocator.alloc(u8, conventional_memsize);
testing.expect(@ptrToInt(extended.ptr) >= conventional_memsize);
try testing.expect(@ptrToInt(extended.ptr) >= conventional_memsize);
const use_small = try page_allocator.alloc(u8, 1);
testing.expectEqual(initial.ptr, use_small.ptr);
try testing.expectEqual(initial.ptr, use_small.ptr);
page_allocator.free(use_small);
inplace = try page_allocator.realloc(extended, 1);
testing.expectEqual(extended.ptr, inplace.ptr);
try testing.expectEqual(extended.ptr, inplace.ptr);
page_allocator.free(inplace);
const reuse_extended = try page_allocator.alloc(u8, conventional_memsize);
testing.expectEqual(extended.ptr, reuse_extended.ptr);
try testing.expectEqual(extended.ptr, reuse_extended.ptr);
page_allocator.free(reuse_extended);
}
}
@ -959,15 +959,15 @@ test "FixedBufferAllocator.reset" {
var x = try fba.allocator.create(u64);
x.* = X;
testing.expectError(error.OutOfMemory, fba.allocator.create(u64));
try testing.expectError(error.OutOfMemory, fba.allocator.create(u64));
fba.reset();
var y = try fba.allocator.create(u64);
y.* = Y;
// we expect Y to have overwritten X.
testing.expect(x.* == y.*);
testing.expect(y.* == Y);
try testing.expect(x.* == y.*);
try testing.expect(y.* == Y);
}
test "StackFallbackAllocator" {
@ -987,11 +987,11 @@ test "FixedBufferAllocator Reuse memory on realloc" {
var fixed_buffer_allocator = FixedBufferAllocator.init(small_fixed_buffer[0..]);
var slice0 = try fixed_buffer_allocator.allocator.alloc(u8, 5);
testing.expect(slice0.len == 5);
try testing.expect(slice0.len == 5);
var slice1 = try fixed_buffer_allocator.allocator.realloc(slice0, 10);
testing.expect(slice1.ptr == slice0.ptr);
testing.expect(slice1.len == 10);
testing.expectError(error.OutOfMemory, fixed_buffer_allocator.allocator.realloc(slice1, 11));
try testing.expect(slice1.ptr == slice0.ptr);
try testing.expect(slice1.len == 10);
try testing.expectError(error.OutOfMemory, fixed_buffer_allocator.allocator.realloc(slice1, 11));
}
// check that we don't re-use the memory if it's not the most recent block
{
@ -1002,10 +1002,10 @@ test "FixedBufferAllocator Reuse memory on realloc" {
slice0[1] = 2;
var slice1 = try fixed_buffer_allocator.allocator.alloc(u8, 2);
var slice2 = try fixed_buffer_allocator.allocator.realloc(slice0, 4);
testing.expect(slice0.ptr != slice2.ptr);
testing.expect(slice1.ptr != slice2.ptr);
testing.expect(slice2[0] == 1);
testing.expect(slice2[1] == 2);
try testing.expect(slice0.ptr != slice2.ptr);
try testing.expect(slice1.ptr != slice2.ptr);
try testing.expect(slice2[0] == 1);
try testing.expect(slice2[1] == 2);
}
}
@ -1024,28 +1024,28 @@ pub fn testAllocator(base_allocator: *mem.Allocator) !void {
const allocator = &validationAllocator.allocator;
var slice = try allocator.alloc(*i32, 100);
testing.expect(slice.len == 100);
try testing.expect(slice.len == 100);
for (slice) |*item, i| {
item.* = try allocator.create(i32);
item.*.* = @intCast(i32, i);
}
slice = try allocator.realloc(slice, 20000);
testing.expect(slice.len == 20000);
try testing.expect(slice.len == 20000);
for (slice[0..100]) |item, i| {
testing.expect(item.* == @intCast(i32, i));
try testing.expect(item.* == @intCast(i32, i));
allocator.destroy(item);
}
slice = allocator.shrink(slice, 50);
testing.expect(slice.len == 50);
try testing.expect(slice.len == 50);
slice = allocator.shrink(slice, 25);
testing.expect(slice.len == 25);
try testing.expect(slice.len == 25);
slice = allocator.shrink(slice, 0);
testing.expect(slice.len == 0);
try testing.expect(slice.len == 0);
slice = try allocator.realloc(slice, 10);
testing.expect(slice.len == 10);
try testing.expect(slice.len == 10);
allocator.free(slice);
@ -1058,7 +1058,7 @@ pub fn testAllocator(base_allocator: *mem.Allocator) !void {
allocator.destroy(zero_bit_ptr);
const oversize = try allocator.allocAdvanced(u32, null, 5, .at_least);
testing.expect(oversize.len >= 5);
try testing.expect(oversize.len >= 5);
for (oversize) |*item| {
item.* = 0xDEADBEEF;
}
@ -1073,29 +1073,29 @@ pub fn testAllocatorAligned(base_allocator: *mem.Allocator) !void {
inline for ([_]u29{ 1, 2, 4, 8, 16, 32, 64 }) |alignment| {
// initial
var slice = try allocator.alignedAlloc(u8, alignment, 10);
testing.expect(slice.len == 10);
try testing.expect(slice.len == 10);
// grow
slice = try allocator.realloc(slice, 100);
testing.expect(slice.len == 100);
try testing.expect(slice.len == 100);
// shrink
slice = allocator.shrink(slice, 10);
testing.expect(slice.len == 10);
try testing.expect(slice.len == 10);
// go to zero
slice = allocator.shrink(slice, 0);
testing.expect(slice.len == 0);
try testing.expect(slice.len == 0);
// realloc from zero
slice = try allocator.realloc(slice, 100);
testing.expect(slice.len == 100);
try testing.expect(slice.len == 100);
// shrink with shrink
slice = allocator.shrink(slice, 10);
testing.expect(slice.len == 10);
try testing.expect(slice.len == 10);
// shrink to zero
slice = allocator.shrink(slice, 0);
testing.expect(slice.len == 0);
try testing.expect(slice.len == 0);
}
}
pub fn testAllocatorLargeAlignment(base_allocator: *mem.Allocator) mem.Allocator.Error!void {
pub fn testAllocatorLargeAlignment(base_allocator: *mem.Allocator) !void {
var validationAllocator = mem.validationWrap(base_allocator);
const allocator = &validationAllocator.allocator;
@ -1110,24 +1110,24 @@ pub fn testAllocatorLargeAlignment(base_allocator: *mem.Allocator) mem.Allocator
_ = @shlWithOverflow(usize, ~@as(usize, 0), @as(USizeShift, @ctz(u29, large_align)), &align_mask);
var slice = try allocator.alignedAlloc(u8, large_align, 500);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
try testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = allocator.shrink(slice, 100);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
try testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.realloc(slice, 5000);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
try testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = allocator.shrink(slice, 10);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
try testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
slice = try allocator.realloc(slice, 20000);
testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
try testing.expect(@ptrToInt(slice.ptr) & align_mask == @ptrToInt(slice.ptr));
allocator.free(slice);
}
pub fn testAllocatorAlignedShrink(base_allocator: *mem.Allocator) mem.Allocator.Error!void {
pub fn testAllocatorAlignedShrink(base_allocator: *mem.Allocator) !void {
var validationAllocator = mem.validationWrap(base_allocator);
const allocator = &validationAllocator.allocator;
@ -1155,8 +1155,8 @@ pub fn testAllocatorAlignedShrink(base_allocator: *mem.Allocator) mem.Allocator.
// realloc to a smaller size but with a larger alignment
slice = try allocator.reallocAdvanced(slice, mem.page_size * 32, alloc_size / 2, .exact);
testing.expect(slice[0] == 0x12);
testing.expect(slice[60] == 0x34);
try testing.expect(slice[0] == 0x12);
try testing.expect(slice[60] == 0x34);
}
test "heap" {

View File

@ -697,7 +697,7 @@ const test_config = Config{};
test "small allocations - free in same order" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var list = std.ArrayList(*u64).init(std.testing.allocator);
@ -716,7 +716,7 @@ test "small allocations - free in same order" {
test "small allocations - free in reverse order" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var list = std.ArrayList(*u64).init(std.testing.allocator);
@ -735,7 +735,7 @@ test "small allocations - free in reverse order" {
test "large allocations" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
const ptr1 = try allocator.alloc(u64, 42768);
@ -748,7 +748,7 @@ test "large allocations" {
test "realloc" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alignedAlloc(u8, @alignOf(u32), 1);
@ -758,19 +758,19 @@ test "realloc" {
// This reallocation should keep its pointer address.
const old_slice = slice;
slice = try allocator.realloc(slice, 2);
std.testing.expect(old_slice.ptr == slice.ptr);
std.testing.expect(slice[0] == 0x12);
try std.testing.expect(old_slice.ptr == slice.ptr);
try std.testing.expect(slice[0] == 0x12);
slice[1] = 0x34;
// This requires upgrading to a larger size class
slice = try allocator.realloc(slice, 17);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[1] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[1] == 0x34);
}
test "shrink" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alloc(u8, 20);
@ -781,19 +781,19 @@ test "shrink" {
slice = allocator.shrink(slice, 17);
for (slice) |b| {
std.testing.expect(b == 0x11);
try std.testing.expect(b == 0x11);
}
slice = allocator.shrink(slice, 16);
for (slice) |b| {
std.testing.expect(b == 0x11);
try std.testing.expect(b == 0x11);
}
}
test "large object - grow" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice1 = try allocator.alloc(u8, page_size * 2 - 20);
@ -801,17 +801,17 @@ test "large object - grow" {
const old = slice1;
slice1 = try allocator.realloc(slice1, page_size * 2 - 10);
std.testing.expect(slice1.ptr == old.ptr);
try std.testing.expect(slice1.ptr == old.ptr);
slice1 = try allocator.realloc(slice1, page_size * 2);
std.testing.expect(slice1.ptr == old.ptr);
try std.testing.expect(slice1.ptr == old.ptr);
slice1 = try allocator.realloc(slice1, page_size * 2 + 1);
}
test "realloc small object to large object" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alloc(u8, 70);
@ -822,13 +822,13 @@ test "realloc small object to large object" {
// This requires upgrading to a large object
const large_object_size = page_size * 2 + 50;
slice = try allocator.realloc(slice, large_object_size);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[60] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[60] == 0x34);
}
test "shrink large object to large object" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alloc(u8, page_size * 2 + 50);
@ -837,21 +837,21 @@ test "shrink large object to large object" {
slice[60] = 0x34;
slice = try allocator.resize(slice, page_size * 2 + 1);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[60] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[60] == 0x34);
slice = allocator.shrink(slice, page_size * 2 + 1);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[60] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[60] == 0x34);
slice = try allocator.realloc(slice, page_size * 2);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[60] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[60] == 0x34);
}
test "shrink large object to large object with larger alignment" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var debug_buffer: [1000]u8 = undefined;
@ -880,13 +880,13 @@ test "shrink large object to large object with larger alignment" {
slice[60] = 0x34;
slice = try allocator.reallocAdvanced(slice, big_alignment, alloc_size / 2, .exact);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[60] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[60] == 0x34);
}
test "realloc large object to small object" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alloc(u8, page_size * 2 + 50);
@ -895,8 +895,8 @@ test "realloc large object to small object" {
slice[16] = 0x34;
slice = try allocator.realloc(slice, 19);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[16] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[16] == 0x34);
}
test "overrideable mutexes" {
@ -904,7 +904,7 @@ test "overrideable mutexes" {
.backing_allocator = std.testing.allocator,
.mutex = std.Thread.Mutex{},
};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
const ptr = try allocator.create(i32);
@ -913,7 +913,7 @@ test "overrideable mutexes" {
test "non-page-allocator backing allocator" {
var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = std.testing.allocator };
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
const ptr = try allocator.create(i32);
@ -922,7 +922,7 @@ test "non-page-allocator backing allocator" {
test "realloc large object to larger alignment" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var debug_buffer: [1000]u8 = undefined;
@ -948,22 +948,22 @@ test "realloc large object to larger alignment" {
slice[16] = 0x34;
slice = try allocator.reallocAdvanced(slice, 32, page_size * 2 + 100, .exact);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[16] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[16] == 0x34);
slice = try allocator.reallocAdvanced(slice, 32, page_size * 2 + 25, .exact);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[16] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[16] == 0x34);
slice = try allocator.reallocAdvanced(slice, big_alignment, page_size * 2 + 100, .exact);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[16] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[16] == 0x34);
}
test "large object shrinks to small but allocation fails during shrink" {
var failing_allocator = std.testing.FailingAllocator.init(std.heap.page_allocator, 3);
var gpa = GeneralPurposeAllocator(.{}){ .backing_allocator = &failing_allocator.allocator };
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
var slice = try allocator.alloc(u8, page_size * 2 + 50);
@ -974,13 +974,13 @@ test "large object shrinks to small but allocation fails during shrink" {
// Next allocation will fail in the backing allocator of the GeneralPurposeAllocator
slice = allocator.shrink(slice, 4);
std.testing.expect(slice[0] == 0x12);
std.testing.expect(slice[3] == 0x34);
try std.testing.expect(slice[0] == 0x12);
try std.testing.expect(slice[3] == 0x34);
}
test "objects of size 1024 and 2048" {
var gpa = GeneralPurposeAllocator(test_config){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
const slice = try allocator.alloc(u8, 1025);
@ -992,26 +992,26 @@ test "objects of size 1024 and 2048" {
test "setting a memory cap" {
var gpa = GeneralPurposeAllocator(.{ .enable_memory_limit = true }){};
defer std.testing.expect(!gpa.deinit());
defer std.testing.expect(!gpa.deinit()) catch @panic("leak");
const allocator = &gpa.allocator;
gpa.setRequestedMemoryLimit(1010);
const small = try allocator.create(i32);
std.testing.expect(gpa.total_requested_bytes == 4);
try std.testing.expect(gpa.total_requested_bytes == 4);
const big = try allocator.alloc(u8, 1000);
std.testing.expect(gpa.total_requested_bytes == 1004);
try std.testing.expect(gpa.total_requested_bytes == 1004);
std.testing.expectError(error.OutOfMemory, allocator.create(u64));
try std.testing.expectError(error.OutOfMemory, allocator.create(u64));
allocator.destroy(small);
std.testing.expect(gpa.total_requested_bytes == 1000);
try std.testing.expect(gpa.total_requested_bytes == 1000);
allocator.free(big);
std.testing.expect(gpa.total_requested_bytes == 0);
try std.testing.expect(gpa.total_requested_bytes == 0);
const exact = try allocator.alloc(u8, 1010);
std.testing.expect(gpa.total_requested_bytes == 1010);
try std.testing.expect(gpa.total_requested_bytes == 1010);
allocator.free(exact);
}

View File

@ -93,11 +93,11 @@ test "LoggingAllocator" {
var a = try allocator.alloc(u8, 10);
a = allocator.shrink(a, 5);
std.testing.expect(a.len == 5);
std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
try std.testing.expect(a.len == 5);
try std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20));
allocator.free(a);
std.testing.expectEqualSlices(u8,
try std.testing.expectEqualSlices(u8,
\\alloc : 10 success!
\\shrink: 10 to 5
\\expand: 5 to 20 failure!

View File

@ -185,64 +185,64 @@ test "api coverage" {
const expect = testing.expect;
const expectError = testing.expectError;
expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
try expect(1 == try bit_stream_be.readBits(u2, 1, &out_bits));
try expect(out_bits == 1);
try expect(2 == try bit_stream_be.readBits(u5, 2, &out_bits));
try expect(out_bits == 2);
try expect(3 == try bit_stream_be.readBits(u128, 3, &out_bits));
try expect(out_bits == 3);
try expect(4 == try bit_stream_be.readBits(u8, 4, &out_bits));
try expect(out_bits == 4);
try expect(5 == try bit_stream_be.readBits(u9, 5, &out_bits));
try expect(out_bits == 5);
try expect(1 == try bit_stream_be.readBits(u1, 1, &out_bits));
try expect(out_bits == 1);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
try expect(0b110011010000101 == try bit_stream_be.readBits(u15, 15, &out_bits));
try expect(out_bits == 15);
mem_in_be.pos = 0;
bit_stream_be.bit_count = 0;
expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
try expect(0b1100110100001011 == try bit_stream_be.readBits(u16, 16, &out_bits));
try expect(out_bits == 16);
_ = try bit_stream_be.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
try expect(0 == try bit_stream_be.readBits(u1, 1, &out_bits));
try expect(out_bits == 0);
try expectError(error.EndOfStream, bit_stream_be.readBitsNoEof(u1, 1));
var mem_in_le = io.fixedBufferStream(&mem_le);
var bit_stream_le = bitReader(.Little, mem_in_le.reader());
expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
try expect(1 == try bit_stream_le.readBits(u2, 1, &out_bits));
try expect(out_bits == 1);
try expect(2 == try bit_stream_le.readBits(u5, 2, &out_bits));
try expect(out_bits == 2);
try expect(3 == try bit_stream_le.readBits(u128, 3, &out_bits));
try expect(out_bits == 3);
try expect(4 == try bit_stream_le.readBits(u8, 4, &out_bits));
try expect(out_bits == 4);
try expect(5 == try bit_stream_le.readBits(u9, 5, &out_bits));
try expect(out_bits == 5);
try expect(1 == try bit_stream_le.readBits(u1, 1, &out_bits));
try expect(out_bits == 1);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
expect(out_bits == 15);
try expect(0b001010100011101 == try bit_stream_le.readBits(u15, 15, &out_bits));
try expect(out_bits == 15);
mem_in_le.pos = 0;
bit_stream_le.bit_count = 0;
expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
expect(out_bits == 16);
try expect(0b1001010100011101 == try bit_stream_le.readBits(u16, 16, &out_bits));
try expect(out_bits == 16);
_ = try bit_stream_le.readBits(u0, 0, &out_bits);
expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
expect(out_bits == 0);
expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
try expect(0 == try bit_stream_le.readBits(u1, 1, &out_bits));
try expect(out_bits == 0);
try expectError(error.EndOfStream, bit_stream_le.readBitsNoEof(u1, 1));
}

View File

@ -163,17 +163,17 @@ test "api coverage" {
try bit_stream_be.writeBits(@as(u9, 5), 5);
try bit_stream_be.writeBits(@as(u1, 1), 1);
testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
try testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001011);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_be.flushBits();
testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
try testing.expect(mem_be[0] == 0b11001101 and mem_be[1] == 0b00001010);
mem_out_be.pos = 0;
try bit_stream_be.writeBits(@as(u32, 0b110011010000101), 16);
testing.expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
try testing.expect(mem_be[0] == 0b01100110 and mem_be[1] == 0b10000101);
try bit_stream_be.writeBits(@as(u0, 0), 0);
@ -187,16 +187,16 @@ test "api coverage" {
try bit_stream_le.writeBits(@as(u9, 5), 5);
try bit_stream_le.writeBits(@as(u1, 1), 1);
testing.expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
try testing.expect(mem_le[0] == 0b00011101 and mem_le[1] == 0b10010101);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(@as(u15, 0b110011010000101), 15);
try bit_stream_le.flushBits();
testing.expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
try testing.expect(mem_le[0] == 0b10000101 and mem_le[1] == 0b01100110);
mem_out_le.pos = 0;
try bit_stream_le.writeBits(@as(u32, 0b1100110100001011), 16);
testing.expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
try testing.expect(mem_le[0] == 0b00001011 and mem_le[1] == 0b11001101);
try bit_stream_le.writeBits(@as(u0, 0), 0);
}

View File

@ -87,5 +87,5 @@ test "io.BufferedReader" {
const res = try stream.readAllAlloc(testing.allocator, str.len + 1);
defer testing.allocator.free(res);
testing.expectEqualSlices(u8, str, res);
try testing.expectEqualSlices(u8, str, res);
}

View File

@ -41,8 +41,8 @@ test "io.CountingReader" {
//read and discard all bytes
while (stream.readByte()) |_| {} else |err| {
testing.expect(err == error.EndOfStream);
try testing.expect(err == error.EndOfStream);
}
testing.expect(counting_stream.bytes_read == bytes.len);
try testing.expect(counting_stream.bytes_read == bytes.len);
}

View File

@ -40,5 +40,5 @@ test "io.CountingWriter" {
const bytes = "yay" ** 100;
stream.writeAll(bytes) catch unreachable;
testing.expect(counting_stream.bytes_written == bytes.len);
try testing.expect(counting_stream.bytes_written == bytes.len);
}

View File

@ -134,7 +134,7 @@ test "FixedBufferStream output" {
const stream = fbs.writer();
try stream.print("{s}{s}!", .{ "Hello", "World" });
testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
try testing.expectEqualSlices(u8, "HelloWorld!", fbs.getWritten());
}
test "FixedBufferStream output 2" {
@ -142,19 +142,19 @@ test "FixedBufferStream output 2" {
var fbs = fixedBufferStream(&buffer);
try fbs.writer().writeAll("Hello");
testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello"));
try fbs.writer().writeAll("world");
testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!"));
testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("!"));
try testing.expect(mem.eql(u8, fbs.getWritten(), "Helloworld"));
fbs.reset();
testing.expect(fbs.getWritten().len == 0);
try testing.expect(fbs.getWritten().len == 0);
testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!"));
testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
try testing.expectError(error.NoSpaceLeft, fbs.writer().writeAll("Hello world!"));
try testing.expect(mem.eql(u8, fbs.getWritten(), "Hello worl"));
}
test "FixedBufferStream input" {
@ -164,13 +164,13 @@ test "FixedBufferStream input" {
var dest: [4]u8 = undefined;
var read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 4);
testing.expect(mem.eql(u8, dest[0..4], bytes[0..4]));
try testing.expect(read == 4);
try testing.expect(mem.eql(u8, dest[0..4], bytes[0..4]));
read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 3);
testing.expect(mem.eql(u8, dest[0..3], bytes[4..7]));
try testing.expect(read == 3);
try testing.expect(mem.eql(u8, dest[0..3], bytes[4..7]));
read = try fbs.reader().read(dest[0..4]);
testing.expect(read == 0);
try testing.expect(read == 0);
}

View File

@ -43,8 +43,8 @@ test "basic usage" {
var early_stream = limitedReader(fbs.reader(), 3);
var buf: [5]u8 = undefined;
testing.expectEqual(@as(usize, 3), try early_stream.reader().read(&buf));
testing.expectEqualSlices(u8, data[0..3], buf[0..3]);
testing.expectEqual(@as(usize, 0), try early_stream.reader().read(&buf));
testing.expectError(error.EndOfStream, early_stream.reader().skipBytes(10, .{}));
try testing.expectEqual(@as(usize, 3), try early_stream.reader().read(&buf));
try testing.expectEqualSlices(u8, data[0..3], buf[0..3]);
try testing.expectEqual(@as(usize, 0), try early_stream.reader().read(&buf));
try testing.expectError(error.EndOfStream, early_stream.reader().skipBytes(10, .{}));
}

View File

@ -52,6 +52,6 @@ test "MultiWriter" {
var fbs2 = io.fixedBufferStream(&buf2);
var stream = multiWriter(.{ fbs1.writer(), fbs2.writer() });
try stream.writer().print("HI", .{});
testing.expectEqualSlices(u8, "HI", fbs1.getWritten());
testing.expectEqualSlices(u8, "HI", fbs2.getWritten());
try testing.expectEqualSlices(u8, "HI", fbs1.getWritten());
try testing.expectEqualSlices(u8, "HI", fbs2.getWritten());
}

View File

@ -94,24 +94,24 @@ test "PeekStream" {
try ps.putBackByte(10);
var read = try ps.reader().read(dest[0..4]);
testing.expect(read == 4);
testing.expect(dest[0] == 10);
testing.expect(dest[1] == 9);
testing.expect(mem.eql(u8, dest[2..4], bytes[0..2]));
try testing.expect(read == 4);
try testing.expect(dest[0] == 10);
try testing.expect(dest[1] == 9);
try testing.expect(mem.eql(u8, dest[2..4], bytes[0..2]));
read = try ps.reader().read(dest[0..4]);
testing.expect(read == 4);
testing.expect(mem.eql(u8, dest[0..4], bytes[2..6]));
try testing.expect(read == 4);
try testing.expect(mem.eql(u8, dest[0..4], bytes[2..6]));
read = try ps.reader().read(dest[0..4]);
testing.expect(read == 2);
testing.expect(mem.eql(u8, dest[0..2], bytes[6..8]));
try testing.expect(read == 2);
try testing.expect(mem.eql(u8, dest[0..2], bytes[6..8]));
try ps.putBackByte(11);
try ps.putBackByte(12);
read = try ps.reader().read(dest[0..4]);
testing.expect(read == 2);
testing.expect(dest[0] == 12);
testing.expect(dest[1] == 11);
try testing.expect(read == 2);
try testing.expect(dest[0] == 12);
try testing.expect(dest[1] == 11);
}

View File

@ -329,26 +329,26 @@ pub fn Reader(
test "Reader" {
var buf = "a\x02".*;
const reader = std.io.fixedBufferStream(&buf).reader();
testing.expect((try reader.readByte()) == 'a');
testing.expect((try reader.readEnum(enum(u8) {
try testing.expect((try reader.readByte()) == 'a');
try testing.expect((try reader.readEnum(enum(u8) {
a = 0,
b = 99,
c = 2,
d = 3,
}, undefined)) == .c);
testing.expectError(error.EndOfStream, reader.readByte());
try testing.expectError(error.EndOfStream, reader.readByte());
}
test "Reader.isBytes" {
const reader = std.io.fixedBufferStream("foobar").reader();
testing.expectEqual(true, try reader.isBytes("foo"));
testing.expectEqual(false, try reader.isBytes("qux"));
try testing.expectEqual(true, try reader.isBytes("foo"));
try testing.expectEqual(false, try reader.isBytes("qux"));
}
test "Reader.skipBytes" {
const reader = std.io.fixedBufferStream("foobar").reader();
try reader.skipBytes(3, .{});
testing.expect(try reader.isBytes("bar"));
try testing.expect(try reader.isBytes("bar"));
try reader.skipBytes(0, .{});
testing.expectError(error.EndOfStream, reader.skipBytes(1, .{}));
try testing.expectError(error.EndOfStream, reader.skipBytes(1, .{}));
}

View File

@ -40,7 +40,7 @@ test "write a file, read it, then delete it" {
{
// Make sure the exclusive flag is honored.
expectError(File.OpenError.PathAlreadyExists, tmp.dir.createFile(tmp_file_name, .{ .exclusive = true }));
try expectError(File.OpenError.PathAlreadyExists, tmp.dir.createFile(tmp_file_name, .{ .exclusive = true }));
}
{
@ -49,16 +49,16 @@ test "write a file, read it, then delete it" {
const file_size = try file.getEndPos();
const expected_file_size: u64 = "begin".len + data.len + "end".len;
expectEqual(expected_file_size, file_size);
try expectEqual(expected_file_size, file_size);
var buf_stream = io.bufferedReader(file.reader());
const st = buf_stream.reader();
const contents = try st.readAllAlloc(std.testing.allocator, 2 * 1024);
defer std.testing.allocator.free(contents);
expect(mem.eql(u8, contents[0.."begin".len], "begin"));
expect(mem.eql(u8, contents["begin".len .. contents.len - "end".len], &data));
expect(mem.eql(u8, contents[contents.len - "end".len ..], "end"));
try expect(mem.eql(u8, contents[0.."begin".len], "begin"));
try expect(mem.eql(u8, contents["begin".len .. contents.len - "end".len], &data));
try expect(mem.eql(u8, contents[contents.len - "end".len ..], "end"));
}
try tmp.dir.deleteFile(tmp_file_name);
}
@ -90,20 +90,20 @@ test "BitStreams with File Stream" {
var out_bits: usize = undefined;
expect(1 == try bit_stream.readBits(u2, 1, &out_bits));
expect(out_bits == 1);
expect(2 == try bit_stream.readBits(u5, 2, &out_bits));
expect(out_bits == 2);
expect(3 == try bit_stream.readBits(u128, 3, &out_bits));
expect(out_bits == 3);
expect(4 == try bit_stream.readBits(u8, 4, &out_bits));
expect(out_bits == 4);
expect(5 == try bit_stream.readBits(u9, 5, &out_bits));
expect(out_bits == 5);
expect(1 == try bit_stream.readBits(u1, 1, &out_bits));
expect(out_bits == 1);
try expect(1 == try bit_stream.readBits(u2, 1, &out_bits));
try expect(out_bits == 1);
try expect(2 == try bit_stream.readBits(u5, 2, &out_bits));
try expect(out_bits == 2);
try expect(3 == try bit_stream.readBits(u128, 3, &out_bits));
try expect(out_bits == 3);
try expect(4 == try bit_stream.readBits(u8, 4, &out_bits));
try expect(out_bits == 4);
try expect(5 == try bit_stream.readBits(u9, 5, &out_bits));
try expect(out_bits == 5);
try expect(1 == try bit_stream.readBits(u1, 1, &out_bits));
try expect(out_bits == 1);
expectError(error.EndOfStream, bit_stream.readBitsNoEof(u1, 1));
try expectError(error.EndOfStream, bit_stream.readBitsNoEof(u1, 1));
}
try tmp.dir.deleteFile(tmp_file_name);
}
@ -123,16 +123,16 @@ test "File seek ops" {
// Seek to the end
try file.seekFromEnd(0);
expect((try file.getPos()) == try file.getEndPos());
try expect((try file.getPos()) == try file.getEndPos());
// Negative delta
try file.seekBy(-4096);
expect((try file.getPos()) == 4096);
try expect((try file.getPos()) == 4096);
// Positive delta
try file.seekBy(10);
expect((try file.getPos()) == 4106);
try expect((try file.getPos()) == 4106);
// Absolute position
try file.seekTo(1234);
expect((try file.getPos()) == 1234);
try expect((try file.getPos()) == 1234);
}
test "setEndPos" {
@ -147,18 +147,18 @@ test "setEndPos" {
}
// Verify that the file size changes and the file offset is not moved
std.testing.expect((try file.getEndPos()) == 0);
std.testing.expect((try file.getPos()) == 0);
try std.testing.expect((try file.getEndPos()) == 0);
try std.testing.expect((try file.getPos()) == 0);
try file.setEndPos(8192);
std.testing.expect((try file.getEndPos()) == 8192);
std.testing.expect((try file.getPos()) == 0);
try std.testing.expect((try file.getEndPos()) == 8192);
try std.testing.expect((try file.getPos()) == 0);
try file.seekTo(100);
try file.setEndPos(4096);
std.testing.expect((try file.getEndPos()) == 4096);
std.testing.expect((try file.getPos()) == 100);
try std.testing.expect((try file.getEndPos()) == 4096);
try std.testing.expect((try file.getPos()) == 100);
try file.setEndPos(0);
std.testing.expect((try file.getEndPos()) == 0);
std.testing.expect((try file.getPos()) == 100);
try std.testing.expect((try file.getEndPos()) == 0);
try std.testing.expect((try file.getPos()) == 100);
}
test "updateTimes" {
@ -178,6 +178,6 @@ test "updateTimes" {
stat_old.mtime - 5 * std.time.ns_per_s,
);
var stat_new = try file.stat();
expect(stat_new.atime < stat_old.atime);
expect(stat_new.mtime < stat_old.mtime);
try expect(stat_new.atime < stat_old.atime);
try expect(stat_new.mtime < stat_old.mtime);
}

View File

@ -79,18 +79,18 @@ fn encodesTo(decoded: []const u8, encoded: []const u8) bool {
test "encodesTo" {
// same
testing.expectEqual(true, encodesTo("false", "false"));
try testing.expectEqual(true, encodesTo("false", "false"));
// totally different
testing.expectEqual(false, encodesTo("false", "true"));
try testing.expectEqual(false, encodesTo("false", "true"));
// different lengths
testing.expectEqual(false, encodesTo("false", "other"));
try testing.expectEqual(false, encodesTo("false", "other"));
// with escape
testing.expectEqual(true, encodesTo("\\", "\\\\"));
testing.expectEqual(true, encodesTo("with\nescape", "with\\nescape"));
try testing.expectEqual(true, encodesTo("\\", "\\\\"));
try testing.expectEqual(true, encodesTo("with\nescape", "with\\nescape"));
// with unicode
testing.expectEqual(true, encodesTo("ą", "\\u0105"));
testing.expectEqual(true, encodesTo("😂", "\\ud83d\\ude02"));
testing.expectEqual(true, encodesTo("withąunicode😂", "with\\u0105unicode\\ud83d\\ude02"));
try testing.expectEqual(true, encodesTo("ą", "\\u0105"));
try testing.expectEqual(true, encodesTo("😂", "\\ud83d\\ude02"));
try testing.expectEqual(true, encodesTo("withąunicode😂", "with\\u0105unicode\\ud83d\\ude02"));
}
/// A single token slice into the parent string.
@ -1138,9 +1138,9 @@ pub const TokenStream = struct {
}
};
fn checkNext(p: *TokenStream, id: std.meta.Tag(Token)) void {
fn checkNext(p: *TokenStream, id: std.meta.Tag(Token)) !void {
const token = (p.next() catch unreachable).?;
debug.assert(std.meta.activeTag(token) == id);
try testing.expect(std.meta.activeTag(token) == id);
}
test "json.token" {
@ -1163,46 +1163,46 @@ test "json.token" {
var p = TokenStream.init(s);
checkNext(&p, .ObjectBegin);
checkNext(&p, .String); // Image
checkNext(&p, .ObjectBegin);
checkNext(&p, .String); // Width
checkNext(&p, .Number);
checkNext(&p, .String); // Height
checkNext(&p, .Number);
checkNext(&p, .String); // Title
checkNext(&p, .String);
checkNext(&p, .String); // Thumbnail
checkNext(&p, .ObjectBegin);
checkNext(&p, .String); // Url
checkNext(&p, .String);
checkNext(&p, .String); // Height
checkNext(&p, .Number);
checkNext(&p, .String); // Width
checkNext(&p, .Number);
checkNext(&p, .ObjectEnd);
checkNext(&p, .String); // Animated
checkNext(&p, .False);
checkNext(&p, .String); // IDs
checkNext(&p, .ArrayBegin);
checkNext(&p, .Number);
checkNext(&p, .Number);
checkNext(&p, .Number);
checkNext(&p, .Number);
checkNext(&p, .ArrayEnd);
checkNext(&p, .ObjectEnd);
checkNext(&p, .ObjectEnd);
try checkNext(&p, .ObjectBegin);
try checkNext(&p, .String); // Image
try checkNext(&p, .ObjectBegin);
try checkNext(&p, .String); // Width
try checkNext(&p, .Number);
try checkNext(&p, .String); // Height
try checkNext(&p, .Number);
try checkNext(&p, .String); // Title
try checkNext(&p, .String);
try checkNext(&p, .String); // Thumbnail
try checkNext(&p, .ObjectBegin);
try checkNext(&p, .String); // Url
try checkNext(&p, .String);
try checkNext(&p, .String); // Height
try checkNext(&p, .Number);
try checkNext(&p, .String); // Width
try checkNext(&p, .Number);
try checkNext(&p, .ObjectEnd);
try checkNext(&p, .String); // Animated
try checkNext(&p, .False);
try checkNext(&p, .String); // IDs
try checkNext(&p, .ArrayBegin);
try checkNext(&p, .Number);
try checkNext(&p, .Number);
try checkNext(&p, .Number);
try checkNext(&p, .Number);
try checkNext(&p, .ArrayEnd);
try checkNext(&p, .ObjectEnd);
try checkNext(&p, .ObjectEnd);
testing.expect((try p.next()) == null);
try testing.expect((try p.next()) == null);
}
test "json.token mismatched close" {
var p = TokenStream.init("[102, 111, 111 }");
checkNext(&p, .ArrayBegin);
checkNext(&p, .Number);
checkNext(&p, .Number);
checkNext(&p, .Number);
testing.expectError(error.UnexpectedClosingBrace, p.next());
try checkNext(&p, .ArrayBegin);
try checkNext(&p, .Number);
try checkNext(&p, .Number);
try checkNext(&p, .Number);
try testing.expectError(error.UnexpectedClosingBrace, p.next());
}
/// Validate a JSON string. This does not limit number precision so a decoder may not necessarily
@ -1223,12 +1223,12 @@ pub fn validate(s: []const u8) bool {
}
test "json.validate" {
testing.expectEqual(true, validate("{}"));
testing.expectEqual(true, validate("[]"));
testing.expectEqual(true, validate("[{[[[[{}]]]]}]"));
testing.expectEqual(false, validate("{]"));
testing.expectEqual(false, validate("[}"));
testing.expectEqual(false, validate("{{{{[]}}}]"));
try testing.expectEqual(true, validate("{}"));
try testing.expectEqual(true, validate("[]"));
try testing.expectEqual(true, validate("[{[[[[{}]]]]}]"));
try testing.expectEqual(false, validate("{]"));
try testing.expectEqual(false, validate("[}"));
try testing.expectEqual(false, validate("{{{{[]}}}]"));
}
const Allocator = std.mem.Allocator;
@ -1326,37 +1326,37 @@ test "Value.jsonStringify" {
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try @as(Value, .Null).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "null");
try testing.expectEqualSlices(u8, fbs.getWritten(), "null");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .Bool = true }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "true");
try testing.expectEqualSlices(u8, fbs.getWritten(), "true");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .Integer = 42 }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "42");
try testing.expectEqualSlices(u8, fbs.getWritten(), "42");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .NumberString = "43" }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "43");
try testing.expectEqualSlices(u8, fbs.getWritten(), "43");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .Float = 42 }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01");
try testing.expectEqualSlices(u8, fbs.getWritten(), "4.2e+01");
}
{
var buffer: [10]u8 = undefined;
var fbs = std.io.fixedBufferStream(&buffer);
try (Value{ .String = "weeee" }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\"");
try testing.expectEqualSlices(u8, fbs.getWritten(), "\"weeee\"");
}
{
var buffer: [10]u8 = undefined;
@ -1369,7 +1369,7 @@ test "Value.jsonStringify" {
try (Value{
.Array = Array.fromOwnedSlice(undefined, &vals),
}).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]");
try testing.expectEqualSlices(u8, fbs.getWritten(), "[1,2,3]");
}
{
var buffer: [10]u8 = undefined;
@ -1378,7 +1378,7 @@ test "Value.jsonStringify" {
defer obj.deinit();
try obj.putNoClobber("a", .{ .String = "b" });
try (Value{ .Object = obj }).jsonStringify(.{}, fbs.writer());
testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}");
try testing.expectEqualSlices(u8, fbs.getWritten(), "{\"a\":\"b\"}");
}
}
@ -1751,17 +1751,17 @@ pub fn parseFree(comptime T: type, value: T, options: ParseOptions) void {
}
test "parse" {
testing.expectEqual(false, try parse(bool, &TokenStream.init("false"), ParseOptions{}));
testing.expectEqual(true, try parse(bool, &TokenStream.init("true"), ParseOptions{}));
testing.expectEqual(@as(u1, 1), try parse(u1, &TokenStream.init("1"), ParseOptions{}));
testing.expectError(error.Overflow, parse(u1, &TokenStream.init("50"), ParseOptions{}));
testing.expectEqual(@as(u64, 42), try parse(u64, &TokenStream.init("42"), ParseOptions{}));
testing.expectEqual(@as(f64, 42), try parse(f64, &TokenStream.init("42.0"), ParseOptions{}));
testing.expectEqual(@as(?bool, null), try parse(?bool, &TokenStream.init("null"), ParseOptions{}));
testing.expectEqual(@as(?bool, true), try parse(?bool, &TokenStream.init("true"), ParseOptions{}));
try testing.expectEqual(false, try parse(bool, &TokenStream.init("false"), ParseOptions{}));
try testing.expectEqual(true, try parse(bool, &TokenStream.init("true"), ParseOptions{}));
try testing.expectEqual(@as(u1, 1), try parse(u1, &TokenStream.init("1"), ParseOptions{}));
try testing.expectError(error.Overflow, parse(u1, &TokenStream.init("50"), ParseOptions{}));
try testing.expectEqual(@as(u64, 42), try parse(u64, &TokenStream.init("42"), ParseOptions{}));
try testing.expectEqual(@as(f64, 42), try parse(f64, &TokenStream.init("42.0"), ParseOptions{}));
try testing.expectEqual(@as(?bool, null), try parse(?bool, &TokenStream.init("null"), ParseOptions{}));
try testing.expectEqual(@as(?bool, true), try parse(?bool, &TokenStream.init("true"), ParseOptions{}));
testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("\"foo\""), ParseOptions{}));
testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("[102, 111, 111]"), ParseOptions{}));
try testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("\"foo\""), ParseOptions{}));
try testing.expectEqual(@as([3]u8, "foo".*), try parse([3]u8, &TokenStream.init("[102, 111, 111]"), ParseOptions{}));
}
test "parse into enum" {
@ -1770,31 +1770,31 @@ test "parse into enum" {
Bar,
@"with\\escape",
};
testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("\"Foo\""), ParseOptions{}));
testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("42"), ParseOptions{}));
testing.expectEqual(@as(T, .@"with\\escape"), try parse(T, &TokenStream.init("\"with\\\\escape\""), ParseOptions{}));
testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("5"), ParseOptions{}));
testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("\"Qux\""), ParseOptions{}));
try testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("\"Foo\""), ParseOptions{}));
try testing.expectEqual(@as(T, .Foo), try parse(T, &TokenStream.init("42"), ParseOptions{}));
try testing.expectEqual(@as(T, .@"with\\escape"), try parse(T, &TokenStream.init("\"with\\\\escape\""), ParseOptions{}));
try testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("5"), ParseOptions{}));
try testing.expectError(error.InvalidEnumTag, parse(T, &TokenStream.init("\"Qux\""), ParseOptions{}));
}
test "parse into that allocates a slice" {
testing.expectError(error.AllocatorRequired, parse([]u8, &TokenStream.init("\"foo\""), ParseOptions{}));
try testing.expectError(error.AllocatorRequired, parse([]u8, &TokenStream.init("\"foo\""), ParseOptions{}));
const options = ParseOptions{ .allocator = testing.allocator };
{
const r = try parse([]u8, &TokenStream.init("\"foo\""), options);
defer parseFree([]u8, r, options);
testing.expectEqualSlices(u8, "foo", r);
try testing.expectEqualSlices(u8, "foo", r);
}
{
const r = try parse([]u8, &TokenStream.init("[102, 111, 111]"), options);
defer parseFree([]u8, r, options);
testing.expectEqualSlices(u8, "foo", r);
try testing.expectEqualSlices(u8, "foo", r);
}
{
const r = try parse([]u8, &TokenStream.init("\"with\\\\escape\""), options);
defer parseFree([]u8, r, options);
testing.expectEqualSlices(u8, "with\\escape", r);
try testing.expectEqualSlices(u8, "with\\escape", r);
}
}
@ -1805,7 +1805,7 @@ test "parse into tagged union" {
float: f64,
string: []const u8,
};
testing.expectEqual(T{ .float = 1.5 }, try parse(T, &TokenStream.init("1.5"), ParseOptions{}));
try testing.expectEqual(T{ .float = 1.5 }, try parse(T, &TokenStream.init("1.5"), ParseOptions{}));
}
{ // failing allocations should be bubbled up instantly without trying next member
@ -1816,7 +1816,7 @@ test "parse into tagged union" {
string: []const u8,
array: [3]u8,
};
testing.expectError(error.OutOfMemory, parse(T, &TokenStream.init("[1,2,3]"), options));
try testing.expectError(error.OutOfMemory, parse(T, &TokenStream.init("[1,2,3]"), options));
}
{
@ -1825,7 +1825,7 @@ test "parse into tagged union" {
x: u8,
y: u8,
};
testing.expectEqual(T{ .x = 42 }, try parse(T, &TokenStream.init("42"), ParseOptions{}));
try testing.expectEqual(T{ .x = 42 }, try parse(T, &TokenStream.init("42"), ParseOptions{}));
}
{ // needs to back out when first union member doesn't match
@ -1833,7 +1833,7 @@ test "parse into tagged union" {
A: struct { x: u32 },
B: struct { y: u32 },
};
testing.expectEqual(T{ .B = .{ .y = 42 } }, try parse(T, &TokenStream.init("{\"y\":42}"), ParseOptions{}));
try testing.expectEqual(T{ .B = .{ .y = 42 } }, try parse(T, &TokenStream.init("{\"y\":42}"), ParseOptions{}));
}
}
@ -1843,7 +1843,7 @@ test "parse union bubbles up AllocatorRequired" {
string: []const u8,
int: i32,
};
testing.expectError(error.AllocatorRequired, parse(T, &TokenStream.init("42"), ParseOptions{}));
try testing.expectError(error.AllocatorRequired, parse(T, &TokenStream.init("42"), ParseOptions{}));
}
{ // string member not first in union (and matching)
@ -1852,7 +1852,7 @@ test "parse union bubbles up AllocatorRequired" {
float: f64,
string: []const u8,
};
testing.expectError(error.AllocatorRequired, parse(T, &TokenStream.init("\"foo\""), ParseOptions{}));
try testing.expectError(error.AllocatorRequired, parse(T, &TokenStream.init("\"foo\""), ParseOptions{}));
}
}
@ -1866,11 +1866,11 @@ test "parseFree descends into tagged union" {
};
// use a string with unicode escape so we know result can't be a reference to global constant
const r = try parse(T, &TokenStream.init("\"with\\u0105unicode\""), options);
testing.expectEqual(std.meta.Tag(T).string, @as(std.meta.Tag(T), r));
testing.expectEqualSlices(u8, "withąunicode", r.string);
testing.expectEqual(@as(usize, 0), fail_alloc.deallocations);
try testing.expectEqual(std.meta.Tag(T).string, @as(std.meta.Tag(T), r));
try testing.expectEqualSlices(u8, "withąunicode", r.string);
try testing.expectEqual(@as(usize, 0), fail_alloc.deallocations);
parseFree(T, r, options);
testing.expectEqual(@as(usize, 1), fail_alloc.deallocations);
try testing.expectEqual(@as(usize, 1), fail_alloc.deallocations);
}
test "parse with comptime field" {
@ -1879,7 +1879,7 @@ test "parse with comptime field" {
comptime a: i32 = 0,
b: bool,
};
testing.expectEqual(T{ .a = 0, .b = true }, try parse(T, &TokenStream.init(
try testing.expectEqual(T{ .a = 0, .b = true }, try parse(T, &TokenStream.init(
\\{
\\ "a": 0,
\\ "b": true
@ -1912,7 +1912,7 @@ test "parse with comptime field" {
test "parse into struct with no fields" {
const T = struct {};
testing.expectEqual(T{}, try parse(T, &TokenStream.init("{}"), ParseOptions{}));
try testing.expectEqual(T{}, try parse(T, &TokenStream.init("{}"), ParseOptions{}));
}
test "parse into struct with misc fields" {
@ -1968,24 +1968,24 @@ test "parse into struct with misc fields" {
\\}
), options);
defer parseFree(T, r, options);
testing.expectEqual(@as(i64, 420), r.int);
testing.expectEqual(@as(f64, 3.14), r.float);
testing.expectEqual(true, r.@"with\\escape");
testing.expectEqual(false, r.@"withąunicode😂");
testing.expectEqualSlices(u8, "zig", r.language);
testing.expectEqual(@as(?bool, null), r.optional);
testing.expectEqual(@as(i32, 42), r.default_field);
testing.expectEqual(@as(f64, 66.6), r.static_array[0]);
testing.expectEqual(@as(f64, 420.420), r.static_array[1]);
testing.expectEqual(@as(f64, 69.69), r.static_array[2]);
testing.expectEqual(@as(usize, 3), r.dynamic_array.len);
testing.expectEqual(@as(f64, 66.6), r.dynamic_array[0]);
testing.expectEqual(@as(f64, 420.420), r.dynamic_array[1]);
testing.expectEqual(@as(f64, 69.69), r.dynamic_array[2]);
testing.expectEqualSlices(u8, r.complex.nested, "zig");
testing.expectEqualSlices(u8, "zig", r.veryComplex[0].foo);
testing.expectEqualSlices(u8, "rocks", r.veryComplex[1].foo);
testing.expectEqual(T.Union{ .float = 100000 }, r.a_union);
try testing.expectEqual(@as(i64, 420), r.int);
try testing.expectEqual(@as(f64, 3.14), r.float);
try testing.expectEqual(true, r.@"with\\escape");
try testing.expectEqual(false, r.@"withąunicode😂");
try testing.expectEqualSlices(u8, "zig", r.language);
try testing.expectEqual(@as(?bool, null), r.optional);
try testing.expectEqual(@as(i32, 42), r.default_field);
try testing.expectEqual(@as(f64, 66.6), r.static_array[0]);
try testing.expectEqual(@as(f64, 420.420), r.static_array[1]);
try testing.expectEqual(@as(f64, 69.69), r.static_array[2]);
try testing.expectEqual(@as(usize, 3), r.dynamic_array.len);
try testing.expectEqual(@as(f64, 66.6), r.dynamic_array[0]);
try testing.expectEqual(@as(f64, 420.420), r.dynamic_array[1]);
try testing.expectEqual(@as(f64, 69.69), r.dynamic_array[2]);
try testing.expectEqualSlices(u8, r.complex.nested, "zig");
try testing.expectEqualSlices(u8, "zig", r.veryComplex[0].foo);
try testing.expectEqualSlices(u8, "rocks", r.veryComplex[1].foo);
try testing.expectEqual(T.Union{ .float = 100000 }, r.a_union);
}
/// A non-stream JSON parser which constructs a tree of Value's.
@ -2320,28 +2320,28 @@ test "json.parser.dynamic" {
var image = root.Object.get("Image").?;
const width = image.Object.get("Width").?;
testing.expect(width.Integer == 800);
try testing.expect(width.Integer == 800);
const height = image.Object.get("Height").?;
testing.expect(height.Integer == 600);
try testing.expect(height.Integer == 600);
const title = image.Object.get("Title").?;
testing.expect(mem.eql(u8, title.String, "View from 15th Floor"));
try testing.expect(mem.eql(u8, title.String, "View from 15th Floor"));
const animated = image.Object.get("Animated").?;
testing.expect(animated.Bool == false);
try testing.expect(animated.Bool == false);
const array_of_object = image.Object.get("ArrayOfObject").?;
testing.expect(array_of_object.Array.items.len == 1);
try testing.expect(array_of_object.Array.items.len == 1);
const obj0 = array_of_object.Array.items[0].Object.get("n").?;
testing.expect(mem.eql(u8, obj0.String, "m"));
try testing.expect(mem.eql(u8, obj0.String, "m"));
const double = image.Object.get("double").?;
testing.expect(double.Float == 1.3412);
try testing.expect(double.Float == 1.3412);
const large_int = image.Object.get("LargeInt").?;
testing.expect(mem.eql(u8, large_int.NumberString, "18446744073709551615"));
try testing.expect(mem.eql(u8, large_int.NumberString, "18446744073709551615"));
}
test "import more json tests" {
@ -2388,12 +2388,12 @@ test "write json then parse it" {
var tree = try parser.parse(fixed_buffer_stream.getWritten());
defer tree.deinit();
testing.expect(tree.root.Object.get("f").?.Bool == false);
testing.expect(tree.root.Object.get("t").?.Bool == true);
testing.expect(tree.root.Object.get("int").?.Integer == 1234);
testing.expect(tree.root.Object.get("array").?.Array.items[0].Null == {});
testing.expect(tree.root.Object.get("array").?.Array.items[1].Float == 12.34);
testing.expect(mem.eql(u8, tree.root.Object.get("str").?.String, "hello"));
try testing.expect(tree.root.Object.get("f").?.Bool == false);
try testing.expect(tree.root.Object.get("t").?.Bool == true);
try testing.expect(tree.root.Object.get("int").?.Integer == 1234);
try testing.expect(tree.root.Object.get("array").?.Array.items[0].Null == {});
try testing.expect(tree.root.Object.get("array").?.Array.items[1].Float == 12.34);
try testing.expect(mem.eql(u8, tree.root.Object.get("str").?.String, "hello"));
}
fn test_parse(arena_allocator: *std.mem.Allocator, json_str: []const u8) !Value {
@ -2404,7 +2404,7 @@ fn test_parse(arena_allocator: *std.mem.Allocator, json_str: []const u8) !Value
test "parsing empty string gives appropriate error" {
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
testing.expectError(error.UnexpectedEndOfJson, test_parse(&arena_allocator.allocator, ""));
try testing.expectError(error.UnexpectedEndOfJson, test_parse(&arena_allocator.allocator, ""));
}
test "integer after float has proper type" {
@ -2416,7 +2416,7 @@ test "integer after float has proper type" {
\\ "ints": [1, 2, 3]
\\}
);
std.testing.expect(json.Object.get("ints").?.Array.items[0] == .Integer);
try std.testing.expect(json.Object.get("ints").?.Array.items[0] == .Integer);
}
test "escaped characters" {
@ -2439,16 +2439,16 @@ test "escaped characters" {
const obj = (try test_parse(&arena_allocator.allocator, input)).Object;
testing.expectEqualSlices(u8, obj.get("backslash").?.String, "\\");
testing.expectEqualSlices(u8, obj.get("forwardslash").?.String, "/");
testing.expectEqualSlices(u8, obj.get("newline").?.String, "\n");
testing.expectEqualSlices(u8, obj.get("carriagereturn").?.String, "\r");
testing.expectEqualSlices(u8, obj.get("tab").?.String, "\t");
testing.expectEqualSlices(u8, obj.get("formfeed").?.String, "\x0C");
testing.expectEqualSlices(u8, obj.get("backspace").?.String, "\x08");
testing.expectEqualSlices(u8, obj.get("doublequote").?.String, "\"");
testing.expectEqualSlices(u8, obj.get("unicode").?.String, "ą");
testing.expectEqualSlices(u8, obj.get("surrogatepair").?.String, "😂");
try testing.expectEqualSlices(u8, obj.get("backslash").?.String, "\\");
try testing.expectEqualSlices(u8, obj.get("forwardslash").?.String, "/");
try testing.expectEqualSlices(u8, obj.get("newline").?.String, "\n");
try testing.expectEqualSlices(u8, obj.get("carriagereturn").?.String, "\r");
try testing.expectEqualSlices(u8, obj.get("tab").?.String, "\t");
try testing.expectEqualSlices(u8, obj.get("formfeed").?.String, "\x0C");
try testing.expectEqualSlices(u8, obj.get("backspace").?.String, "\x08");
try testing.expectEqualSlices(u8, obj.get("doublequote").?.String, "\"");
try testing.expectEqualSlices(u8, obj.get("unicode").?.String, "ą");
try testing.expectEqualSlices(u8, obj.get("surrogatepair").?.String, "😂");
}
test "string copy option" {
@ -2471,7 +2471,7 @@ test "string copy option" {
const obj_copy = tree_copy.root.Object;
for ([_][]const u8{ "noescape", "simple", "unicode", "surrogatepair" }) |field_name| {
testing.expectEqualSlices(u8, obj_nocopy.get(field_name).?.String, obj_copy.get(field_name).?.String);
try testing.expectEqualSlices(u8, obj_nocopy.get(field_name).?.String, obj_copy.get(field_name).?.String);
}
const nocopy_addr = &obj_nocopy.get("noescape").?.String[0];
@ -2479,12 +2479,12 @@ test "string copy option" {
var found_nocopy = false;
for (input) |_, index| {
testing.expect(copy_addr != &input[index]);
try testing.expect(copy_addr != &input[index]);
if (nocopy_addr == &input[index]) {
found_nocopy = true;
}
}
testing.expect(found_nocopy);
try testing.expect(found_nocopy);
}
pub const StringifyOptions = struct {

File diff suppressed because it is too large Load Diff

View File

@ -288,7 +288,7 @@ test "json write stream" {
\\ "float": 3.5e+00
\\}
;
std.testing.expect(std.mem.eql(u8, expected, result));
try std.testing.expect(std.mem.eql(u8, expected, result));
}
fn getJsonObject(allocator: *std.mem.Allocator) !std.json.Value {

View File

@ -152,22 +152,22 @@ test "writeUnsignedFixed" {
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 0);
testing.expect((try test_read_uleb128(u64, &buf)) == 0);
try testing.expect((try test_read_uleb128(u64, &buf)) == 0);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 1);
testing.expect((try test_read_uleb128(u64, &buf)) == 1);
try testing.expect((try test_read_uleb128(u64, &buf)) == 1);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 1000);
testing.expect((try test_read_uleb128(u64, &buf)) == 1000);
try testing.expect((try test_read_uleb128(u64, &buf)) == 1000);
}
{
var buf: [4]u8 = undefined;
writeUnsignedFixed(4, &buf, 10000000);
testing.expect((try test_read_uleb128(u64, &buf)) == 10000000);
try testing.expect((try test_read_uleb128(u64, &buf)) == 10000000);
}
}
@ -212,44 +212,44 @@ fn test_read_uleb128_seq(comptime T: type, comptime N: usize, encoded: []const u
test "deserialize signed LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_ileb128(i64, "\x80"));
try testing.expectError(error.EndOfStream, test_read_stream_ileb128(i64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_ileb128(i8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_ileb128(i8, "\xff\x7e"));
try testing.expectError(error.Overflow, test_read_ileb128(i8, "\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_ileb128(i16, "\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_ileb128(i32, "\x80\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_ileb128(i8, "\xff\x7e"));
// Decode SLEB128
testing.expect((try test_read_ileb128(i64, "\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x01")) == 1);
testing.expect((try test_read_ileb128(i64, "\x3f")) == 63);
testing.expect((try test_read_ileb128(i64, "\x40")) == -64);
testing.expect((try test_read_ileb128(i64, "\x41")) == -63);
testing.expect((try test_read_ileb128(i64, "\x7f")) == -1);
testing.expect((try test_read_ileb128(i64, "\x80\x01")) == 128);
testing.expect((try test_read_ileb128(i64, "\x81\x01")) == 129);
testing.expect((try test_read_ileb128(i64, "\xff\x7e")) == -129);
testing.expect((try test_read_ileb128(i64, "\x80\x7f")) == -128);
testing.expect((try test_read_ileb128(i64, "\x81\x7f")) == -127);
testing.expect((try test_read_ileb128(i64, "\xc0\x00")) == 64);
testing.expect((try test_read_ileb128(i64, "\xc7\x9f\x7f")) == -12345);
testing.expect((try test_read_ileb128(i8, "\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i16, "\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
testing.expect((try test_read_ileb128(i32, "\x80\x80\x80\x80\x08")) == -0x80000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == @bitCast(i64, @intCast(u64, 0x8000000000000000)));
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
try testing.expect((try test_read_ileb128(i64, "\x00")) == 0);
try testing.expect((try test_read_ileb128(i64, "\x01")) == 1);
try testing.expect((try test_read_ileb128(i64, "\x3f")) == 63);
try testing.expect((try test_read_ileb128(i64, "\x40")) == -64);
try testing.expect((try test_read_ileb128(i64, "\x41")) == -63);
try testing.expect((try test_read_ileb128(i64, "\x7f")) == -1);
try testing.expect((try test_read_ileb128(i64, "\x80\x01")) == 128);
try testing.expect((try test_read_ileb128(i64, "\x81\x01")) == 129);
try testing.expect((try test_read_ileb128(i64, "\xff\x7e")) == -129);
try testing.expect((try test_read_ileb128(i64, "\x80\x7f")) == -128);
try testing.expect((try test_read_ileb128(i64, "\x81\x7f")) == -127);
try testing.expect((try test_read_ileb128(i64, "\xc0\x00")) == 64);
try testing.expect((try test_read_ileb128(i64, "\xc7\x9f\x7f")) == -12345);
try testing.expect((try test_read_ileb128(i8, "\xff\x7f")) == -1);
try testing.expect((try test_read_ileb128(i16, "\xff\xff\x7f")) == -1);
try testing.expect((try test_read_ileb128(i32, "\xff\xff\xff\xff\x7f")) == -1);
try testing.expect((try test_read_ileb128(i32, "\x80\x80\x80\x80\x08")) == -0x80000000);
try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == @bitCast(i64, @intCast(u64, 0x8000000000000000)));
try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x40")) == -0x4000000000000000);
try testing.expect((try test_read_ileb128(i64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7f")) == -0x8000000000000000);
// Decode unnormalized SLEB128 with extra padding bytes.
testing.expect((try test_read_ileb128(i64, "\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_ileb128(i64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_ileb128(i64, "\x80\x81\x80\x00")) == 0x80);
try testing.expect((try test_read_ileb128(i64, "\x80\x00")) == 0);
try testing.expect((try test_read_ileb128(i64, "\x80\x80\x00")) == 0);
try testing.expect((try test_read_ileb128(i64, "\xff\x00")) == 0x7f);
try testing.expect((try test_read_ileb128(i64, "\xff\x80\x00")) == 0x7f);
try testing.expect((try test_read_ileb128(i64, "\x80\x81\x00")) == 0x80);
try testing.expect((try test_read_ileb128(i64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of SLEB128 values
try test_read_ileb128_seq(i64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
@ -257,39 +257,39 @@ test "deserialize signed LEB128" {
test "deserialize unsigned LEB128" {
// Truncated
testing.expectError(error.EndOfStream, test_read_stream_uleb128(u64, "\x80"));
try testing.expectError(error.EndOfStream, test_read_stream_uleb128(u64, "\x80"));
// Overflow
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x02"));
testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x84"));
testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x90"));
testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x40"));
testing.expectError(error.Overflow, test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x02"));
try testing.expectError(error.Overflow, test_read_uleb128(u8, "\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x84"));
try testing.expectError(error.Overflow, test_read_uleb128(u16, "\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x90"));
try testing.expectError(error.Overflow, test_read_uleb128(u32, "\x80\x80\x80\x80\x40"));
try testing.expectError(error.Overflow, test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x40"));
// Decode ULEB128
testing.expect((try test_read_uleb128(u64, "\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x01")) == 1);
testing.expect((try test_read_uleb128(u64, "\x3f")) == 63);
testing.expect((try test_read_uleb128(u64, "\x40")) == 64);
testing.expect((try test_read_uleb128(u64, "\x7f")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x01")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x81\x01")) == 0x81);
testing.expect((try test_read_uleb128(u64, "\x90\x01")) == 0x90);
testing.expect((try test_read_uleb128(u64, "\xff\x01")) == 0xff);
testing.expect((try test_read_uleb128(u64, "\x80\x02")) == 0x100);
testing.expect((try test_read_uleb128(u64, "\x81\x02")) == 0x101);
testing.expect((try test_read_uleb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
try testing.expect((try test_read_uleb128(u64, "\x00")) == 0);
try testing.expect((try test_read_uleb128(u64, "\x01")) == 1);
try testing.expect((try test_read_uleb128(u64, "\x3f")) == 63);
try testing.expect((try test_read_uleb128(u64, "\x40")) == 64);
try testing.expect((try test_read_uleb128(u64, "\x7f")) == 0x7f);
try testing.expect((try test_read_uleb128(u64, "\x80\x01")) == 0x80);
try testing.expect((try test_read_uleb128(u64, "\x81\x01")) == 0x81);
try testing.expect((try test_read_uleb128(u64, "\x90\x01")) == 0x90);
try testing.expect((try test_read_uleb128(u64, "\xff\x01")) == 0xff);
try testing.expect((try test_read_uleb128(u64, "\x80\x02")) == 0x100);
try testing.expect((try test_read_uleb128(u64, "\x81\x02")) == 0x101);
try testing.expect((try test_read_uleb128(u64, "\x80\xc1\x80\x80\x10")) == 4294975616);
try testing.expect((try test_read_uleb128(u64, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01")) == 0x8000000000000000);
// Decode ULEB128 with extra padding bytes
testing.expect((try test_read_uleb128(u64, "\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\x80\x80\x00")) == 0);
testing.expect((try test_read_uleb128(u64, "\xff\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\xff\x80\x00")) == 0x7f);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x00")) == 0x80);
testing.expect((try test_read_uleb128(u64, "\x80\x81\x80\x00")) == 0x80);
try testing.expect((try test_read_uleb128(u64, "\x80\x00")) == 0);
try testing.expect((try test_read_uleb128(u64, "\x80\x80\x00")) == 0);
try testing.expect((try test_read_uleb128(u64, "\xff\x00")) == 0x7f);
try testing.expect((try test_read_uleb128(u64, "\xff\x80\x00")) == 0x7f);
try testing.expect((try test_read_uleb128(u64, "\x80\x81\x00")) == 0x80);
try testing.expect((try test_read_uleb128(u64, "\x80\x81\x80\x00")) == 0x80);
// Decode sequence of ULEB128 values
try test_read_uleb128_seq(u64, 4, "\x81\x01\x3f\x80\x7f\x80\x80\x80\x00");
@ -326,19 +326,19 @@ fn test_write_leb128(value: anytype) !void {
// stream write
try writeStream(fbs.writer(), value);
const w1_pos = fbs.pos;
testing.expect(w1_pos == bytes_needed);
try testing.expect(w1_pos == bytes_needed);
// stream read
fbs.pos = 0;
const sr = try readStream(T, fbs.reader());
testing.expect(fbs.pos == w1_pos);
testing.expect(sr == value);
try testing.expect(fbs.pos == w1_pos);
try testing.expect(sr == value);
// bigger type stream read
fbs.pos = 0;
const bsr = try readStream(B, fbs.reader());
testing.expect(fbs.pos == w1_pos);
testing.expect(bsr == value);
try testing.expect(fbs.pos == w1_pos);
try testing.expect(bsr == value);
}
test "serialize unsigned LEB128" {

Some files were not shown because too many files have changed in this diff Show More