# Is it safe to cast \`ptr::from\_raw\_parts()\` to \`\*mut T\`?

**URL:** <https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389>\
**Category:** help\
**Created:** [July 15, 2021, 11:16pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389 "2021-07-15T23:16:13Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![chrefr](https://avatars.discourse-cdn.com/v4/letter/c/e480ec/32.png) [@chrefr](https://users.rust-lang.org/u/chrefr)\
**Post date:** [July 15, 2021, 11:16pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/1 "2021-07-15T23:16:13Z")

</div>

I'm talking when **it was derived from a `&mut` reference**.

Usually, it's safe to cast a const raw pointer derived from a mutable reference to a mut pointer. This can be used to share common code between `&self` and `&mut self` methods. For example:

```rust
impl<T: ?Sized> Something<T> {
    pub fn get_ptr(this: *const Self) -> *const T {
        // Just an example
        this as *const T
    }
    pub fn get(&self) -> &T { unsafe { &*Self::get_ptr(self) } }
    pub fn get_mut(&mut self) -> &mut T { unsafe { &mut *(Self::get_ptr(self as *mut Self) as *mut T) } }
}

```

Is it also valid when the `get_ptr()` function compose the pointer using the nightly [`std::ptr::from_raw_parts()`](https://doc.rust-lang.org/std/ptr/fn.from_raw_parts.html) or that the cycle breaks there, and I need `from_raw_parts_mut()`?

A similar question applies to [`std::ptr::addr_of!()`](https://doc.rust-lang.org/std/ptr/macro.addr_of.html) and [`std::ptr::addr_of_mut!()`](https://doc.rust-lang.org/std/ptr/macro.addr_of_mut.html).

If possible, I'd prefer sources from the documentation and not just what you think.

Thank you.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [July 15, 2021, 11:58pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/2 "2021-07-15T23:58:16Z")

</div>

(Tangentially, IIRC that `|it: &mut T| -> *const T { it }` was (is?) a dangerous coercion since it may involve an _implicit_ `it as &T` coercion, _i.e._, a `&*it` reborrow which changes provenance)

- EDIT: added a [godbolt demo comparing MIRs](https://rust.godbolt.org/z/e8ooGjan3)

---

<div class="post-metadata">

**Author:** ![chrefr](https://avatars.discourse-cdn.com/v4/letter/c/e480ec/32.png) [@chrefr](https://users.rust-lang.org/u/chrefr)\
**Post date:** [July 16, 2021, 12:00am UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/3 "2021-07-16T00:00:08Z")

</div>

> [@Yandros](#):
>
> (Tangentially, IIRC that `|it: &mut T| -> *const T { it }` was (is?) a dangerous coercion since it may involve an _implicit_ `it as &T` coercion, _i.e._ , a `&*it` reborrow which changes provenance)

Interesting. Does this have a source?

---

<div class="post-metadata">

**Author:** ![quinedot](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/quinedot/32/17693_2.png) [@quinedot](https://users.rust-lang.org/u/quinedot)\
**Post date:** [July 16, 2021, 12:01am UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/4 "2021-07-16T00:01:45Z")

</div>

[Not currently](https://github.com/rust-lang/rust/issues/56604) -- this is the coercion bug @Yandros mentioned. In both your example and `from_raw_parts` you hit the coercion. They wish it would work though.

I think you can just put `my_mut_ref as *mut` in there for it to be ok though? (I was trying to find confirmation but I'm going to post this right now instead since you just asked for a citation.)

---

<div class="post-metadata">

**Author:** ![chrefr](https://avatars.discourse-cdn.com/v4/letter/c/e480ec/32.png) [@chrefr](https://users.rust-lang.org/u/chrefr)\
**Post date:** [July 16, 2021, 12:05am UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/5 "2021-07-16T00:05:35Z")

</div>

Nice to know. Still, I would like to know whether that's valid with `as *mut Self`, where it's valid without `from_raw_parts()`. Updated the main post.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [July 16, 2021, 12:08am UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/6 "2021-07-16T00:08:18Z")

</div>

Yeah, the main post is still an interesting question; I've currently been assuming that if a `_mut` variant exists, then there _may_ be a reason, but I can't provide anything more concrete: I feel like we need to summon @RalfJung this time 🙂

---

<div class="post-metadata">

**Author:** ![RalfJung](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/ralfjung/32/4469_2.png) [@RalfJung](https://users.rust-lang.org/u/RalfJung)\
**Post date:** [July 17, 2021, 12:41pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/7 "2021-07-17T12:41:16Z")

</div>

Under my proposed aliasing model, only the initial cast from a reference to a raw ptr matters -- that must be `reference as *mut _`. Thereafter, it does not matter if you use `*mut*` or `*const` as long as it's all raw pointers. This includes methods like `ptr::from_raw_parts` since they use only raw pointers. It also includes `addr_of!` as long as you only take the address of fields -- once you actually follow an indirection, that's a totally unrelated pointer.

However, that is just my proposed model. There is nothing official currently.

---

<div class="post-metadata">

**Author:** ![Yandros](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/yandros/32/8136_2.png) [@Yandros](https://users.rust-lang.org/u/Yandros)\
**Post date:** [July 17, 2021, 1:29pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/8 "2021-07-17T13:29:10Z")

</div>

I'll clarify one point here, regarding `ptr::addr_of{,_mut}!`, since I find this distinction to be a bit sneaky and thus able to catch some people off guard:

> [@RalfJung](#):
>
> It also [**as long as it's all raw pointers**] includes `addr_of!` as long as you only take the address of fields

This means that while the following is fine under that model:

```rust
let mut it = (42_i32, 27_i32);
let p = &mut it as *mut _; // shared read-write over `(i32, i32)`.
unsafe { 
    // instead of `addr_of_mut!`
    let snd = ptr::addr_of!( (*p).1 ) as *mut i32;
    *snd += (*p).0;
}

```

The following is not "fine":

```rust
let mut it = (42, 27);
// instead of `addr_of_mut!`
let snd = ptr::addr_of!( it.1 ) as *mut i32;
unsafe {
    *snd += it.0; // Error, mutating through a shared read-only
}

```

It think it's pretty obvious in hindsight, but it doesn't hurt to clarify. In that regard, `addr_of_mut!` is _less error-prone_, by checking the `mut`-accessiblity as if a `&mut` was being performed 🙂

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [October 15, 2021, 1:29pm UTC](https://users.rust-lang.org/t/is-it-safe-to-cast-ptr-from-raw-parts-to-mut-t/62389/9 "2021-10-15T13:29:40Z")

</div>

Closed on October 15, 2021, 1:29pm UTC

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.
