std: promote tests to doctests

Now these show up as "example usage" in generated documentation.
This commit is contained in:
Andrew Kelley 2024-03-13 15:56:09 -07:00
parent d029e0e972
commit e5a95c6af1
26 changed files with 313 additions and 290 deletions

View file

@ -147,7 +147,7 @@ pub fn isWhitespace(c: u8) bool {
/// See also: `isWhitespace` /// See also: `isWhitespace`
pub const whitespace = [_]u8{ ' ', '\t', '\n', '\r', control_code.vt, control_code.ff }; pub const whitespace = [_]u8{ ' ', '\t', '\n', '\r', control_code.vt, control_code.ff };
test "whitespace" { test whitespace {
for (whitespace) |char| try std.testing.expect(isWhitespace(char)); for (whitespace) |char| try std.testing.expect(isWhitespace(char));
var i: u8 = 0; var i: u8 = 0;
@ -278,7 +278,7 @@ pub fn lowerString(output: []u8, ascii_string: []const u8) []u8 {
return output[0..ascii_string.len]; return output[0..ascii_string.len];
} }
test "lowerString" { test lowerString {
var buf: [1024]u8 = undefined; var buf: [1024]u8 = undefined;
const result = lowerString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!"); const result = lowerString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result); try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
@ -291,7 +291,7 @@ pub fn allocLowerString(allocator: std.mem.Allocator, ascii_string: []const u8)
return lowerString(result, ascii_string); return lowerString(result, ascii_string);
} }
test "allocLowerString" { test allocLowerString {
const result = try allocLowerString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!"); const result = try allocLowerString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result); defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result); try std.testing.expectEqualStrings("abcdefghijklmnopqrst0234+💩!", result);
@ -307,7 +307,7 @@ pub fn upperString(output: []u8, ascii_string: []const u8) []u8 {
return output[0..ascii_string.len]; return output[0..ascii_string.len];
} }
test "upperString" { test upperString {
var buf: [1024]u8 = undefined; var buf: [1024]u8 = undefined;
const result = upperString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!"); const result = upperString(&buf, "aBcDeFgHiJkLmNOPqrst0234+💩!");
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result); try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
@ -320,7 +320,7 @@ pub fn allocUpperString(allocator: std.mem.Allocator, ascii_string: []const u8)
return upperString(result, ascii_string); return upperString(result, ascii_string);
} }
test "allocUpperString" { test allocUpperString {
const result = try allocUpperString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!"); const result = try allocUpperString(std.testing.allocator, "aBcDeFgHiJkLmNOPqrst0234+💩!");
defer std.testing.allocator.free(result); defer std.testing.allocator.free(result);
try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result); try std.testing.expectEqualStrings("ABCDEFGHIJKLMNOPQRST0234+💩!", result);
@ -335,7 +335,7 @@ pub fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {
return true; return true;
} }
test "eqlIgnoreCase" { test eqlIgnoreCase {
try std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!")); try std.testing.expect(eqlIgnoreCase("HEl💩Lo!", "hel💩lo!"));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! ")); try std.testing.expect(!eqlIgnoreCase("hElLo!", "hello! "));
try std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!")); try std.testing.expect(!eqlIgnoreCase("hElLo!", "helro!"));
@ -345,7 +345,7 @@ pub fn startsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[0..needle.len], needle); return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[0..needle.len], needle);
} }
test "startsWithIgnoreCase" { test startsWithIgnoreCase {
try std.testing.expect(startsWithIgnoreCase("boB", "Bo")); try std.testing.expect(startsWithIgnoreCase("boB", "Bo"));
try std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack")); try std.testing.expect(!startsWithIgnoreCase("Needle in hAyStAcK", "haystack"));
} }
@ -354,7 +354,7 @@ pub fn endsWithIgnoreCase(haystack: []const u8, needle: []const u8) bool {
return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[haystack.len - needle.len ..], needle); return if (needle.len > haystack.len) false else eqlIgnoreCase(haystack[haystack.len - needle.len ..], needle);
} }
test "endsWithIgnoreCase" { test endsWithIgnoreCase {
try std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack")); try std.testing.expect(endsWithIgnoreCase("Needle in HaYsTaCk", "haystack"));
try std.testing.expect(!endsWithIgnoreCase("BoB", "Bo")); try std.testing.expect(!endsWithIgnoreCase("BoB", "Bo"));
} }
@ -409,7 +409,7 @@ fn boyerMooreHorspoolPreprocessIgnoreCase(pattern: []const u8, table: *[256]usiz
} }
} }
test "indexOfIgnoreCase" { test indexOfIgnoreCase {
try std.testing.expect(indexOfIgnoreCase("one Two Three Four", "foUr").? == 14); 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("one two three FouR", "gOur") == null);
try std.testing.expect(indexOfIgnoreCase("foO", "Foo").? == 0); try std.testing.expect(indexOfIgnoreCase("foO", "Foo").? == 0);

View file

@ -1648,7 +1648,7 @@ fn testStaticBitSet(comptime Set: type) !void {
try testPureBitSet(Set); try testPureBitSet(Set);
} }
test "IntegerBitSet" { test IntegerBitSet {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest;
try testStaticBitSet(IntegerBitSet(0)); try testStaticBitSet(IntegerBitSet(0));
@ -1661,7 +1661,7 @@ test "IntegerBitSet" {
try testStaticBitSet(IntegerBitSet(127)); try testStaticBitSet(IntegerBitSet(127));
} }
test "ArrayBitSet" { test ArrayBitSet {
inline for (.{ 0, 1, 2, 31, 32, 33, 63, 64, 65, 254, 500, 3000 }) |size| { inline for (.{ 0, 1, 2, 31, 32, 33, 63, 64, 65, 254, 500, 3000 }) |size| {
try testStaticBitSet(ArrayBitSet(u8, size)); try testStaticBitSet(ArrayBitSet(u8, size));
try testStaticBitSet(ArrayBitSet(u16, size)); try testStaticBitSet(ArrayBitSet(u16, size));
@ -1671,7 +1671,7 @@ test "ArrayBitSet" {
} }
} }
test "DynamicBitSetUnmanaged" { test DynamicBitSetUnmanaged {
const allocator = std.testing.allocator; const allocator = std.testing.allocator;
var a = try DynamicBitSetUnmanaged.initEmpty(allocator, 300); var a = try DynamicBitSetUnmanaged.initEmpty(allocator, 300);
try testing.expectEqual(@as(usize, 0), a.count()); try testing.expectEqual(@as(usize, 0), a.count());
@ -1724,7 +1724,7 @@ test "DynamicBitSetUnmanaged" {
} }
} }
test "DynamicBitSet" { test DynamicBitSet {
const allocator = std.testing.allocator; const allocator = std.testing.allocator;
var a = try DynamicBitSet.initEmpty(allocator, 300); var a = try DynamicBitSet.initEmpty(allocator, 300);
try testing.expectEqual(@as(usize, 0), a.count()); try testing.expectEqual(@as(usize, 0), a.count());
@ -1765,7 +1765,7 @@ test "DynamicBitSet" {
} }
} }
test "StaticBitSet" { test StaticBitSet {
try testing.expectEqual(IntegerBitSet(0), StaticBitSet(0)); try testing.expectEqual(IntegerBitSet(0), StaticBitSet(0));
try testing.expectEqual(IntegerBitSet(5), StaticBitSet(5)); try testing.expectEqual(IntegerBitSet(5), StaticBitSet(5));
try testing.expectEqual(IntegerBitSet(@bitSizeOf(usize)), StaticBitSet(@bitSizeOf(usize))); try testing.expectEqual(IntegerBitSet(@bitSizeOf(usize)), StaticBitSet(@bitSizeOf(usize)));

View file

@ -287,7 +287,7 @@ pub fn BoundedArrayAligned(
}; };
} }
test "BoundedArray" { test BoundedArray {
var a = try BoundedArray(u8, 64).init(32); var a = try BoundedArray(u8, 64).init(32);
try testing.expectEqual(a.capacity(), 64); try testing.expectEqual(a.capacity(), 64);

View file

@ -1230,7 +1230,7 @@ fn windowsCreateProcessSupportsExtension(ext: []const u16) ?CreateProcessSupport
return null; return null;
} }
test "windowsCreateProcessSupportsExtension" { test windowsCreateProcessSupportsExtension {
try std.testing.expectEqual(CreateProcessSupportedExtension.exe, windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e' }).?); try std.testing.expectEqual(CreateProcessSupportedExtension.exe, windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e' }).?);
try std.testing.expect(windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e', 'c' }) == null); try std.testing.expect(windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e', 'c' }) == null);
} }
@ -1321,7 +1321,7 @@ pub fn argvToCommandLineWindows(
return try unicode.wtf8ToWtf16LeAllocZ(allocator, buf.items); return try unicode.wtf8ToWtf16LeAllocZ(allocator, buf.items);
} }
test "argvToCommandLineWindows" { test argvToCommandLineWindows {
const t = testArgvToCommandLineWindows; const t = testArgvToCommandLineWindows;
try t(&.{ try t(&.{
@ -1555,7 +1555,7 @@ pub fn createNullDelimitedEnvMap(arena: mem.Allocator, env_map: *const EnvMap) !
return envp_buf; return envp_buf;
} }
test "createNullDelimitedEnvMap" { test createNullDelimitedEnvMap {
const testing = std.testing; const testing = std.testing;
const allocator = testing.allocator; const allocator = testing.allocator;
var envmap = EnvMap.init(allocator); var envmap = EnvMap.init(allocator);

View file

@ -138,7 +138,7 @@ pub inline fn secureZero(comptime T: type, s: []T) void {
@memset(@as([]volatile T, s), 0); @memset(@as([]volatile T, s), 0);
} }
test "timingSafeEql" { test timingSafeEql {
var a: [100]u8 = undefined; var a: [100]u8 = undefined;
var b: [100]u8 = undefined; var b: [100]u8 = undefined;
random.bytes(a[0..]); random.bytes(a[0..]);
@ -162,7 +162,7 @@ test "timingSafeEql (vectors)" {
try testing.expect(timingSafeEql(@Vector(100, u8), v1, v3)); try testing.expect(timingSafeEql(@Vector(100, u8), v1, v3));
} }
test "timingSafeCompare" { test timingSafeCompare {
var a = [_]u8{10} ** 32; var a = [_]u8{10} ** 32;
var b = [_]u8{10} ** 32; var b = [_]u8{10} ** 32;
try testing.expectEqual(timingSafeCompare(u8, &a, &b, .big), .eq); try testing.expectEqual(timingSafeCompare(u8, &a, &b, .big), .eq);
@ -195,7 +195,7 @@ test "timingSafe{Add,Sub}" {
} }
} }
test "secureZero" { test secureZero {
var a = [_]u8{0xfe} ** 8; var a = [_]u8{0xfe} ** 8;
var b = [_]u8{0xfe} ** 8; var b = [_]u8{0xfe} ** 8;

View file

@ -908,7 +908,7 @@ fn machoSearchSymbols(symbols: []const MachoSymbol, address: usize) ?*const Mach
return null; return null;
} }
test "machoSearchSymbols" { test machoSearchSymbols {
const symbols = [_]MachoSymbol{ const symbols = [_]MachoSymbol{
.{ .addr = 100, .strx = undefined, .size = undefined, .ofile = undefined }, .{ .addr = 100, .strx = undefined, .size = undefined, .ofile = undefined },
.{ .addr = 200, .strx = undefined, .size = undefined, .ofile = undefined }, .{ .addr = 200, .strx = undefined, .size = undefined, .ofile = undefined },
@ -1502,7 +1502,7 @@ fn printLineFromFileAnyOs(out_stream: anytype, line_info: LineInfo) !void {
} }
} }
test "printLineFromFileAnyOs" { test printLineFromFileAnyOs {
var output = std.ArrayList(u8).init(std.testing.allocator); var output = std.ArrayList(u8).init(std.testing.allocator);
defer output.deinit(); defer output.deinit();
const output_stream = output.writer(); const output_stream = output.writer();

View file

@ -507,7 +507,7 @@ test "LinearFifo(u8, .Dynamic)" {
} }
} }
test "LinearFifo" { test LinearFifo {
inline for ([_]type{ u1, u8, u16, u64 }) |T| { inline for ([_]type{ u1, u8, u16, u64 }) |T| {
inline for ([_]LinearFifoBufferType{ LinearFifoBufferType{ .Static = 32 }, .Slice, .Dynamic }) |bt| { inline for ([_]LinearFifoBufferType{ LinearFifoBufferType{ .Static = 32 }, .Slice, .Dynamic }) |bt| {
const FifoType = LinearFifo(T, bt); const FifoType = LinearFifo(T, bt);

View file

@ -1300,7 +1300,7 @@ pub fn fmtDuration(ns: u64) Formatter(formatDuration) {
return .{ .data = data }; return .{ .data = data };
} }
test "fmtDuration" { test fmtDuration {
var buf: [24]u8 = undefined; var buf: [24]u8 = undefined;
inline for (.{ inline for (.{
.{ .s = "0ns", .d = 0 }, .{ .s = "0ns", .d = 0 },
@ -1364,7 +1364,7 @@ pub fn fmtDurationSigned(ns: i64) Formatter(formatDurationSigned) {
return .{ .data = ns }; return .{ .data = ns };
} }
test "fmtDurationSigned" { test fmtDurationSigned {
var buf: [24]u8 = undefined; var buf: [24]u8 = undefined;
inline for (.{ inline for (.{
.{ .s = "0ns", .d = 0 }, .{ .s = "0ns", .d = 0 },
@ -1494,7 +1494,7 @@ pub fn parseInt(comptime T: type, buf: []const u8, base: u8) ParseIntError!T {
return parseWithSign(T, buf, base, .pos); return parseWithSign(T, buf, base, .pos);
} }
test "parseInt" { test parseInt {
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(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.expect((try parseInt(u32, "+10", 10)) == 10);
@ -1636,7 +1636,7 @@ pub fn parseUnsigned(comptime T: type, buf: []const u8, base: u8) ParseIntError!
return parseWithSign(T, buf, base, .pos); return parseWithSign(T, buf, base, .pos);
} }
test "parseUnsigned" { test parseUnsigned {
try std.testing.expect((try parseUnsigned(u16, "050124", 10)) == 50124); 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, "65535", 10)) == 65535);
try std.testing.expect((try parseUnsigned(u16, "65_535", 10)) == 65535); try std.testing.expect((try parseUnsigned(u16, "65_535", 10)) == 65535);
@ -1710,7 +1710,7 @@ pub fn parseIntSizeSuffix(buf: []const u8, digit_base: u8) ParseIntError!usize {
return math.mul(usize, number, multiplier); return math.mul(usize, number, multiplier);
} }
test "parseIntSizeSuffix" { test parseIntSizeSuffix {
try std.testing.expect(try parseIntSizeSuffix("2", 10) == 2); try std.testing.expect(try parseIntSizeSuffix("2", 10) == 2);
try std.testing.expect(try parseIntSizeSuffix("2B", 10) == 2); try std.testing.expect(try parseIntSizeSuffix("2B", 10) == 2);
try std.testing.expect(try parseIntSizeSuffix("2kB", 10) == 2000); try std.testing.expect(try parseIntSizeSuffix("2kB", 10) == 2000);
@ -1793,7 +1793,7 @@ pub fn allocPrintZ(allocator: mem.Allocator, comptime fmt: []const u8, args: any
return result[0 .. result.len - 1 :0]; return result[0 .. result.len - 1 :0];
} }
test "bufPrintInt" { test bufPrintIntToSlice {
var buffer: [100]u8 = undefined; var buffer: [100]u8 = undefined;
const buf = buffer[0..]; const buf = buffer[0..];
@ -1827,7 +1827,7 @@ pub inline fn comptimePrint(comptime fmt: []const u8, args: anytype) *const [cou
} }
} }
test "comptimePrint" { test comptimePrint {
@setEvalBranchQuota(2000); @setEvalBranchQuota(2000);
try std.testing.expectEqual(*const [3:0]u8, @TypeOf(comptimePrint("{}", .{100}))); try std.testing.expectEqual(*const [3:0]u8, @TypeOf(comptimePrint("{}", .{100})));
try std.testing.expectEqualSlices(u8, "100", comptimePrint("{}", .{100})); try std.testing.expectEqualSlices(u8, "100", comptimePrint("{}", .{100}));
@ -2442,14 +2442,14 @@ pub fn hexToBytes(out: []u8, input: []const u8) ![]u8 {
return out[0 .. in_i / 2]; return out[0 .. in_i / 2];
} }
test "bytesToHex" { test bytesToHex {
const input = "input slice"; const input = "input slice";
const encoded = bytesToHex(input, .lower); const encoded = bytesToHex(input, .lower);
var decoded: [input.len]u8 = undefined; var decoded: [input.len]u8 = undefined;
try std.testing.expectEqualSlices(u8, input, try hexToBytes(&decoded, &encoded)); try std.testing.expectEqualSlices(u8, input, try hexToBytes(&decoded, &encoded));
} }
test "hexToBytes" { test hexToBytes {
var buf: [32]u8 = undefined; var buf: [32]u8 = undefined;
try expectFmt("90" ** 32, "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "90" ** 32))}); try expectFmt("90" ** 32, "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "90" ** 32))});
try expectFmt("ABCD", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "ABCD"))}); try expectFmt("ABCD", "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "ABCD"))});

View file

@ -60,7 +60,7 @@ pub fn getAppDataDir(allocator: mem.Allocator, appname: []const u8) GetAppDataDi
} }
} }
test "getAppDataDir" { test getAppDataDir {
if (builtin.os.tag == .wasi) return error.SkipZigTest; if (builtin.os.tag == .wasi) return error.SkipZigTest;
// We can't actually validate the result // We can't actually validate the result

View file

@ -180,7 +180,7 @@ fn testJoinMaybeZPosix(paths: []const []const u8, expected: []const u8, zero: bo
try 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" { test join {
{ {
const actual: []u8 = try join(testing.allocator, &[_][]const u8{}); const actual: []u8 = try join(testing.allocator, &[_][]const u8{});
defer testing.allocator.free(actual); defer testing.allocator.free(actual);
@ -303,7 +303,7 @@ pub fn isAbsolutePosixZ(path_c: [*:0]const u8) bool {
return isAbsolutePosix(mem.sliceTo(path_c, 0)); return isAbsolutePosix(mem.sliceTo(path_c, 0));
} }
test "isAbsoluteWindows" { test isAbsoluteWindows {
try testIsAbsoluteWindows("", false); try testIsAbsoluteWindows("", false);
try testIsAbsoluteWindows("/", true); try testIsAbsoluteWindows("/", true);
try testIsAbsoluteWindows("//", true); try testIsAbsoluteWindows("//", true);
@ -326,7 +326,7 @@ test "isAbsoluteWindows" {
try testIsAbsoluteWindows("/usr/local", true); try testIsAbsoluteWindows("/usr/local", true);
} }
test "isAbsolutePosix" { test isAbsolutePosix {
try testIsAbsolutePosix("", false); try testIsAbsolutePosix("", false);
try testIsAbsolutePosix("/home/foo", true); try testIsAbsolutePosix("/home/foo", true);
try testIsAbsolutePosix("/home/foo/..", true); try testIsAbsolutePosix("/home/foo/..", true);
@ -400,7 +400,7 @@ pub fn windowsParsePath(path: []const u8) WindowsPath {
return relative_path; return relative_path;
} }
test "windowsParsePath" { test windowsParsePath {
{ {
const parsed = windowsParsePath("//a/b"); const parsed = windowsParsePath("//a/b");
try testing.expect(parsed.is_abs); try testing.expect(parsed.is_abs);
@ -884,7 +884,7 @@ pub fn dirnamePosix(path: []const u8) ?[]const u8 {
return path[0..end_index]; return path[0..end_index];
} }
test "dirnamePosix" { test dirnamePosix {
try testDirnamePosix("/a/b/c", "/a/b"); try testDirnamePosix("/a/b/c", "/a/b");
try testDirnamePosix("/a/b/c///", "/a/b"); try testDirnamePosix("/a/b/c///", "/a/b");
try testDirnamePosix("/a", "/"); try testDirnamePosix("/a", "/");
@ -898,7 +898,7 @@ test "dirnamePosix" {
try testDirnamePosix("a//", null); try testDirnamePosix("a//", null);
} }
test "dirnameWindows" { test dirnameWindows {
try testDirnameWindows("c:\\", null); try testDirnameWindows("c:\\", null);
try testDirnameWindows("c:\\foo", "c:\\"); try testDirnameWindows("c:\\foo", "c:\\");
try testDirnameWindows("c:\\foo\\", "c:\\"); try testDirnameWindows("c:\\foo\\", "c:\\");
@ -1011,7 +1011,7 @@ pub fn basenameWindows(path: []const u8) []const u8 {
return path[start_index + 1 .. end_index]; return path[start_index + 1 .. end_index];
} }
test "basename" { test basename {
try testBasename("", ""); try testBasename("", "");
try testBasename("/", ""); try testBasename("/", "");
try testBasename("/dir/basename.ext", "basename.ext"); try testBasename("/dir/basename.ext", "basename.ext");
@ -1186,7 +1186,7 @@ pub fn relativePosix(allocator: Allocator, from: []const u8, to: []const u8) ![]
return [_]u8{}; return [_]u8{};
} }
test "relative" { test relative {
try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games"); try testRelativeWindows("c:/blah\\blah", "d:/games", "D:\\games");
try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", ".."); try testRelativeWindows("c:/aaaa/bbbb", "c:/aaaa", "..");
try testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc"); try testRelativeWindows("c:/aaaa/bbbb", "c:/cccc", "..\\..\\cccc");
@ -1271,7 +1271,7 @@ fn testExtension(path: []const u8, expected: []const u8) !void {
try testing.expectEqualStrings(expected, extension(path)); try testing.expectEqualStrings(expected, extension(path));
} }
test "extension" { test extension {
try testExtension("", ""); try testExtension("", "");
try testExtension(".", ""); try testExtension(".", "");
try testExtension("a.", "."); try testExtension("a.", ".");
@ -1328,7 +1328,7 @@ fn testStem(path: []const u8, expected: []const u8) !void {
try testing.expectEqualStrings(expected, stem(path)); try testing.expectEqualStrings(expected, stem(path));
} }
test "stem" { test stem {
try testStem("hello/world/lib.tar.gz", "lib.tar"); try testStem("hello/world/lib.tar.gz", "lib.tar");
try testStem("hello/world/lib.tar", "lib"); try testStem("hello/world/lib.tar", "lib");
try testStem("hello/world/lib", "lib"); try testStem("hello/world/lib", "lib");

View file

@ -425,7 +425,7 @@ fn dummyWrite(context: void, data: []const u8) error{}!usize {
return data.len; return data.len;
} }
test "null_writer" { test null_writer {
null_writer.writeAll("yay" ** 10) catch |err| switch (err) {}; null_writer.writeAll("yay" ** 10) catch |err| switch (err) {};
} }

View file

@ -161,26 +161,16 @@ pub fn approxEqRel(comptime T: type, x: T, y: T, tolerance: T) bool {
return @abs(x - y) <= @max(@abs(x), @abs(y)) * tolerance; return @abs(x - y) <= @max(@abs(x), @abs(y)) * tolerance;
} }
test "approxEqAbs and approxEqRel" { test approxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| { inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T); const eps_value = comptime floatEps(T);
const sqrt_eps_value = comptime sqrt(eps_value);
const nan_value = comptime nan(T);
const inf_value = comptime inf(T);
const min_value = comptime floatMin(T); const min_value = comptime floatMin(T);
try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value)); try testing.expect(approxEqAbs(T, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value)); try testing.expect(approxEqAbs(T, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value)); try testing.expect(approxEqAbs(T, 0.0, -0.0, eps_value));
try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value)); try testing.expect(!approxEqAbs(T, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value)); try testing.expect(approxEqAbs(T, 1.0 + 1 * eps_value, 1.0, eps_value));
try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2)); try testing.expect(approxEqAbs(T, min_value, 0.0, eps_value * 2));
try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2)); try testing.expect(approxEqAbs(T, -min_value, 0.0, eps_value * 2));
} }
@ -192,18 +182,46 @@ test "approxEqAbs and approxEqRel" {
// possible epsilon value like we do in the tests above. In the same vein, we // possible epsilon value like we do in the tests above. In the same vein, we
// also can't represent a max/min, `NaN` or `Inf` values. // also can't represent a max/min, `NaN` or `Inf` values.
const eps_value = 1e-4; const eps_value = 1e-4;
const sqrt_eps_value = sqrt(eps_value);
try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value)); try testing.expect(approxEqAbs(comptime_float, 0.0, 0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value)); try testing.expect(approxEqAbs(comptime_float, -0.0, -0.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value)); try testing.expect(approxEqAbs(comptime_float, 0.0, -0.0, eps_value));
try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value)); try testing.expect(!approxEqAbs(comptime_float, 1.0 + 2 * eps_value, 1.0, eps_value));
try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value)); try testing.expect(approxEqAbs(comptime_float, 1.0 + 1 * eps_value, 1.0, eps_value));
} }
} }
test approxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime floatEps(T);
const sqrt_eps_value = comptime sqrt(eps_value);
const nan_value = comptime nan(T);
const inf_value = comptime inf(T);
const min_value = comptime floatMin(T);
try testing.expect(approxEqRel(T, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, 0.0, sqrt_eps_value));
try testing.expect(!approxEqRel(T, 1.0, nan_value, sqrt_eps_value));
try testing.expect(!approxEqRel(T, nan_value, nan_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, inf_value, inf_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, min_value, min_value, sqrt_eps_value));
try testing.expect(approxEqRel(T, -min_value, -min_value, sqrt_eps_value));
}
comptime {
// `comptime_float` is guaranteed to have the same precision and operations of
// the largest other floating point type, which is f128 but it doesn't have a
// defined layout so we can't rely on `@bitCast` to construct the smallest
// possible epsilon value like we do in the tests above. In the same vein, we
// also can't represent a max/min, `NaN` or `Inf` values.
const eps_value = 1e-4;
const sqrt_eps_value = sqrt(eps_value);
try testing.expect(approxEqRel(comptime_float, 1.0, 1.0, sqrt_eps_value));
try testing.expect(!approxEqRel(comptime_float, 1.0, 0.0, sqrt_eps_value));
}
}
pub const doNotOptimizeAway = @compileError("Deprecated: use `std.mem.doNotOptimizeAway` instead"); pub const doNotOptimizeAway = @compileError("Deprecated: use `std.mem.doNotOptimizeAway` instead");
pub fn raiseInvalid() void { pub fn raiseInvalid() void {
@ -300,7 +318,7 @@ pub fn radiansToDegrees(comptime T: type, angle_in_radians: T) T {
return angle_in_radians * 180.0 / pi; return angle_in_radians * 180.0 / pi;
} }
test "radiansToDegrees" { test radiansToDegrees {
try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(f32, 0), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, 0), radiansToDegrees(f32, 0), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(f32, pi / 2.0), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, 90), radiansToDegrees(f32, pi / 2.0), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(f32, -pi / 4.0), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, -45), radiansToDegrees(f32, -pi / 4.0), 1e-6);
@ -315,7 +333,7 @@ pub fn degreesToRadians(comptime T: type, angle_in_degrees: T) T {
return angle_in_degrees * pi / 180.0; return angle_in_degrees * pi / 180.0;
} }
test "degreesToRadians" { test degreesToRadians {
try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(f32, 90), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, pi / 2.0), degreesToRadians(f32, 90), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(f32, -270), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, -3 * pi / 2.0), degreesToRadians(f32, -270), 1e-6);
try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(f32, 360), 1e-6); try std.testing.expectApproxEqAbs(@as(f32, 2 * pi), degreesToRadians(f32, 360), 1e-6);
@ -464,7 +482,7 @@ pub fn wrap(x: anytype, r: anytype) @TypeOf(x) {
}, },
} }
} }
test "wrap" { test wrap {
// Within range // Within range
try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75); try testing.expect(wrap(@as(i32, -75), @as(i32, 180)) == -75);
try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75); try testing.expect(wrap(@as(i32, -75), @as(i32, -180)) == -75);
@ -501,8 +519,7 @@ test "wrap" {
var i: i32 = 1; var i: i32 = 1;
_ = &i; _ = &i;
try testing.expect(wrap(i, 10) == 1); try testing.expect(wrap(i, 10) == 1);
}
test wrap {
const limit: i32 = 180; const limit: i32 = 180;
// Within range // Within range
try testing.expect(wrap(@as(i32, -75), limit) == -75); try testing.expect(wrap(@as(i32, -75), limit) == -75);
@ -527,7 +544,7 @@ pub fn clamp(val: anytype, lower: anytype, upper: anytype) @TypeOf(val, lower, u
assert(lower <= upper); assert(lower <= upper);
return @max(lower, @min(val, upper)); return @max(lower, @min(val, upper));
} }
test "clamp" { test clamp {
// Within range // Within range
try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1); try testing.expect(std.math.clamp(@as(i32, -1), @as(i32, -4), @as(i32, 7)) == -1);
// Below // Below
@ -608,7 +625,7 @@ pub fn shl(comptime T: type, a: T, shift_amt: anytype) T {
return a << casted_shift_amt; return a << casted_shift_amt;
} }
test "shl" { test shl {
if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) { if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) {
// https://github.com/ziglang/zig/issues/12012 // https://github.com/ziglang/zig/issues/12012
return error.SkipZigTest; return error.SkipZigTest;
@ -653,7 +670,7 @@ pub fn shr(comptime T: type, a: T, shift_amt: anytype) T {
return a >> casted_shift_amt; return a >> casted_shift_amt;
} }
test "shr" { test shr {
if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) { if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) {
// https://github.com/ziglang/zig/issues/12012 // https://github.com/ziglang/zig/issues/12012
return error.SkipZigTest; return error.SkipZigTest;
@ -699,7 +716,7 @@ pub fn rotr(comptime T: type, x: T, r: anytype) T {
} }
} }
test "rotr" { test rotr {
if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) { if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) {
// https://github.com/ziglang/zig/issues/12012 // https://github.com/ziglang/zig/issues/12012
return error.SkipZigTest; return error.SkipZigTest;
@ -744,7 +761,7 @@ pub fn rotl(comptime T: type, x: T, r: anytype) T {
} }
} }
test "rotl" { test rotl {
if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) { if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) {
// https://github.com/ziglang/zig/issues/12012 // https://github.com/ziglang/zig/issues/12012
return error.SkipZigTest; return error.SkipZigTest;
@ -806,7 +823,7 @@ pub fn IntFittingRange(comptime from: comptime_int, comptime to: comptime_int) t
return std.meta.Int(signedness, magnitude_bits); return std.meta.Int(signedness, magnitude_bits);
} }
test "IntFittingRange" { test IntFittingRange {
try testing.expect(IntFittingRange(0, 0) == u0); try testing.expect(IntFittingRange(0, 0) == u0);
try testing.expect(IntFittingRange(0, 1) == u1); try testing.expect(IntFittingRange(0, 1) == u1);
try testing.expect(IntFittingRange(0, 2) == u2); try testing.expect(IntFittingRange(0, 2) == u2);
@ -874,7 +891,7 @@ pub fn divTrunc(comptime T: type, numerator: T, denominator: T) !T {
return @divTrunc(numerator, denominator); return @divTrunc(numerator, denominator);
} }
test "divTrunc" { test divTrunc {
try testDivTrunc(); try testDivTrunc();
try comptime testDivTrunc(); try comptime testDivTrunc();
} }
@ -898,7 +915,7 @@ pub fn divFloor(comptime T: type, numerator: T, denominator: T) !T {
return @divFloor(numerator, denominator); return @divFloor(numerator, denominator);
} }
test "divFloor" { test divFloor {
try testDivFloor(); try testDivFloor();
try comptime testDivFloor(); try comptime testDivFloor();
} }
@ -935,7 +952,7 @@ pub fn divCeil(comptime T: type, numerator: T, denominator: T) !T {
} }
} }
test "divCeil" { test divCeil {
try testDivCeil(); try testDivCeil();
try comptime testDivCeil(); try comptime testDivCeil();
} }
@ -979,7 +996,7 @@ pub fn divExact(comptime T: type, numerator: T, denominator: T) !T {
return result; return result;
} }
test "divExact" { test divExact {
try testDivExact(); try testDivExact();
try comptime testDivExact(); try comptime testDivExact();
} }
@ -1005,7 +1022,7 @@ pub fn mod(comptime T: type, numerator: T, denominator: T) !T {
return @mod(numerator, denominator); return @mod(numerator, denominator);
} }
test "mod" { test mod {
try testMod(); try testMod();
try comptime testMod(); try comptime testMod();
} }
@ -1031,7 +1048,7 @@ pub fn rem(comptime T: type, numerator: T, denominator: T) !T {
return @rem(numerator, denominator); return @rem(numerator, denominator);
} }
test "rem" { test rem {
try testRem(); try testRem();
try comptime testRem(); try comptime testRem();
} }
@ -1060,7 +1077,7 @@ pub fn negateCast(x: anytype) !std.meta.Int(.signed, @bitSizeOf(@TypeOf(x))) {
return -@as(int, @intCast(x)); return -@as(int, @intCast(x));
} }
test "negateCast" { test negateCast {
try testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999); try testing.expect((negateCast(@as(u32, 999)) catch unreachable) == -999);
try testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32); try testing.expect(@TypeOf(negateCast(@as(u32, 999)) catch unreachable) == i32);
@ -1085,7 +1102,7 @@ pub fn cast(comptime T: type, x: anytype) ?T {
} }
} }
test "cast" { test cast {
try testing.expect(cast(u8, 300) == null); try testing.expect(cast(u8, 300) == null);
try testing.expect(cast(u8, @as(u32, 300)) == null); try testing.expect(cast(u8, @as(u32, 300)) == null);
try testing.expect(cast(i8, -200) == null); try testing.expect(cast(i8, -200) == null);
@ -1144,7 +1161,7 @@ pub fn ByteAlignedInt(comptime T: type) type {
return extended_type; return extended_type;
} }
test "ByteAlignedInt" { test ByteAlignedInt {
try testing.expect(ByteAlignedInt(u0) == u0); try testing.expect(ByteAlignedInt(u0) == u0);
try testing.expect(ByteAlignedInt(i0) == i0); try testing.expect(ByteAlignedInt(i0) == i0);
try testing.expect(ByteAlignedInt(u3) == u8); try testing.expect(ByteAlignedInt(u3) == u8);
@ -1182,7 +1199,7 @@ pub fn floorPowerOfTwo(comptime T: type, value: T) T {
return @as(T, 1) << log2_int(uT, @as(uT, @intCast(value))); return @as(T, 1) << log2_int(uT, @as(uT, @intCast(value)));
} }
test "floorPowerOfTwo" { test floorPowerOfTwo {
try testFloorPowerOfTwo(); try testFloorPowerOfTwo();
try comptime testFloorPowerOfTwo(); try comptime testFloorPowerOfTwo();
} }
@ -1244,7 +1261,7 @@ pub fn ceilPowerOfTwoAssert(comptime T: type, value: T) T {
return ceilPowerOfTwo(T, value) catch unreachable; return ceilPowerOfTwo(T, value) catch unreachable;
} }
test "ceilPowerOfTwoPromote" { test ceilPowerOfTwoPromote {
try testCeilPowerOfTwoPromote(); try testCeilPowerOfTwoPromote();
try comptime testCeilPowerOfTwoPromote(); try comptime testCeilPowerOfTwoPromote();
} }
@ -1261,7 +1278,7 @@ fn testCeilPowerOfTwoPromote() !void {
try testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9)); try testing.expectEqual(@as(u5, 16), ceilPowerOfTwoPromote(u4, 9));
} }
test "ceilPowerOfTwo" { test ceilPowerOfTwo {
try testCeilPowerOfTwo(); try testCeilPowerOfTwo();
try comptime testCeilPowerOfTwo(); try comptime testCeilPowerOfTwo();
} }
@ -1354,7 +1371,7 @@ pub fn lossyCast(comptime T: type, value: anytype) T {
} }
} }
test "lossyCast" { test lossyCast {
try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767)); try testing.expect(lossyCast(i16, 70000.0) == @as(i16, 32767));
try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0)); try testing.expect(lossyCast(u32, @as(i16, -255)) == @as(u32, 0));
try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200)); try testing.expect(lossyCast(i9, @as(u32, 200)) == @as(i9, 200));
@ -1383,7 +1400,7 @@ pub fn lerp(a: anytype, b: anytype, t: anytype) @TypeOf(a, b, t) {
return @mulAdd(Type, b - a, t, a); return @mulAdd(Type, b - a, t, a);
} }
test "lerp" { test lerp {
if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/17884 if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/17884
if (builtin.zig_backend == .stage2_x86_64 and if (builtin.zig_backend == .stage2_x86_64 and
!comptime std.Target.x86.featureSetHas(builtin.cpu.features, .fma)) return error.SkipZigTest; !comptime std.Target.x86.featureSetHas(builtin.cpu.features, .fma)) return error.SkipZigTest;
@ -1437,7 +1454,7 @@ pub fn minInt(comptime T: type) comptime_int {
return -(1 << (bit_count - 1)); return -(1 << (bit_count - 1));
} }
test "minInt and maxInt" { test maxInt {
try testing.expect(maxInt(u0) == 0); try testing.expect(maxInt(u0) == 0);
try testing.expect(maxInt(u1) == 1); try testing.expect(maxInt(u1) == 1);
try testing.expect(maxInt(u8) == 255); try testing.expect(maxInt(u8) == 255);
@ -1454,7 +1471,9 @@ test "minInt and maxInt" {
try testing.expect(maxInt(i63) == 4611686018427387903); try testing.expect(maxInt(i63) == 4611686018427387903);
try testing.expect(maxInt(i64) == 9223372036854775807); try testing.expect(maxInt(i64) == 9223372036854775807);
try testing.expect(maxInt(i128) == 170141183460469231731687303715884105727); try testing.expect(maxInt(i128) == 170141183460469231731687303715884105727);
}
test minInt {
try testing.expect(minInt(u0) == 0); try testing.expect(minInt(u0) == 0);
try testing.expect(minInt(u1) == 0); try testing.expect(minInt(u1) == 0);
try testing.expect(minInt(u8) == 0); try testing.expect(minInt(u8) == 0);
@ -1492,7 +1511,7 @@ pub fn mulWide(comptime T: type, a: T, b: T) std.meta.Int(
return @as(ResultInt, a) * @as(ResultInt, b); return @as(ResultInt, a) * @as(ResultInt, b);
} }
test "mulWide" { test mulWide {
try testing.expect(mulWide(u8, 5, 5) == 25); try testing.expect(mulWide(u8, 5, 5) == 25);
try testing.expect(mulWide(i8, 5, -5) == -25); try testing.expect(mulWide(i8, 5, -5) == -25);
try testing.expect(mulWide(u8, 100, 100) == 10000); try testing.expect(mulWide(u8, 100, 100) == 10000);
@ -1517,6 +1536,12 @@ pub const Order = enum {
}; };
} }
test invert {
try testing.expect(Order.invert(order(0, 0)) == .eq);
try testing.expect(Order.invert(order(1, 0)) == .lt);
try testing.expect(Order.invert(order(-1, 0)) == .gt);
}
pub fn compare(self: Order, op: CompareOperator) bool { pub fn compare(self: Order, op: CompareOperator) bool {
return switch (self) { return switch (self) {
.lt => switch (op) { .lt => switch (op) {
@ -1545,6 +1570,19 @@ pub const Order = enum {
}, },
}; };
} }
// TODO flaw in the language, can't make this a doctest due to ambiguous reference
// also: can't currently add a doctest from an outside scope
test "compare" {
try testing.expect(order(-1, 0).compare(.lt));
try testing.expect(order(-1, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.eq));
try testing.expect(order(0, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gt));
try testing.expect(order(1, 0).compare(.neq));
}
}; };
/// Given two numbers, this function returns the order they are with respect to each other. /// Given two numbers, this function returns the order they are with respect to each other.
@ -1587,6 +1625,15 @@ pub const CompareOperator = enum {
.neq => .neq, .neq => .neq,
}; };
} }
test reverse {
inline for (@typeInfo(CompareOperator).Enum.fields) |op_field| {
const op = @as(CompareOperator, @enumFromInt(op_field.value));
try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2));
try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3));
try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4));
}
}
}; };
/// This function does the same thing as comparison operators, however the /// This function does the same thing as comparison operators, however the
@ -1603,7 +1650,7 @@ pub fn compare(a: anytype, op: CompareOperator, b: anytype) bool {
}; };
} }
test "compare between signed and unsigned" { test compare {
try testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255))); try testing.expect(compare(@as(i8, -1), .lt, @as(u8, 255)));
try testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1))); try testing.expect(compare(@as(i8, 2), .gt, @as(u8, 1)));
try testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255))); try testing.expect(!compare(@as(i8, -1), .gte, @as(u8, 255)));
@ -1623,38 +1670,12 @@ test "compare between signed and unsigned" {
try testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1))); try testing.expect(compare(@as(u8, 1), .eq, @as(u8, 1)));
} }
test "order" { test order {
try testing.expect(order(0, 0) == .eq); try testing.expect(order(0, 0) == .eq);
try testing.expect(order(1, 0) == .gt); try testing.expect(order(1, 0) == .gt);
try testing.expect(order(-1, 0) == .lt); try testing.expect(order(-1, 0) == .lt);
} }
test "order.invert" {
try testing.expect(Order.invert(order(0, 0)) == .eq);
try testing.expect(Order.invert(order(1, 0)) == .lt);
try testing.expect(Order.invert(order(-1, 0)) == .gt);
}
test "order.compare" {
try testing.expect(order(-1, 0).compare(.lt));
try testing.expect(order(-1, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.lte));
try testing.expect(order(0, 0).compare(.eq));
try testing.expect(order(0, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gte));
try testing.expect(order(1, 0).compare(.gt));
try testing.expect(order(1, 0).compare(.neq));
}
test "compare.reverse" {
inline for (@typeInfo(CompareOperator).Enum.fields) |op_field| {
const op = @as(CompareOperator, @enumFromInt(op_field.value));
try testing.expect(compare(2, op, 3) == compare(3, op.reverse(), 2));
try testing.expect(compare(3, op, 3) == compare(3, op.reverse(), 3));
try testing.expect(compare(4, op, 3) == compare(3, op.reverse(), 4));
}
}
/// Returns a mask of all ones if value is true, /// Returns a mask of all ones if value is true,
/// and a mask of all zeroes if value is false. /// and a mask of all zeroes if value is false.
/// Compiles to one instruction for register sized integers. /// Compiles to one instruction for register sized integers.
@ -1676,7 +1697,7 @@ pub inline fn boolMask(comptime MaskInt: type, value: bool) MaskInt {
return -%@as(MaskInt, @intCast(@intFromBool(value))); return -%@as(MaskInt, @intCast(@intFromBool(value)));
} }
test "boolMask" { test boolMask {
const runTest = struct { const runTest = struct {
fn runTest() !void { fn runTest() !void {
try testing.expectEqual(@as(u1, 0), boolMask(u1, false)); try testing.expectEqual(@as(u1, 0), boolMask(u1, false));
@ -1824,7 +1845,7 @@ fn testSign() !void {
try std.testing.expectEqual(0.0, sign(0.0)); try std.testing.expectEqual(0.0, sign(0.0));
} }
test "sign" { test sign {
if (builtin.zig_backend == .stage2_llvm) { if (builtin.zig_backend == .stage2_llvm) {
// https://github.com/ziglang/zig/issues/12012 // https://github.com/ziglang/zig/issues/12012
return error.SkipZigTest; return error.SkipZigTest;

View file

@ -306,7 +306,7 @@ pub fn zeroes(comptime T: type) T {
} }
} }
test "zeroes" { test zeroes {
const C_struct = extern struct { const C_struct = extern struct {
x: u32, x: u32,
y: u32 align(128), y: u32 align(128),
@ -475,7 +475,7 @@ pub fn zeroInit(comptime T: type, init: anytype) T {
} }
} }
test "zeroInit" { test zeroInit {
const I = struct { const I = struct {
d: f64, d: f64,
}; };
@ -606,16 +606,19 @@ pub fn orderZ(comptime T: type, lhs: [*:0]const T, rhs: [*:0]const T) math.Order
return math.order(lhs[i], rhs[i]); return math.order(lhs[i], rhs[i]);
} }
test "order and orderZ" { test order {
try testing.expect(order(u8, "abcd", "bee") == .lt); try testing.expect(order(u8, "abcd", "bee") == .lt);
try testing.expect(orderZ(u8, "abcd", "bee") == .lt);
try testing.expect(order(u8, "abc", "abc") == .eq); try testing.expect(order(u8, "abc", "abc") == .eq);
try testing.expect(orderZ(u8, "abc", "abc") == .eq);
try testing.expect(order(u8, "abc", "abc0") == .lt); try testing.expect(order(u8, "abc", "abc0") == .lt);
try testing.expect(orderZ(u8, "abc", "abc0") == .lt);
try testing.expect(order(u8, "", "") == .eq); try testing.expect(order(u8, "", "") == .eq);
try testing.expect(orderZ(u8, "", "") == .eq);
try testing.expect(order(u8, "", "a") == .lt); try testing.expect(order(u8, "", "a") == .lt);
}
test orderZ {
try testing.expect(orderZ(u8, "abcd", "bee") == .lt);
try testing.expect(orderZ(u8, "abc", "abc") == .eq);
try testing.expect(orderZ(u8, "abc", "abc0") == .lt);
try testing.expect(orderZ(u8, "", "") == .eq);
try testing.expect(orderZ(u8, "", "a") == .lt); try testing.expect(orderZ(u8, "", "a") == .lt);
} }
@ -624,7 +627,7 @@ pub fn lessThan(comptime T: type, lhs: []const T, rhs: []const T) bool {
return order(T, lhs, rhs) == .lt; return order(T, lhs, rhs) == .lt;
} }
test "lessThan" { test lessThan {
try testing.expect(lessThan(u8, "abcd", "bee")); try testing.expect(lessThan(u8, "abcd", "bee"));
try testing.expect(!lessThan(u8, "abc", "abc")); try testing.expect(!lessThan(u8, "abc", "abc"));
try testing.expect(lessThan(u8, "abc", "abc0")); try testing.expect(lessThan(u8, "abc", "abc0"));
@ -726,7 +729,7 @@ pub fn indexOfDiff(comptime T: type, a: []const T, b: []const T) ?usize {
return if (a.len == b.len) null else shortest; return if (a.len == b.len) null else shortest;
} }
test "indexOfDiff" { test indexOfDiff {
try testing.expectEqual(indexOfDiff(u8, "one", "one"), null); try testing.expectEqual(indexOfDiff(u8, "one", "one"), null);
try testing.expectEqual(indexOfDiff(u8, "one two", "one"), 3); try testing.expectEqual(indexOfDiff(u8, "one two", "one"), 3);
try testing.expectEqual(indexOfDiff(u8, "one", "one two"), 3); try testing.expectEqual(indexOfDiff(u8, "one", "one two"), 3);
@ -759,7 +762,7 @@ fn Span(comptime T: type) type {
@compileError("invalid type given to std.mem.span: " ++ @typeName(T)); @compileError("invalid type given to std.mem.span: " ++ @typeName(T));
} }
test "Span" { test Span {
try testing.expect(Span([*:1]u16) == [:1]u16); try testing.expect(Span([*:1]u16) == [:1]u16);
try testing.expect(Span(?[*:1]u16) == ?[:1]u16); try testing.expect(Span(?[*:1]u16) == ?[:1]u16);
try testing.expect(Span([*:1]const u8) == [:1]const u8); try testing.expect(Span([*:1]const u8) == [:1]const u8);
@ -793,7 +796,7 @@ pub fn span(ptr: anytype) Span(@TypeOf(ptr)) {
} }
} }
test "span" { test span {
var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 }; var array: [5]u16 = [_]u16{ 1, 2, 3, 4, 5 };
const ptr = @as([*:3]u16, array[0..2 :3]); const ptr = @as([*:3]u16, array[0..2 :3]);
try testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 })); try testing.expect(eql(u16, span(ptr), &[_]u16{ 1, 2 }));
@ -877,7 +880,7 @@ pub fn sliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) SliceTo(
} }
} }
test "sliceTo" { test sliceTo {
try testing.expectEqualSlices(u8, "aoeu", sliceTo("aoeu", 0)); try testing.expectEqualSlices(u8, "aoeu", sliceTo("aoeu", 0));
{ {
@ -963,7 +966,7 @@ fn lenSliceTo(ptr: anytype, comptime end: std.meta.Elem(@TypeOf(ptr))) usize {
@compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(@TypeOf(ptr))); @compileError("invalid type given to std.mem.sliceTo: " ++ @typeName(@TypeOf(ptr)));
} }
test "lenSliceTo" { test lenSliceTo {
try testing.expect(lenSliceTo("aoeu", 0) == 4); try testing.expect(lenSliceTo("aoeu", 0) == 4);
{ {
@ -1018,7 +1021,7 @@ pub fn len(value: anytype) usize {
} }
} }
test "len" { test len {
var array: [5]u16 = [_]u16{ 1, 2, 0, 4, 5 }; var array: [5]u16 = [_]u16{ 1, 2, 0, 4, 5 };
const ptr = @as([*:4]u16, array[0..3 :4]); const ptr = @as([*:4]u16, array[0..3 :4]);
try testing.expect(len(ptr) == 3); try testing.expect(len(ptr) == 3);
@ -1157,7 +1160,7 @@ pub fn trim(comptime T: type, slice: []const T, values_to_strip: []const T) []co
return slice[begin..end]; return slice[begin..end];
} }
test "trim" { test trim {
try testing.expectEqualSlices(u8, "foo\n ", trimLeft(u8, " foo\n ", " \n")); try testing.expectEqualSlices(u8, "foo\n ", trimLeft(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, " foo", trimRight(u8, " foo\n ", " \n")); try testing.expectEqualSlices(u8, " foo", trimRight(u8, " foo\n ", " \n"));
try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n")); try testing.expectEqualSlices(u8, "foo", trim(u8, " foo\n ", " \n"));
@ -1240,7 +1243,7 @@ pub fn indexOfScalarPos(comptime T: type, slice: []const T, start_index: usize,
return null; return null;
} }
test "indexOfScalarPos" { test indexOfScalarPos {
const Types = [_]type{ u8, u16, u32, u64 }; const Types = [_]type{ u8, u16, u32, u64 };
inline for (Types) |T| { inline for (Types) |T| {
@ -1316,7 +1319,7 @@ pub fn indexOfNonePos(comptime T: type, slice: []const T, start_index: usize, va
return null; return null;
} }
test "indexOfNone" { test indexOfNone {
try testing.expect(indexOfNone(u8, "abc123", "123").? == 0); try testing.expect(indexOfNone(u8, "abc123", "123").? == 0);
try testing.expect(lastIndexOfNone(u8, "abc123", "123").? == 2); try testing.expect(lastIndexOfNone(u8, "abc123", "123").? == 2);
try testing.expect(indexOfNone(u8, "123abc", "123").? == 3); try testing.expect(indexOfNone(u8, "123abc", "123").? == 3);
@ -1460,7 +1463,7 @@ pub fn indexOfPos(comptime T: type, haystack: []const T, start_index: usize, nee
return null; return null;
} }
test "indexOf" { test indexOf {
try testing.expect(indexOf(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8); try testing.expect(indexOf(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8); try testing.expect(lastIndexOf(u8, "one two three four five six seven eight nine ten eleven", "three four").? == 8);
try testing.expect(indexOf(u8, "one two three four five six seven eight nine ten eleven", "two two") == null); try testing.expect(indexOf(u8, "one two three four five six seven eight nine ten eleven", "two two") == null);
@ -1533,7 +1536,7 @@ pub fn count(comptime T: type, haystack: []const T, needle: []const T) usize {
return found; return found;
} }
test "count" { test count {
try testing.expect(count(u8, "", "h") == 0); try testing.expect(count(u8, "", "h") == 0);
try testing.expect(count(u8, "h", "h") == 1); try testing.expect(count(u8, "h", "h") == 1);
try testing.expect(count(u8, "hh", "h") == 2); try testing.expect(count(u8, "hh", "h") == 2);
@ -1565,7 +1568,7 @@ pub fn containsAtLeast(comptime T: type, haystack: []const T, expected_count: us
return false; return false;
} }
test "containsAtLeast" { test containsAtLeast {
try testing.expect(containsAtLeast(u8, "aa", 0, "a")); try testing.expect(containsAtLeast(u8, "aa", 0, "a"));
try testing.expect(containsAtLeast(u8, "aa", 1, "a")); try testing.expect(containsAtLeast(u8, "aa", 1, "a"));
try testing.expect(containsAtLeast(u8, "aa", 2, "a")); try testing.expect(containsAtLeast(u8, "aa", 2, "a"));
@ -1698,6 +1701,9 @@ test readInt {
try testing.expect(readInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3); try testing.expect(readInt(i16, &[_]u8{ 0xff, 0xfd }, .big) == -3);
try testing.expect(readInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4); try testing.expect(readInt(i16, &[_]u8{ 0xfc, 0xff }, .little) == -4);
try moreReadIntTests();
try comptime moreReadIntTests();
} }
fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T { fn readPackedIntLittle(comptime T: type, bytes: []const u8, bit_offset: usize) T {
@ -2027,7 +2033,7 @@ pub fn byteSwapAllFields(comptime S: type, ptr: *S) void {
} }
} }
test "byteSwapAllFields" { test byteSwapAllFields {
const T = extern struct { const T = extern struct {
f0: u8, f0: u8,
f1: u16, f1: u16,
@ -2136,7 +2142,7 @@ pub fn tokenizeScalar(comptime T: type, buffer: []const T, delimiter: T) TokenIt
}; };
} }
test "tokenizeScalar" { test tokenizeScalar {
var it = tokenizeScalar(u8, " abc def ghi ", ' '); var it = tokenizeScalar(u8, " abc def ghi ", ' ');
try testing.expect(eql(u8, it.next().?, "abc")); try testing.expect(eql(u8, it.next().?, "abc"));
try testing.expect(eql(u8, it.peek().?, "def")); try testing.expect(eql(u8, it.peek().?, "def"));
@ -2177,7 +2183,7 @@ test "tokenizeScalar" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "tokenizeAny" { test tokenizeAny {
var it = tokenizeAny(u8, "a|b,c/d e", " /,|"); var it = tokenizeAny(u8, "a|b,c/d e", " /,|");
try testing.expect(eql(u8, it.next().?, "a")); try testing.expect(eql(u8, it.next().?, "a"));
try testing.expect(eql(u8, it.peek().?, "b")); try testing.expect(eql(u8, it.peek().?, "b"));
@ -2205,7 +2211,7 @@ test "tokenizeAny" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "tokenizeSequence" { test tokenizeSequence {
var it = tokenizeSequence(u8, "a<>b<><>c><>d><", "<>"); var it = tokenizeSequence(u8, "a<>b<><>c><>d><", "<>");
try testing.expectEqualStrings("a", it.next().?); try testing.expectEqualStrings("a", it.next().?);
try testing.expectEqualStrings("b", it.peek().?); try testing.expectEqualStrings("b", it.peek().?);
@ -2334,7 +2340,7 @@ pub fn splitScalar(comptime T: type, buffer: []const T, delimiter: T) SplitItera
}; };
} }
test "splitScalar" { test splitScalar {
var it = splitScalar(u8, "abc|def||ghi", '|'); var it = splitScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi"); try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "abc"); try testing.expectEqualSlices(u8, it.first(), "abc");
@ -2377,7 +2383,7 @@ test "splitScalar" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "splitSequence" { test splitSequence {
var it = splitSequence(u8, "a, b ,, c, d, e", ", "); var it = splitSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a"); try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b ,, c, d, e"); try testing.expectEqualSlices(u8, it.rest(), "b ,, c, d, e");
@ -2400,7 +2406,7 @@ test "splitSequence" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "splitAny" { test splitAny {
var it = splitAny(u8, "a,b, c d e", ", "); var it = splitAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.first(), "a"); try testing.expectEqualSlices(u8, it.first(), "a");
try testing.expectEqualSlices(u8, it.rest(), "b, c d e"); try testing.expectEqualSlices(u8, it.rest(), "b, c d e");
@ -2536,7 +2542,7 @@ pub fn splitBackwardsScalar(comptime T: type, buffer: []const T, delimiter: T) S
}; };
} }
test "splitBackwardsScalar" { test splitBackwardsScalar {
var it = splitBackwardsScalar(u8, "abc|def||ghi", '|'); var it = splitBackwardsScalar(u8, "abc|def||ghi", '|');
try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi"); try testing.expectEqualSlices(u8, it.rest(), "abc|def||ghi");
try testing.expectEqualSlices(u8, it.first(), "ghi"); try testing.expectEqualSlices(u8, it.first(), "ghi");
@ -2575,7 +2581,7 @@ test "splitBackwardsScalar" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "splitBackwardsSequence" { test splitBackwardsSequence {
var it = splitBackwardsSequence(u8, "a, b ,, c, d, e", ", "); var it = splitBackwardsSequence(u8, "a, b ,, c, d, e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d, e"); try testing.expectEqualSlices(u8, it.rest(), "a, b ,, c, d, e");
try testing.expectEqualSlices(u8, it.first(), "e"); try testing.expectEqualSlices(u8, it.first(), "e");
@ -2608,7 +2614,7 @@ test "splitBackwardsSequence" {
try testing.expect(it16.next() == null); try testing.expect(it16.next() == null);
} }
test "splitBackwardsAny" { test splitBackwardsAny {
var it = splitBackwardsAny(u8, "a,b, c d e", ", "); var it = splitBackwardsAny(u8, "a,b, c d e", ", ");
try testing.expectEqualSlices(u8, it.rest(), "a,b, c d e"); try testing.expectEqualSlices(u8, it.rest(), "a,b, c d e");
try testing.expectEqualSlices(u8, it.first(), "e"); try testing.expectEqualSlices(u8, it.first(), "e");
@ -2715,7 +2721,7 @@ pub fn window(comptime T: type, buffer: []const T, size: usize, advance: usize)
}; };
} }
test "window" { test window {
{ {
// moving average size 3 // moving average size 3
var it = window(u8, "abcdefg", 3, 1); var it = window(u8, "abcdefg", 3, 1);
@ -2841,7 +2847,7 @@ pub fn startsWith(comptime T: type, haystack: []const T, needle: []const T) bool
return if (needle.len > haystack.len) false else eql(T, haystack[0..needle.len], needle); return if (needle.len > haystack.len) false else eql(T, haystack[0..needle.len], needle);
} }
test "startsWith" { test startsWith {
try testing.expect(startsWith(u8, "Bob", "Bo")); try testing.expect(startsWith(u8, "Bob", "Bo"));
try testing.expect(!startsWith(u8, "Needle in haystack", "haystack")); try testing.expect(!startsWith(u8, "Needle in haystack", "haystack"));
} }
@ -2850,7 +2856,7 @@ pub fn endsWith(comptime T: type, haystack: []const T, needle: []const T) bool {
return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle); return if (needle.len > haystack.len) false else eql(T, haystack[haystack.len - needle.len ..], needle);
} }
test "endsWith" { test endsWith {
try testing.expect(endsWith(u8, "Needle in haystack", "haystack")); try testing.expect(endsWith(u8, "Needle in haystack", "haystack"));
try testing.expect(!endsWith(u8, "Bob", "Bo")); try testing.expect(!endsWith(u8, "Bob", "Bo"));
} }
@ -3086,7 +3092,7 @@ fn joinMaybeZ(allocator: Allocator, separator: []const u8, slices: []const []con
return buf; return buf;
} }
test "join" { test join {
{ {
const str = try join(testing.allocator, ",", &[_][]const u8{}); const str = try join(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str); defer testing.allocator.free(str);
@ -3109,7 +3115,7 @@ test "join" {
} }
} }
test "joinZ" { test joinZ {
{ {
const str = try joinZ(testing.allocator, ",", &[_][]const u8{}); const str = try joinZ(testing.allocator, ",", &[_][]const u8{});
defer testing.allocator.free(str); defer testing.allocator.free(str);
@ -3181,7 +3187,7 @@ pub fn concatMaybeSentinel(allocator: Allocator, comptime T: type, slices: []con
return buf; return buf;
} }
test "concat" { test concat {
{ {
const str = try concat(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" }); const str = try concat(testing.allocator, u8, &[_][]const u8{ "abc", "def", "ghi" });
defer testing.allocator.free(str); defer testing.allocator.free(str);
@ -3219,17 +3225,13 @@ test "concat" {
} }
} }
test "testStringEquality" { test eql {
try testing.expect(eql(u8, "abcd", "abcd")); try testing.expect(eql(u8, "abcd", "abcd"));
try testing.expect(!eql(u8, "abcdef", "abZdef")); try testing.expect(!eql(u8, "abcdef", "abZdef"));
try testing.expect(!eql(u8, "abcdefg", "abcdef")); try testing.expect(!eql(u8, "abcdefg", "abcdef"));
} }
test "testReadInt" { fn moreReadIntTests() !void {
try testReadIntImpl();
try comptime testReadIntImpl();
}
fn testReadIntImpl() !void {
{ {
const bytes = [_]u8{ const bytes = [_]u8{
0x12, 0x12,
@ -3287,7 +3289,7 @@ pub fn min(comptime T: type, slice: []const T) T {
return best; return best;
} }
test "min" { test min {
try testing.expectEqual(min(u8, "abcdefg"), 'a'); try testing.expectEqual(min(u8, "abcdefg"), 'a');
try testing.expectEqual(min(u8, "bcdefga"), 'a'); try testing.expectEqual(min(u8, "bcdefga"), 'a');
try testing.expectEqual(min(u8, "a"), 'a'); try testing.expectEqual(min(u8, "a"), 'a');
@ -3304,7 +3306,7 @@ pub fn max(comptime T: type, slice: []const T) T {
return best; return best;
} }
test "max" { test max {
try testing.expectEqual(max(u8, "abcdefg"), 'g'); try testing.expectEqual(max(u8, "abcdefg"), 'g');
try testing.expectEqual(max(u8, "gabcdef"), 'g'); try testing.expectEqual(max(u8, "gabcdef"), 'g');
try testing.expectEqual(max(u8, "g"), 'g'); try testing.expectEqual(max(u8, "g"), 'g');
@ -3357,7 +3359,7 @@ pub fn indexOfMin(comptime T: type, slice: []const T) usize {
return index; return index;
} }
test "indexOfMin" { test indexOfMin {
try testing.expectEqual(indexOfMin(u8, "abcdefg"), 0); try testing.expectEqual(indexOfMin(u8, "abcdefg"), 0);
try testing.expectEqual(indexOfMin(u8, "bcdefga"), 6); try testing.expectEqual(indexOfMin(u8, "bcdefga"), 6);
try testing.expectEqual(indexOfMin(u8, "a"), 0); try testing.expectEqual(indexOfMin(u8, "a"), 0);
@ -3378,7 +3380,7 @@ pub fn indexOfMax(comptime T: type, slice: []const T) usize {
return index; return index;
} }
test "indexOfMax" { test indexOfMax {
try testing.expectEqual(indexOfMax(u8, "abcdefg"), 6); try testing.expectEqual(indexOfMax(u8, "abcdefg"), 6);
try testing.expectEqual(indexOfMax(u8, "gabcdef"), 0); try testing.expectEqual(indexOfMax(u8, "gabcdef"), 0);
try testing.expectEqual(indexOfMax(u8, "a"), 0); try testing.expectEqual(indexOfMax(u8, "a"), 0);
@ -3408,7 +3410,7 @@ pub fn indexOfMinMax(comptime T: type, slice: []const T) IndexOfMinMaxResult {
pub const IndexOfMinMaxResult = struct { index_min: usize, index_max: usize }; pub const IndexOfMinMaxResult = struct { index_min: usize, index_max: usize };
test "indexOfMinMax" { test indexOfMinMax {
try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 0, .index_max = 6 }, indexOfMinMax(u8, "abcdefg")); try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 0, .index_max = 6 }, indexOfMinMax(u8, "abcdefg"));
try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 1, .index_max = 0 }, indexOfMinMax(u8, "gabcdef")); try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 1, .index_max = 0 }, indexOfMinMax(u8, "gabcdef"));
try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 0, .index_max = 0 }, indexOfMinMax(u8, "a")); try testing.expectEqual(IndexOfMinMaxResult{ .index_min = 0, .index_max = 0 }, indexOfMinMax(u8, "a"));
@ -3429,7 +3431,7 @@ pub fn reverse(comptime T: type, items: []T) void {
} }
} }
test "reverse" { test reverse {
var arr = [_]i32{ 5, 3, 1, 2, 4 }; var arr = [_]i32{ 5, 3, 1, 2, 4 };
reverse(i32, arr[0..]); reverse(i32, arr[0..]);
@ -3490,7 +3492,7 @@ pub fn reverseIterator(slice: anytype) ReverseIterator(@TypeOf(slice)) {
return .{ .ptr = slice.ptr, .index = slice.len }; return .{ .ptr = slice.ptr, .index = slice.len };
} }
test "reverseIterator" { test reverseIterator {
{ {
var it = reverseIterator("abc"); var it = reverseIterator("abc");
try testing.expectEqual(@as(?u8, 'c'), it.next()); try testing.expectEqual(@as(?u8, 'c'), it.next());
@ -3548,7 +3550,7 @@ pub fn rotate(comptime T: type, items: []T, amount: usize) void {
reverse(T, items); reverse(T, items);
} }
test "rotate" { test rotate {
var arr = [_]i32{ 5, 3, 1, 2, 4 }; var arr = [_]i32{ 5, 3, 1, 2, 4 };
rotate(i32, arr[0..], 2); rotate(i32, arr[0..], 2);
@ -3582,7 +3584,7 @@ pub fn replace(comptime T: type, input: []const T, needle: []const T, replacemen
return replacements; return replacements;
} }
test "replace" { test replace {
var output: [29]u8 = undefined; var output: [29]u8 = undefined;
var replacements = replace(u8, "All your base are belong to us", "base", "Zig", output[0..]); var replacements = replace(u8, "All your base are belong to us", "base", "Zig", output[0..]);
var expected: []const u8 = "All your Zig are belong to us"; var expected: []const u8 = "All your Zig are belong to us";
@ -3645,7 +3647,7 @@ fn testCollapseRepeats(str: []const u8, elem: u8, expected: []const u8) !void {
defer std.testing.allocator.free(mutable); defer std.testing.allocator.free(mutable);
try testing.expect(std.mem.eql(u8, collapseRepeats(u8, mutable, elem), expected)); try testing.expect(std.mem.eql(u8, collapseRepeats(u8, mutable, elem), expected));
} }
test "collapseRepeats" { test collapseRepeats {
try testCollapseRepeats("", '/', ""); try testCollapseRepeats("", '/', "");
try testCollapseRepeats("a", '/', "a"); try testCollapseRepeats("a", '/', "a");
try testCollapseRepeats("/", '/', "/"); try testCollapseRepeats("/", '/', "/");
@ -3679,7 +3681,7 @@ pub fn replacementSize(comptime T: type, input: []const T, needle: []const T, re
return size; return size;
} }
test "replacementSize" { test replacementSize {
try testing.expect(replacementSize(u8, "All your base are belong to us", "base", "Zig") == 29); try testing.expect(replacementSize(u8, "All your base are belong to us", "base", "Zig") == 29);
try testing.expect(replacementSize(u8, "Favor reading code over writing code.", "code", "") == 29); try testing.expect(replacementSize(u8, "Favor reading code over writing code.", "code", "") == 29);
try testing.expect(replacementSize(u8, "Only one obvious way to do things.", "things.", "things in Zig.") == 41); try testing.expect(replacementSize(u8, "Only one obvious way to do things.", "things.", "things in Zig.") == 41);
@ -3699,7 +3701,7 @@ pub fn replaceOwned(comptime T: type, allocator: Allocator, input: []const T, ne
return output; return output;
} }
test "replaceOwned" { test replaceOwned {
const gpa = std.testing.allocator; const gpa = std.testing.allocator;
const base_replace = replaceOwned(u8, gpa, "All your base are belong to us", "base", "Zig") catch @panic("out of memory"); const base_replace = replaceOwned(u8, gpa, "All your base are belong to us", "base", "Zig") catch @panic("out of memory");
@ -3803,7 +3805,7 @@ pub fn alignPointer(ptr: anytype, align_to: usize) ?@TypeOf(ptr) {
return @alignCast(ptr + adjust_off); return @alignCast(ptr + adjust_off);
} }
test "alignPointer" { test alignPointer {
const S = struct { const S = struct {
fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void { fn checkAlign(comptime T: type, base: usize, align_to: usize, expected: usize) !void {
const ptr: T = @ptrFromInt(base); const ptr: T = @ptrFromInt(base);
@ -3852,7 +3854,7 @@ pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr)) {
return @ptrCast(@alignCast(ptr)); return @ptrCast(@alignCast(ptr));
} }
test "asBytes" { test asBytes {
const deadbeef = @as(u32, 0xDEADBEEF); const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) { const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF", .big => "\xDE\xAD\xBE\xEF",
@ -3912,7 +3914,7 @@ pub fn toBytes(value: anytype) [@sizeOf(@TypeOf(value))]u8 {
return asBytes(&value).*; return asBytes(&value).*;
} }
test "toBytes" { test toBytes {
var my_bytes = toBytes(@as(u32, 0x12345678)); var my_bytes = toBytes(@as(u32, 0x12345678));
switch (native_endian) { switch (native_endian) {
.big => try testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")), .big => try testing.expect(eql(u8, &my_bytes, "\x12\x34\x56\x78")),
@ -3936,7 +3938,7 @@ pub fn bytesAsValue(comptime T: type, bytes: anytype) BytesAsValueReturnType(T,
return @ptrCast(bytes); return @ptrCast(bytes);
} }
test "bytesAsValue" { test bytesAsValue {
const deadbeef = @as(u32, 0xDEADBEEF); const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) { const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF", .big => "\xDE\xAD\xBE\xEF",
@ -3995,7 +3997,7 @@ test "bytesAsValue preserves pointer attributes" {
pub fn bytesToValue(comptime T: type, bytes: anytype) T { pub fn bytesToValue(comptime T: type, bytes: anytype) T {
return bytesAsValue(T, bytes).*; return bytesAsValue(T, bytes).*;
} }
test "bytesToValue" { test bytesToValue {
const deadbeef_bytes = switch (native_endian) { const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF", .big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE", .little => "\xEF\xBE\xAD\xDE",
@ -4023,7 +4025,7 @@ pub fn bytesAsSlice(comptime T: type, bytes: anytype) BytesAsSliceReturnType(T,
return @as(cast_target, @ptrCast(bytes))[0..@divExact(bytes.len, @sizeOf(T))]; return @as(cast_target, @ptrCast(bytes))[0..@divExact(bytes.len, @sizeOf(T))];
} }
test "bytesAsSlice" { test bytesAsSlice {
{ {
const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF }; const bytes = [_]u8{ 0xDE, 0xAD, 0xBE, 0xEF };
const slice = bytesAsSlice(u16, bytes[0..]); const slice = bytesAsSlice(u16, bytes[0..]);
@ -4112,7 +4114,7 @@ pub fn sliceAsBytes(slice: anytype) SliceAsBytesReturnType(@TypeOf(slice)) {
return @as(cast_target, @ptrCast(slice))[0 .. slice.len * @sizeOf(std.meta.Elem(Slice))]; return @as(cast_target, @ptrCast(slice))[0 .. slice.len * @sizeOf(std.meta.Elem(Slice))];
} }
test "sliceAsBytes" { test sliceAsBytes {
const bytes = [_]u16{ 0xDEAD, 0xBEEF }; const bytes = [_]u16{ 0xDEAD, 0xBEEF };
const slice = sliceAsBytes(bytes[0..]); const slice = sliceAsBytes(bytes[0..]);
try testing.expect(slice.len == 4); try testing.expect(slice.len == 4);
@ -4270,7 +4272,7 @@ fn doNotOptimizeAwayC(ptr: anytype) void {
dest.* = 0; dest.* = 0;
} }
test "doNotOptimizeAway" { test doNotOptimizeAway {
comptime doNotOptimizeAway("test"); comptime doNotOptimizeAway("test");
doNotOptimizeAway(null); doNotOptimizeAway(null);
@ -4295,7 +4297,7 @@ test "doNotOptimizeAway" {
doNotOptimizeAway(@as(std.builtin.Endian, .little)); doNotOptimizeAway(@as(std.builtin.Endian, .little));
} }
test "alignForward" { test alignForward {
try testing.expect(alignForward(usize, 1, 1) == 1); try testing.expect(alignForward(usize, 1, 1) == 1);
try testing.expect(alignForward(usize, 2, 1) == 2); try testing.expect(alignForward(usize, 2, 1) == 2);
try testing.expect(alignForward(usize, 1, 2) == 2); try testing.expect(alignForward(usize, 1, 2) == 2);
@ -4364,7 +4366,7 @@ pub fn isAlignedGeneric(comptime T: type, addr: T, alignment: T) bool {
return alignBackward(T, addr, alignment) == addr; return alignBackward(T, addr, alignment) == addr;
} }
test "isAligned" { test isAligned {
try testing.expect(isAligned(0, 4)); try testing.expect(isAligned(0, 4));
try testing.expect(isAligned(1, 1)); try testing.expect(isAligned(1, 1));
try testing.expect(isAligned(2, 1)); try testing.expect(isAligned(2, 1));

View file

@ -132,7 +132,7 @@ pub fn TrailerFlags(comptime Fields: type) type {
}; };
} }
test "TrailerFlags" { test TrailerFlags {
const Flags = TrailerFlags(struct { const Flags = TrailerFlags(struct {
a: i32, a: i32,
b: bool, b: bool,

View file

@ -1077,7 +1077,7 @@ pub fn QueryObjectName(
else => |e| return unexpectedStatus(e), else => |e| return unexpectedStatus(e),
} }
} }
test "QueryObjectName" { test QueryObjectName {
if (builtin.os.tag != .windows) if (builtin.os.tag != .windows)
return; return;
@ -1245,7 +1245,7 @@ pub fn GetFinalPathNameByHandle(
} }
} }
test "GetFinalPathNameByHandle" { test GetFinalPathNameByHandle {
if (builtin.os.tag != .windows) if (builtin.os.tag != .windows)
return; return;
@ -2467,7 +2467,7 @@ pub fn ntToWin32Namespace(path: []const u16) !PathSpace {
} }
} }
test "ntToWin32Namespace" { test ntToWin32Namespace {
const L = std.unicode.utf8ToUtf16LeStringLiteral; const L = std.unicode.utf8ToUtf16LeStringLiteral;
try testNtToWin32Namespace(L("UNC"), L("\\??\\UNC")); try testNtToWin32Namespace(L("UNC"), L("\\??\\UNC"));
@ -3386,7 +3386,7 @@ pub const GUID = extern struct {
} }
}; };
test "GUID" { test GUID {
try std.testing.expectEqual( try std.testing.expectEqual(
GUID{ GUID{
.Data1 = 0x01234567, .Data1 = 0x01234567,

View file

@ -209,7 +209,7 @@ pub const EnvMap = struct {
} }
}; };
test "EnvMap" { test EnvMap {
var env = EnvMap.init(testing.allocator); var env = EnvMap.init(testing.allocator);
defer env.deinit(); defer env.deinit();
@ -371,7 +371,7 @@ pub fn getEnvMap(allocator: Allocator) GetEnvMapError!EnvMap {
} }
} }
test "getEnvMap" { test getEnvMap {
var env = try getEnvMap(testing.allocator); var env = try getEnvMap(testing.allocator);
defer env.deinit(); defer env.deinit();
} }
@ -1132,7 +1132,7 @@ pub fn argsFree(allocator: Allocator, args_alloc: []const [:0]u8) void {
return allocator.free(aligned_allocated_buf); return allocator.free(aligned_allocated_buf);
} }
test "ArgIteratorWindows" { test ArgIteratorWindows {
const t = testArgIteratorWindows; const t = testArgIteratorWindows;
try t( try t(

View file

@ -430,7 +430,7 @@ pub fn binarySearch(
return null; return null;
} }
test "binarySearch" { test binarySearch {
const S = struct { const S = struct {
fn order_u32(context: void, lhs: u32, rhs: u32) math.Order { fn order_u32(context: void, lhs: u32, rhs: u32) math.Order {
_ = context; _ = context;
@ -537,7 +537,7 @@ pub fn lowerBound(
return left; return left;
} }
test "lowerBound" { test lowerBound {
const S = struct { const S = struct {
fn lower_u32(context: void, lhs: u32, rhs: u32) bool { fn lower_u32(context: void, lhs: u32, rhs: u32) bool {
_ = context; _ = context;
@ -627,7 +627,7 @@ pub fn upperBound(
return left; return left;
} }
test "upperBound" { test upperBound {
const S = struct { const S = struct {
fn lower_u32(context: void, lhs: u32, rhs: u32) bool { fn lower_u32(context: void, lhs: u32, rhs: u32) bool {
_ = context; _ = context;
@ -712,7 +712,7 @@ pub fn equalRange(
}; };
} }
test "equalRange" { test equalRange {
const S = struct { const S = struct {
fn lower_u32(context: void, lhs: u32, rhs: u32) bool { fn lower_u32(context: void, lhs: u32, rhs: u32) bool {
_ = context; _ = context;
@ -792,7 +792,7 @@ pub fn argMin(
return smallest_index; return smallest_index;
} }
test "argMin" { test argMin {
try testing.expectEqual(@as(?usize, null), argMin(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?usize, null), argMin(i32, &[_]i32{}, {}, asc_i32));
try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{1}, {}, asc_i32));
try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
@ -812,7 +812,7 @@ pub fn min(
return items[i]; return items[i];
} }
test "min" { test min {
try testing.expectEqual(@as(?i32, null), min(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?i32, null), min(i32, &[_]i32{}, {}, asc_i32));
try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{1}, {}, asc_i32));
try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
@ -844,7 +844,7 @@ pub fn argMax(
return biggest_index; return biggest_index;
} }
test "argMax" { test argMax {
try testing.expectEqual(@as(?usize, null), argMax(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?usize, null), argMax(i32, &[_]i32{}, {}, asc_i32));
try testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{1}, {}, asc_i32));
try testing.expectEqual(@as(?usize, 4), argMax(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 4), argMax(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
@ -864,7 +864,7 @@ pub fn max(
return items[i]; return items[i];
} }
test "max" { test max {
try testing.expectEqual(@as(?i32, null), max(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?i32, null), max(i32, &[_]i32{}, {}, asc_i32));
try testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{1}, {}, asc_i32));
try testing.expectEqual(@as(?i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));
@ -890,7 +890,7 @@ pub fn isSorted(
return true; return true;
} }
test "isSorted" { test isSorted {
try testing.expect(isSorted(i32, &[_]i32{}, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{}, {}, asc_i32));
try testing.expect(isSorted(i32, &[_]i32{10}, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{10}, {}, asc_i32));
try testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32));

View file

@ -676,7 +676,7 @@ fn stripComponents(path: []const u8, count: u32) []const u8 {
return path[i..]; return path[i..];
} }
test "stripComponents" { test stripComponents {
const expectEqualStrings = testing.expectEqualStrings; const expectEqualStrings = testing.expectEqualStrings;
try expectEqualStrings("a/b/c", stripComponents("a/b/c", 0)); try expectEqualStrings("a/b/c", stripComponents("a/b/c", 0));
try expectEqualStrings("b/c", stripComponents("a/b/c", 1)); try expectEqualStrings("b/c", stripComponents("a/b/c", 1));
@ -685,7 +685,7 @@ test "stripComponents" {
try expectEqualStrings("", stripComponents("a/b/c", 4)); try expectEqualStrings("", stripComponents("a/b/c", 4));
} }
test "PaxIterator" { test PaxIterator {
const Attr = struct { const Attr = struct {
kind: PaxAttributeKind, kind: PaxAttributeKind,
value: []const u8 = undefined, value: []const u8 = undefined,

View file

@ -242,7 +242,7 @@ fn expectApproxEqAbsInner(comptime T: type, expected: T, actual: T, tolerance: T
} }
} }
test "expectApproxEqAbs" { test expectApproxEqAbs {
inline for ([_]type{ f16, f32, f64, f128 }) |T| { inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const pos_x: T = 12.0; const pos_x: T = 12.0;
const pos_y: T = 12.06; const pos_y: T = 12.06;
@ -278,7 +278,7 @@ fn expectApproxEqRelInner(comptime T: type, expected: T, actual: T, tolerance: T
} }
} }
test "expectApproxEqRel" { test expectApproxEqRel {
inline for ([_]type{ f16, f32, f64, f128 }) |T| { inline for ([_]type{ f16, f32, f64, f128 }) |T| {
const eps_value = comptime math.floatEps(T); const eps_value = comptime math.floatEps(T);
const sqrt_eps_value = comptime @sqrt(eps_value); const sqrt_eps_value = comptime @sqrt(eps_value);

View file

@ -52,7 +52,7 @@ pub fn sleep(nanoseconds: u64) void {
std.os.nanosleep(s, ns); std.os.nanosleep(s, ns);
} }
test "sleep" { test sleep {
sleep(1); sleep(1);
} }
@ -122,7 +122,7 @@ pub fn nanoTimestamp() i128 {
} }
} }
test "timestamp" { test milliTimestamp {
const margin = ns_per_ms * 50; const margin = ns_per_ms * 50;
const time_0 = milliTimestamp(); const time_0 = milliTimestamp();
@ -326,7 +326,7 @@ pub const Timer = struct {
} }
}; };
test "Timer + Instant" { test Timer {
const margin = ns_per_ms * 150; const margin = ns_per_ms * 150;
var timer = try Timer.start(); var timer = try Timer.start();

View file

@ -53,7 +53,7 @@ pub fn isLeapYear(year: Year) bool {
return (0 == @mod(year, 400)); return (0 == @mod(year, 400));
} }
test "isLeapYear" { test isLeapYear {
try testing.expectEqual(false, isLeapYear(2095)); try testing.expectEqual(false, isLeapYear(2095));
try testing.expectEqual(true, isLeapYear(2096)); try testing.expectEqual(true, isLeapYear(2096));
try testing.expectEqual(false, isLeapYear(2100)); try testing.expectEqual(false, isLeapYear(2100));

View file

@ -907,7 +907,7 @@ pub fn fmtUtf8(utf8: []const u8) std.fmt.Formatter(formatUtf8) {
return .{ .data = utf8 }; return .{ .data = utf8 };
} }
test "fmtUtf8" { test fmtUtf8 {
const expectFmt = testing.expectFmt; const expectFmt = testing.expectFmt;
try expectFmt("", "{}", .{fmtUtf8("")}); try expectFmt("", "{}", .{fmtUtf8("")});
try expectFmt("foo", "{}", .{fmtUtf8("foo")}); try expectFmt("foo", "{}", .{fmtUtf8("foo")});
@ -1249,7 +1249,7 @@ pub fn utf8ToUtf16LeImpl(utf16le: []u16, utf8: []const u8, comptime surrogates:
return dest_index; return dest_index;
} }
test "utf8ToUtf16Le" { test utf8ToUtf16Le {
var utf16le: [128]u16 = undefined; var utf16le: [128]u16 = undefined;
{ {
const length = try utf8ToUtf16Le(utf16le[0..], "𐐷"); const length = try utf8ToUtf16Le(utf16le[0..], "𐐷");
@ -1430,7 +1430,7 @@ pub fn fmtUtf16Le(utf16le: []const u16) std.fmt.Formatter(formatUtf16Le) {
return .{ .data = utf16le }; return .{ .data = utf16le };
} }
test "fmtUtf16Le" { test fmtUtf16Le {
const expectFmt = testing.expectFmt; const expectFmt = testing.expectFmt;
try expectFmt("", "{}", .{fmtUtf16Le(utf8ToUtf16LeStringLiteral(""))}); try expectFmt("", "{}", .{fmtUtf16Le(utf8ToUtf16LeStringLiteral(""))});
try expectFmt("foo", "{}", .{fmtUtf16Le(utf8ToUtf16LeStringLiteral("foo"))}); try expectFmt("foo", "{}", .{fmtUtf16Le(utf8ToUtf16LeStringLiteral("foo"))});
@ -1443,7 +1443,7 @@ test "fmtUtf16Le" {
try expectFmt("", "{}", .{fmtUtf16Le(&[_]u16{mem.readInt(u16, "\x00\xe0", native_endian)})}); try expectFmt("", "{}", .{fmtUtf16Le(&[_]u16{mem.readInt(u16, "\x00\xe0", native_endian)})});
} }
test "utf8ToUtf16LeStringLiteral" { test utf8ToUtf16LeStringLiteral {
{ {
const bytes = [_:0]u16{ const bytes = [_:0]u16{
mem.nativeToLittle(u16, 0x41), mem.nativeToLittle(u16, 0x41),

View file

@ -137,7 +137,7 @@ pub fn countLeaks() CountResult {
return res; return res;
} }
test "countLeaks" { test countLeaks {
try testing.expectEqual( try testing.expectEqual(
@as(CountResult, .{ @as(CountResult, .{
.leaked = 0, .leaked = 0,
@ -167,7 +167,7 @@ pub fn countLeakBlocks() CountResult {
return res; return res;
} }
test "countLeakBlocks" { test countLeakBlocks {
try testing.expectEqual( try testing.expectEqual(
@as(CountResult, .{ @as(CountResult, .{
.leaked = 0, .leaked = 0,

View file

@ -642,9 +642,8 @@ pub const Wip = struct {
i += 1; i += 1;
} }
} }
};
test "addBundleAsRoots" { test addBundleAsRoots {
var bundle = bundle: { var bundle = bundle: {
var wip: ErrorBundle.Wip = undefined; var wip: ErrorBundle.Wip = undefined;
try wip.init(std.testing.allocator); try wip.init(std.testing.allocator);
@ -735,3 +734,4 @@ test "addBundleAsRoots" {
try std.testing.expectEqualStrings(bundle_buf.items, copy_buf.items); try std.testing.expectEqualStrings(bundle_buf.items, copy_buf.items);
} }
};

View file

@ -51,7 +51,7 @@ pub fn isPrimitive(name: []const u8) bool {
return true; return true;
} }
test "isPrimitive" { test isPrimitive {
const expect = std.testing.expect; const expect = std.testing.expect;
try expect(!isPrimitive("")); try expect(!isPrimitive(""));
try expect(!isPrimitive("_")); try expect(!isPrimitive("_"));

View file

@ -148,7 +148,7 @@ pub fn parseEscapeSequence(slice: []const u8, offset: *usize) ParsedCharLiteral
} }
} }
test "parseCharLiteral" { test parseCharLiteral {
try std.testing.expectEqual( try std.testing.expectEqual(
ParsedCharLiteral{ .success = 'a' }, ParsedCharLiteral{ .success = 'a' },
parseCharLiteral("'a'"), parseCharLiteral("'a'"),
@ -281,7 +281,7 @@ pub fn parseAlloc(allocator: std.mem.Allocator, bytes: []const u8) ParseError![]
} }
} }
test "parse" { test parseAlloc {
const expect = std.testing.expect; const expect = std.testing.expect;
const expectError = std.testing.expectError; const expectError = std.testing.expectError;
const eql = std.mem.eql; const eql = std.mem.eql;