Dan Salvato
Dan Salvato

Reputation: 31

Further slicing of an existing slice always results in the same data, regardless of slice position

I'm new to Zig (using 0.9.1 stable) and have had some trouble effectively slicing an array at compile time.

const some_file = @embedFile("filepath.bin");
const data_section = some_file[0x1000..0x2000];

// This has the correct data
const data1 = data_section[0x000..0x100];

// These are identical to data1?
const data2 = data_section[0x100..0x200];
const data2b = data_section.*[0x100..0x200];

I worked around this by omitting data_section:

const some_file = @embedFile("filepath.bin");
const data_offset = 0x1000;
const data_length = 0x1000;

const data1 = some_file[data_offset..data_offset + 0x100];
const data2 = some_file[data_offset + 0x100..data_offset + 0x200];

These all appear to resolve to type []const u8, but I'm baffled as to why in the first example, data1 and data2 would contain the exact same data. It would result in somewhat cleaner and more concise code to go with the first example.

Since I'm new, I wouldn't be surprised if I was misunderstanding something about arrays and slices, but the above was very non-intuitive and left me stumped for a while, because I couldn't figure out which part of my code was causing all data blocks to be identical to the first one. Why does the first example behave like that?

Upvotes: 0

Views: 357

Answers (2)

Dan Salvato
Dan Salvato

Reputation: 31

I confirmed that this is a Zig compiler bug: https://github.com/ziglang/zig/issues/10684

A fix is targeted for 0.11.0.

Upvotes: 3

Ali Chraghi
Ali Chraghi

Reputation: 829

the slicing syntax in 2th example is wrong (slice[x, y]). you must use the three dots syntax, just like your first example.

corrected code:

const some_file = @embedFile("filepath.bin");
const data_offset = 0x1000;
const data_length = 0x1000;

const data1 = some_file[data_offset..data_offset + 0x100];
const data2 = some_file[data_offset + 0x100..data_offset + 0x200];

Upvotes: 0

Related Questions