-
Notifications
You must be signed in to change notification settings - Fork 13.6k
Description
Currently, core::slice::from_raw_parts
is not const
, since it uses debug_assert!
with a non-const
check:
rust/library/core/src/slice/raw.rs
Line 89 in 5dab47d
debug_assert!(is_aligned_and_not_null(data), "attempt to create unaligned or null slice"); |
is_aligned_and_not_null
can't be made const
, since it involves ptr->int cast to check the alignment:
rust/library/core/src/intrinsics.rs
Lines 1950 to 1952 in 5dab47d
pub(crate) fn is_aligned_and_not_null<T>(ptr: *const T) -> bool { | |
!ptr.is_null() && ptr as usize % mem::align_of::<T>() == 0 | |
} |
Recently const_eval_select
intrinsic was implemented, it allows to run different code in CTFE and runtime. This, in turn, allows us to only make the alignment check in runtime and ignore it in the CTFE where it doesn't make much sense.
See also: #67456
cc @rust-lang/lang, @rust-lang/libs and @rust-lang/wg-const-eval (it seems like use of const_eval_select
requires approval of all of the above teams)
@rustbot label +T-lang +T-libs +A-const-eval +A-const-fn
Activity
WaffleLapkin commentedon Oct 18, 2021
Another approach to make
slice::from_raw_parts[_mut]
const would be to disable the checks altogether, but since we already haveconst_eval_select
, that seems unreasonable.oli-obk commentedon Oct 18, 2021
cc @rust-lang/wg-const-eval opinions before we escalate to lang and libs?
mbartlett21 commentedon Oct 18, 2021
If a new intrinsic was added in the spirit of
ptr_guaranteed_eq
andptr_guaranteed_ne
, this could possibly provide a solution withoutconst_eval_select
. Something like:fee1-dead commentedon Oct 18, 2021
It seems useless to be able to perform any align checks in constants. The CTFE catches invalid pointer dereferences anyways.
mbartlett21 commentedon Oct 18, 2021
Yes, but we also want to catch invalid pointer dereferences when we are not in CTFE, hence the idea of the function/intrinsic.
fee1-dead commentedon Oct 18, 2021
So why not use
const_eval_select
?RalfJung commentedon Oct 18, 2021
It doesn't catch insufficiently aligned pointers though.
core::slice::from_raw_parts[_mut]
const #90377Rollup merge of rust-lang#90377 - WaffleLapkin:const_slice_from_raw_p…
Rollup merge of rust-lang#90377 - WaffleLapkin:const_slice_from_raw_p…