Stream: t-lang/wg-unsafe-code-guidelines

Topic: create ptr to elem in unaligned array

gnzlbg (May 23 2019 at 19:26, on Zulip):


Given x: *const [T], how would I write the equivalent of &raw mut (*x)[i]?

How would you do that with raw ? AFAICT, the array itself [T] can be at an unaligned memory location (that is the len and the ptr of the [T] are not properly aligned), and (*x)[i] creates a &self, which would be invalid right ?

RalfJ (May 23 2019 at 19:49, on Zulip):

why would that create a &self?

gnzlbg (May 23 2019 at 19:51, on Zulip):

@RalfJ because the <[T] as IndexMut>::index_mut(&mut self) method is called, or isn't it?

gnzlbg (May 23 2019 at 19:53, on Zulip):

I read &raw mut (*x)[i] as &raw mut <[T] as IndexMut>::index_mut(*x: &mut [T], i)

gnzlbg (May 23 2019 at 19:54, on Zulip):

or am I reading the parenthesis wrong, and that should be <[T] as IndexMut>::index_mut(*x: &raw mut [T], i) ?

gnzlbg (May 23 2019 at 19:55, on Zulip):

or do we have an IndexRawMut::index_raw_mut(x: &raw mut self, i: usize) API ?

gnzlbg (May 23 2019 at 19:56, on Zulip):

as in, (&raw mut (*x))[i] expands to <[T] as IndexRawMut>::index_raw_mut(&raw mut (*x), i): &raw mut T ?

rkruppe (May 23 2019 at 21:51, on Zulip):

I thought this was a hypothetical IndexRawMut overload of the indexing operator for raw pointer slices

RalfJ (May 24 2019 at 07:58, on Zulip):

IndexMut does not get called when indexing a raw slice with a usize

RalfJ (May 24 2019 at 07:58, on Zulip):

(and we dont support indexing them with anything else)

gnzlbg (May 24 2019 at 16:28, on Zulip):

So what gets called ?

gnzlbg (May 24 2019 at 16:29, on Zulip):

The only thing I can think of is the _hypothetical_ IndexRawMut trait that @rkruppe mentions.

rkruppe (May 24 2019 at 16:30, on Zulip):

IIUC Ralf is saying nothing gets called, it's a compiler built-in

rkruppe (May 24 2019 at 16:30, on Zulip):

That sounds plausible

gnzlbg (May 24 2019 at 16:31, on Zulip):

So it wouldn't be a #[lang_item] + unstable trait in libcore ? (implementation-wise)

gnzlbg (May 24 2019 at 16:32, on Zulip):

otherwise it would need to be implemented fairly different than [] overloads for all other types

rkruppe (May 24 2019 at 16:34, on Zulip):

This is no different to how impl Add for i32 ends up boiling down to just return self + rhs. Injecting built-in operations that precedes the general trait based overloading isn't super difficult.

RalfJ (May 24 2019 at 16:38, on Zulip):

indeed. MIR has a primitive operator to index a slice (works for raw slices and reference slices), just like it has a primitive operator for addition.

Last update: Jul 02 2020 at 13:45UTC