#How to get an index in a slice given its subslice?

1 messages · Page 1 of 1 (latest)

proud kettle
#

Do you think this is a good (reliable) way to get an end index of the sub slice?

const std = @import("std");

pub fn main() !void {
    const slice = "hello world!";
    const sub = slice[6..8];
    std.log.debug("slice:   {s}", .{slice});
    std.log.debug("sub:     {s}", .{sub});
    std.log.debug("sub end: {d}", .{(@intFromPtr(sub.ptr) + sub.len) - @intFromPtr(slice.ptr)}); // also works without using *.ptr
}

output:

debug: slice:   hello world!
debug: sub:     wo
debug: sub end: 8
sharp haven
#

Well sub's end index is 1, not 8

#

11 is the end index of slice

#

Or I don't understand what you're trying to do

zenith cipher
proud kettle
sharp haven
#

You mean in relation to slice, I was not sure tha'ts what you meant

proud kettle
proud kettle
sharp haven
#

By end you mean the last index that's part of the slice, or one position after?

#

So maybe like this? subtract one then add one?
std.debug.print("sub end: {d}", .{@intFromPtr(&sub[sub.len - 1]) - @intFromPtr(&slice[0]) + 1});

zenith cipher
sharp haven
#

It's a bit more verbose though at least in my mind captures the intention better.

safe socket
#

we do have pointer subtraction now, so it's just sub.ptr + sub.len - slice.ptr

proud kettle
safe socket
#

probably not released yet

proud kettle
#

:)

safe socket
#

yeah not in 0.13.0

proud kettle