Skip to content

ptr::offset should explicitly clarify 0-sized offset semantics #65108

Closed
@Gankra

Description

@Gankra

https://doc.rust-lang.org/std/primitive.pointer.html#method.offset

I can't remember the past arguments we definitely had about this, but it would be nice to explicitly call out the answer in the docs.

As a relevant example, Vec::into_iter currently unconditionally computes the "end" pointer of the array by offsetting by len (as long as size_of T > 0). This means that we offset a dangling pointer by 0 when iterating an empty Vec. This is obviously useful to support and annoying to have to guard against, so I would hope that's well-defined.

https://doc.rust-lang.org/src/alloc/vec.rs.html#1860

fn into_iter(mut self) -> IntoIter<T> {
        unsafe {
            let begin = self.as_mut_ptr();
            let end = if mem::size_of::<T>() == 0 {
                arith_offset(begin as *const i8, self.len() as isize) as *const T
            } else {
                // SAFE when `begin` dangles and `len == 0`???
                begin.add(self.len()) as *const T
            };
            let cap = self.buf.capacity();
            mem::forget(self);
            IntoIter {
                buf: NonNull::new_unchecked(begin),
                phantom: PhantomData,
                cap,
                ptr: begin,
                end,
            }
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-langRelevant to the language team, which will review and decide on the PR/issue.T-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions