Skip to content

Make all functions part of alloc_layout_extra usable in const contexts #94

@Raekye

Description

@Raekye

Proposal

Problem statement

The Rust standard library provides the Layout type for use with the allocator API. Of the functions in rust-lang/rust#55724, some are already marked as const, but the following currently are not:

  • align_to
  • pad_to_align
  • repeat
  • extend
  • repeat_packed
  • extend_packed
  • array

This makes them unusable in const contexts.

Motivation, use-cases

Layout is also documented by example as being able to calculate the offsets of fields in a #[repr(C)] struct. This is useful since there is no equivalent of C's offsetof in the standard library, and users must rely on a third party crate.

Layout can also be used to correctly determine the offset of trailing elements in a dynamically sized type. It may be desirable to know this offset at compile time (as a const variable). I believe this can currently be emulated by including a zero-length array of the trailing element in the struct definition and using std::mem::size_of, but the intent is not as clear.

Solution sketches

Add the const keyword to the above function definitions. A few functions currently use the std::cmp::max function which relies on the Ord trait, which can't be used in const contexts. So std::cmp::max would need to be replaced by a plain if-else block expression.

Links and related work

What happens now?

This issue is part of the libs-api team API change proposal process. Once this issue is filed the libs-api team will review open proposals in its weekly meeting. You should receive feedback within a week or two.

Metadata

Metadata

Assignees

No one assigned

    Labels

    ACP-acceptedAPI Change Proposal is accepted (seconded with no objections)T-libs-apiapi-change-proposalA proposal to add or alter unstable APIs in the standard libraries

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions