Skip to content

Undefined behavior in safe rust using rustc_layout_scalar_valid_range_start #115284

Closed
@bart358

Description

@bart358

Given the following struct:

#[rustc_layout_scalar_valid_range_start(2)]
struct NonZeroAndOneU8(u8);

trying to initialise it directly with NonZeroAndOneU8(1) (rightfully) results in the error:

error[[E0133]](https://doc.rust-lang.org/nightly/error_codes/E0133.html): initializing type with `rustc_layout_scalar_valid_range` attr is unsafe and requires unsafe function or block
 --> src/main.rs:9:5
  |
9 |     NonZeroAndOneU8(1);
  |     ^^^^^^^^^^^^^^^^^^ initializing type with `rustc_layout_scalar_valid_range` attr
  |
  = note: initializing a layout restricted type's field with a value outside the valid range is undefined behavior

For more information about this error, try `rustc --explain E0133`.
error: could not compile `playground` (bin "playground") due to previous error

But Some(1).map(NonZeroAndOneU8).unwrap() compiles just fine returning NonZeroAndOneU8(1) which is an invalid state (link to the playground).

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.F-rustc_attrsInternal rustc attributes gated on the `#[rustc_attrs]` feature gate.requires-internal-featuresThis issue requires the use of internal features.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions