| ... | @@ -996,6 +996,43 @@ test "mem.join" { | ... | @@ -996,6 +996,43 @@ test "mem.join" { |
| 996 | testing.expect(eql(u8, try join(a, ",", [_][]const u8{ "a", "", "b", "", "c" }), "a,,b,,c")); | 996 | testing.expect(eql(u8, try join(a, ",", [_][]const u8{ "a", "", "b", "", "c" }), "a,,b,,c")); |
| 997 | } | 997 | } |
| 998 | | 998 | |
| | 999 | /// Copies each T from slices into a new slice that exactly holds all the elements. |
| | 1000 | pub fn concat(allocator: *Allocator, comptime T: type, slices: []const []const T) ![]T { |
| | 1001 | if (slices.len == 0) return (([*]T)(undefined))[0..0]; |
| | 1002 | |
| | 1003 | const total_len = blk: { |
| | 1004 | var sum: usize = 0; |
| | 1005 | for (slices) |slice| { |
| | 1006 | sum += slice.len; |
| | 1007 | } |
| | 1008 | break :blk sum; |
| | 1009 | }; |
| | 1010 | |
| | 1011 | const buf = try allocator.alloc(T, total_len); |
| | 1012 | errdefer allocator.free(buf); |
| | 1013 | |
| | 1014 | var buf_index: usize = 0; |
| | 1015 | for (slices) |slice| { |
| | 1016 | copy(T, buf[buf_index..], slice); |
| | 1017 | buf_index += slice.len; |
| | 1018 | } |
| | 1019 | |
| | 1020 | // No need for shrink since buf is exactly the correct size. |
| | 1021 | return buf; |
| | 1022 | } |
| | 1023 | |
| | 1024 | test "concat" { |
| | 1025 | var buf: [1024]u8 = undefined; |
| | 1026 | const a = &std.heap.FixedBufferAllocator.init(&buf).allocator; |
| | 1027 | testing.expect(eql(u8, try concat(a, u8, [_][]const u8{ "abc", "def", "ghi" }), "abcdefghi")); |
| | 1028 | testing.expect(eql(u32, try concat(a, u32, [_][]const u32{ |
| | 1029 | [_]u32{ 0, 1 }, |
| | 1030 | [_]u32{ 2, 3, 4 }, |
| | 1031 | [_]u32{}, |
| | 1032 | [_]u32{5}, |
| | 1033 | }), [_]u32{ 0, 1, 2, 3, 4, 5 })); |
| | 1034 | } |
| | 1035 | |
| 999 | test "testStringEquality" { | 1036 | test "testStringEquality" { |
| 1000 | testing.expect(eql(u8, "abcd", "abcd")); | 1037 | testing.expect(eql(u8, "abcd", "abcd")); |
| 1001 | testing.expect(!eql(u8, "abcdef", "abZdef")); | 1038 | testing.expect(!eql(u8, "abcdef", "abZdef")); |