# \[Idea\] Pointer to Field

**URL:** <https://internals.rust-lang.org/t/idea-pointer-to-field/10061>\
**Category:** Unsafe Code Guidelines\
**Created:** [May 8, 2019, 6:59pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061 "2019-05-08T18:59:00Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 6:59pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/1 "2019-05-08T18:59:00Z")

</div>

This discussion was started from

> [@Need for -\> operator for Unsafe Code Guidelines](https://internals.rust-lang.org/t/need-for-operator-for-unsafe-code-guidelines/10022):
>
> I lost a long detailed draft of this, so I’ll keep it short this time. In my experience, the two most common miri-caught violations of the Unsafe Code Guidelines we have are: [We materialize or hold onto a too-large reference when working with raw pointers](https://github.com/rust-lang/rust/pull/60072)[We mess up pointer alignment in low-level code, often in niche cases like with ZSTs](https://github.com/rust-lang/rust/issues/54908) This post is about the former. I am bothered by the former because it tends to be the consequence of a common problem: it’s a pain in the neck to offset a ra…

But is a bit off topic there, so I started a new thread for it

This is the third edit of this draft, to see previous versions check out the pencil in the top corner

In order to make safe pointer to fields

```rust
struct Field<Parent, Type> {
    offset: usize
}

```

which is auto-generated by the compiler like so

```rust
struct Foo {
    bar: u32,
    quaz: i8
}

fn main() {
    assert_eq!(Foo::bar, Field::<Foo, u32> { offset: 0 });
    assert_eq!(Foo::quaz, Field::<Foo, i8> { offset: 4 }); // (assuming fields aren't reordered by compiler)
}

```

The syntax for this not important (i.e. `Foo::bar` could be changed to something else)

- Another idea for syntax is `Type.field`, this has the benefit of being unambigious

We could then declare it safe to use these fields offsets to project _valid_ pointers to fields like so we could provide something like this

```rust
// Always safe to project using this trait given that `self` and `field` are valid
trait Project<FTy> {
    type Type;
    type Projection;
    
    fn project(self, field: Field<Self::Type, FTy>) -> Self::Projection;
}

impl<T, FTy> *const T {
    unsafe fn project_inbounds<FTy>(self, field: Field<T, FTy>) -> *const FTy {
        (self as *const _ as *const u8)
            .add(field.offset) as *const FTy
    }
}

impl<T, FTy> Project<FTy> for *const T {
    type Type = T;
    type Projection = *const FTy;
    
    fn project(self, field: Field<T, FTy>) -> Self::Projection {
        (self as *const _ as *const u8)
            .wrapping_add(field.offset) as *const FTy
    }
}

impl<'a, T, FTy: 'a> Project<FTy> for &'a T {
    type Type = T;
    type Projection = &'a FTy;
    
    fn project(self, field: Field<T, FTy>) -> Self::Projection {
        unsafe { &*(self as *const _).project_inbounds(field) }
    }
}

```

Which could then be used generically to project to a field.

playground example:

> **[Rust Playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2018&gist=762d05ce656957ad28072cca3bcf80bd)**
>
> A browser interface to the Rust compiler to experiment with the language

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 8, 2019, 7:42pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/2 "2019-05-08T19:42:23Z")

</div>

> [@RustyYato](#):
>
> We could then declare it safe to use these offsets to project pointers to fields like so we could provide something like this

Not really. Projection on pointers _must_ be unsafe since they do not assert that the structure to project upon is actually pointed to. But maybe the converse could be true, one trait that exposes it as an `unsafe fn` and another subtrait that declares it safe.

Why would `Field` need to be a trait? It's an internal so I think a `const` enabled struct could suffice. That would buy us stricter typing over `usize` and a value representation that one would be used-to from `T::*U`. Or alternative, it could be a trait with an associated `constant` with such a type:

```rust
/// Internal, const constructed by the syntax `Foo::bar` or equivalent.
struct Field<Parent, Child> {
    offset: usize,
}

trait Project<T> {
    type Type;
    type Projection;
    fn project(self, field: Field<Self::Type, T>) -> Self::Project;
}

```

This is more like what went through my head [previously](https://internals.rust-lang.org/t/need-for-operator-for-unsafe-code-guidelines/10022/39). But `Type` appearing as associated `type` in the trait locks `Self` into choosing one base type, this is most likely a plus.

---

<div class="post-metadata">

**Author:** ![mcy](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/mcy/32/6512_2.png) [@mcy](https://internals.rust-lang.org/u/mcy)\
**Post date:** [May 8, 2019, 7:53pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/3 "2019-05-08T19:53:39Z")

</div>

I suspect that you need an unsafe variant of `Project`, since projecting through a raw pointer is always unsafe.

I do wonder if we should introduce bounds like `T: ?unsafe Trait`, which allows the impl of `Trait` for `T` to use `unsafe fn`s whre safe `fn`s are required. (By generalization, `T: const Trait`, requiring the implementation to use `const fn`s.)

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 8:22pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/4 "2019-05-08T20:22:57Z")

</div>

> [@197g](#):
>
> Not really. Projection on pointers _must_ be unsafe since they do not assert that the structure to project upon is actually pointed to. But maybe the converse could be true, one trait that exposes it as an `unsafe fn` and another subtrait that declares it safe.

Ok, I wasn't aware of that. The sub-trait solution does seem acceptable though.

> [@197g](#):
>
> Why would `Field` need to be a trait? It’s an internal so I think a `const` enabled struct could suffice. That would buy us stricter typing over `usize` and a value representation that one would be used-to from `T::*U` . Or alternative, it could be a trait with an associated `constant` with such a type:

I was thinking that you could use it to make some generic libraries that operate on the fields of types. But if that is not necessary or wouldn't work, that's fine. I wrote this up as a draft, so I am expecting changes.

> [@197g](#):
>
> ```rust
> /// Internal, const constructed by the syntax `Foo::bar` or equivalent.
> struct Field<Parent, Child> {
> offset: usize,
> }
> 
> trait Project<T> {
> type Type;
> type Projection;
> fn project(self, field: Field<Self::Type, T>) -> Self::Project;
> }
> 
> ```

How would you impl `Project`? For example could you do it for `&T`?

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 8:24pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/5 "2019-05-08T20:24:12Z")

</div>

> [@mcy](#):
>
> I suspect that you need an unsafe variant of `Project` , since projecting through a raw pointer is always unsafe.

I've seen this in a few places, but I don't understand why this is the case, could explain it please? I think that projecting through a raw pointer to a field should be safe, at least the docs for offset seems to say that it is safe to offset a pointer as long as you stay within the size of the pointee + 1 byte. This should always be true for field offsets.

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 8, 2019, 8:49pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/6 "2019-05-08T20:49:14Z")

</div>

> [@RustyYato](#):
>
> How would you impl `Project` ? For example could you do it for `&T` ?

By providing the basic pointer method on the `Field` type.

```rust
// Forgot: this type should likely be Clone + Copy
impl<P, C> Field<P, C> {
    /// Or even an intrinsic internally? Don't need to know or care
    ///
    /// Some probably decenty long list of preconditions, ...
    pub unsafe fn offset_ptr(self, ptr: *const P) -> *const C {
        let ptr = ptr as *const u8;
        let field = ptr.offset(F::OFFSET);
        field as *const F::Type
    }
}

impl<'a, T: ?Sized> Project<U> for &'a T {
    type Type = T;
    type Projection = &'a U;
    fn project(self, field: Field<T, U>) -> Self::Projection {
        // SAFETY: some text about how this fulfills the preconditions.
        unsafe { &*field.offset_ptr(self) }
    }
}

```

Part of the reason for doing it this way is that no stability guarantees about `OFFSET` itself are made. Only about the pointer operation, under a number of preconditions that are additionally listed at the definition of `offset_ptr`. And it doesn't suggest that doing manual byte pointer offsetting is a good idea, because really it is never unless you have to yourself and it can not be put behind a `core` implementation.

---

<div class="post-metadata">

**Author:** ![197g](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/197g/32/7276_2.png) [@197g](https://internals.rust-lang.org/u/197g)\
**Post date:** [May 8, 2019, 8:52pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/7 "2019-05-08T20:52:13Z")

</div>

> [@RustyYato](#):
>
> I’ve seen this in a few places, but I don’t understand why this is the case, could explain it please?

I can also explain, the pointer could be such that the pointer to field has no representation (i.e. overflows addressable memory). A pointer does not need to guarantee that an object of the size of its referent could be placed at its location.

(A bit more even, I think it is technically undefined behaviour if you offset a pointer that was constructed from a reference such that it points outside the region where the original one comes from–and I don't know if you are even allowed to have others. Pointers are allowed to track their underlying reference in llvm. Also, answer likely depends on resolution of the [`unsafe guidelines`](https://github.com/rust-lang/unsafe-code-guidelines). [This one in particular is interesting](https://github.com/rust-lang/unsafe-code-guidelines/issues/93))

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 8:52pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/8 "2019-05-08T20:52:38Z")

</div>

Ok, that seems like a good idea, I like the idea of hiding the actual offset. That does seem like a good idea.

---

<div class="post-metadata">

**Author:** ![eaglgenes101](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eaglgenes101/32/4645_2.png) [@eaglgenes101](https://internals.rust-lang.org/u/eaglgenes101)\
**Post date:** [May 8, 2019, 8:54pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/9 "2019-05-08T20:54:16Z")

</div>

You can throw a pointer absolutely anywhere, and it’s considered safe. Only actually dereferencing it is considered unsafe.

```rust
// Creates a perfectly well-formed pointer, which just happens to point into the middle of nowhere
let x: *const char = 0x0FE203FE203FE203_usize as *const char;

```

So no need to have an unsafe version for raw pointers. No dereferencing is going on in this suggestion, just arithmetic on addresses.

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 8:59pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/10 "2019-05-08T20:59:31Z")

</div>

Instead of an intrinsic, we could simply provide an impl of `Project` for `*const T`/`*mut T` and have everyone else base their `Project` off of that.

```rust
/// Projections may be unsafe, don't use this directly in generic code
trait Project<T> {
    type Type;
    type Projection;
    
    unsafe fn project(self, field: Field<Self::Type, T>) -> Self::Projection;
}

/// Projection is always safe
unsafe trait SafeProjection<T>: Project<T> {}

impl<F, T> Project<F> for *const T {
    type Type = T;
    type Projection = *const F;
    
    unsafe fn project(self, field: Field<T, F>) -> *const F {
        (self as *const u8).offset(field.offset) as *const F
    }
}

impl<'a, T, F> Project<F> for &'a T {
    type Type = T;
    type Projection = &'a F;
    
    unsafe fn project(self, field: Field<T, F>) -> &'a F {
        &*(self as *const T).project(field)
    }
}

unsafe impl<T, F> SafeProjection<F> for &'a T {}

```

---

<div class="post-metadata">

**Author:** ![matt1985](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/matt1985/32/4772_2.png) [@matt1985](https://internals.rust-lang.org/u/matt1985)\
**Post date:** [May 8, 2019, 9:00pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/11 "2019-05-08T21:00:26Z")

</div>

With const-generics,a trait to get the offset of a field could be defined like this(requiring no new syntax):

```rust
unsafe trait FieldOffset<const NAME:&'static str> {
    /// Type of the field
    type Type;
    /// The offset of the field inside the parent
    const OFFSET: usize;
}

struct Foo<'a>{
    bar:u32,
    baz:&'a str
}

// Compiler defined
impl<'a> FieldOffset<"bar"> for Foo<'a>{
    type Type=u32;
    const OFFSET=0;
}

// Compiler defined
impl<'a> FieldOffset<"baz"> for Foo<'a>{
    type Type=&'a str;
    const OFFSET=4;
}

```

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 9:01pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/12 "2019-05-08T21:01:32Z")

</div>

I’m a bit worried about using stringly typed things, especially for unsafe code.

---

<div class="post-metadata">

**Author:** ![matt1985](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/matt1985/32/4772_2.png) [@matt1985](https://internals.rust-lang.org/u/matt1985)\
**Post date:** [May 8, 2019, 9:08pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/13 "2019-05-08T21:08:10Z")

</div>

Why?Those impls are compiler generated,an if you mistype the strings it would just fail to compile.

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 9:09pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/14 "2019-05-08T21:09:51Z")

</div>

These are just normal traits, so anyone could implement them. Also, strings don’t work well with IDEs, so, I would prefer not to use them.

More importantly, this would make fields names part of the public interface for all types. This is bad. With syntax, we could fields being accessed where they are not allowed to be accessed. (maintaining privacy rules)

---

<div class="post-metadata">

**Author:** ![matt1985](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/matt1985/32/4772_2.png) [@matt1985](https://internals.rust-lang.org/u/matt1985)\
**Post date:** [May 8, 2019, 9:14pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/15 "2019-05-08T21:14:04Z")

</div>

> With syntax, we could fields being accessed where they are not allowed to be accessed. (maintaining privacy rules)

Ah ok,hadn't though about how this feature interacts with privacy.

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 9:36pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/16 "2019-05-08T21:36:53Z")

</div>

I have made some updates to the original post. I split `Project` into an `unsafe`/safe versions and changed over to using a compiler generated type instead of a trait.

---

<div class="post-metadata">

**Author:** ![eaglgenes101](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eaglgenes101/32/4645_2.png) [@eaglgenes101](https://internals.rust-lang.org/u/eaglgenes101)\
**Post date:** [May 8, 2019, 9:57pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/17 "2019-05-08T21:57:13Z")

</div>

I’m still not clear on why this is unsafe on raw pointers. What unsoundness could result from this if `Project` and `UnsafeProject` were separated? From what I can tell, getting a raw pointer to field ends up just boiling down to a bit of arithmetic on addresses and a typecast (to another raw pointer), neither of which are considered unsafe.

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 9:59pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/18 "2019-05-08T21:59:22Z")

</div>

> [@\[Idea\] Pointer to Field](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/7):
>
> I can also explain, the pointer could be such that the pointer to field has no representation (i.e. overflows addressable memory). A pointer does not need to guarantee that an object of the size of its referent could be placed at its location. (A bit more even, I think it is technically undefined behaviour if you offset a pointer that was constructed from a reference such that it points outside the region where the original one comes from–and I don't know if you are even allowed to have others…

Basically we want to use `ptr::offset`, but offsetting past `usize::max_value()` is UB, and we can create a raw pointer anywhere, which means that it isn't safe to project raw pointers in general.

> **[pointer - Rust](https://doc.rust-lang.org/std/primitive.pointer.html#method.offset)**
>
> Raw, unsafe pointers, \`\*const T\`, and \`\*mut T\`.

> The offset being in bounds cannot rely on "wrapping around" the address space. That is, the infinite-precision sum, **in bytes** must fit in a usize.

---

<div class="post-metadata">

**Author:** ![eaglgenes101](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/eaglgenes101/32/4645_2.png) [@eaglgenes101](https://internals.rust-lang.org/u/eaglgenes101)\
**Post date:** [May 8, 2019, 10:02pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/19 "2019-05-08T22:02:31Z")

</div>

I was under the impression that raw pointer offsetting followed `usize` overflow rules in either diverging or performing two’s compliment wraparound. Is this just incidental behavior, or is it documented as an intentional decision somewhere?

---

<div class="post-metadata">

**Author:** ![RustyYato](https://sea2.discourse-cdn.com/flex002/user_avatar/internals.rust-lang.org/rustyyato/32/13627_2.png) [@RustyYato](https://internals.rust-lang.org/u/RustyYato)\
**Post date:** [May 8, 2019, 10:03pm UTC](https://internals.rust-lang.org/t/idea-pointer-to-field/10061/20 "2019-05-08T22:03:24Z")

</div>

This is likely incidental behavior, because it is stated to be UB in the docs, you can use `wrapping_offset` if you want that behavior

[Next page](https://internals.rust-lang.org/t/idea-pointer-to-field/10061.md?page=2)
