Skip to content

Can Weak be null? #114517

Open
Open
@est31

Description

@est31

There is a discrepancy between the docs of Weak and its implementation, originally found by @Urgau in #114494 (comment) .

On one hand, the docs of Weak::as_ptr state:

The pointer is valid only if there are some strong references. The pointer may be dangling, unaligned or even null otherwise.

On the other hand, the implementation of Weak uses NonNull:

rust/library/alloc/src/rc.rs

Lines 2681 to 2693 in 1cabb8e

pub struct Weak<
T: ?Sized,
#[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
> {
// This is a `NonNull` to allow optimizing the size of this type in enums,
// but it is not necessarily a valid pointer.
// `Weak::new` sets this to `usize::MAX` so that it doesn’t need
// to allocate space on the heap. That's not a value a real pointer
// will ever have because RcBox has alignment at least 2.
// This is only possible when `T: Sized`; unsized `T` never dangle.
ptr: NonNull<RcBox<T>>,
alloc: A,
}

From what I know, it is okay for NonNull pointers to be dangling or unaligned, but, staying true to their name, they are never allowed to be null pointers.

I think this discrepancy should be resolved, but I wonder, which way? Should the docs be adjusted, or the implementation?

The issue exists both with alloc::sync::Weak as well as alloc::rc::Weak.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsT-libs-apiRelevant to the library API team, which will review and decide on the PR/issue.T-opsemRelevant to the opsem team

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions