tmp.zig (1410B)
1 const std = @import("std"); 2 3 test "slices" { 4 // option 1 slices 5 const a = std.testing.allocator; 6 var words_al = std.ArrayList([]const u8).init(a); 7 defer words_al.deinit(); 8 var toks = std.mem.tokenizeAny(u8, wordlist, "\n "); 9 while (toks.next()) |tok| { 10 try words_al.append(tok); 11 } 12 const words: []const[]const u8 = try words_al.toOwnedSlice(); // a slice is a pointer + length (so 2 x usize x length) 13 defer a.free(words); 14 15 try std.testing.expectEqualStrings("bar", words[1]); // words accessed by index 16 } 17 18 test "offsets" { 19 // option 2 offsets 20 const a = std.testing.allocator; 21 var offsets_al = std.ArrayList(u16).init(a); 22 defer offsets_al.deinit(); 23 try offsets_al.append(0); 24 for (wordlist, 0..) |ch,ix| { 25 if (ch == '\n' and ix < wordlist.len) { 26 try offsets_al.append(@intCast(ix+1)); // we know we have less than 2^16 words 27 } 28 } 29 const offsets = try offsets_al.toOwnedSlice(); // offsets are just u16 x length, so ~4x less memory on 64 bit systems. 30 defer a.free(offsets); 31 // words accessed by slicing wordlist using offsets 32 // be careful of edge cases i.e. accessing the last word in the list, not handled here. 33 const word = wordlist[offsets[1]..(offsets[2]-1)]; 34 try std.testing.expectEqualStrings("bar", word); 35 } 36 37 const wordlist: []const u8 = 38 \\foo 39 \\bar 40 \\baz 41 \\I 42 \\like 43 \\cheese 44 ;