authorgravatar for thejoshwolfe@gmail.comJosh Wolfe <thejoshwolfe@gmail.com> 2019-06-17 00:03:16-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2019-06-17 01:41:33-04:00
log50c8a93a5e2313ffb4183894637ecbd7f4dc50fa
treeb92d0e371e1244bdb6396de3c27f02df690974ee
parent6ce2a03985db3094634742ae2209477de998e70a

mem.concat


1 files changed, 37 insertions(+), 0 deletions(-)

std/mem.zig+37
...@@ -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}
998998
999/// Copies each T from slices into a new slice that exactly holds all the elements.
1000pub 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
1024test "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
999test "testStringEquality" {1036test "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"));