1 //! Compiler intrinsics.
3 //! The corresponding definitions are in `compiler/rustc_codegen_llvm/src/intrinsic.rs`.
4 //! The corresponding const implementations are in `compiler/rustc_mir/src/interpret/intrinsics.rs`
8 //! Note: any changes to the constness of intrinsics should be discussed with the language team.
9 //! This includes changes in the stability of the constness.
11 //! In order to make an intrinsic usable at compile-time, one needs to copy the implementation
12 //! from <https://github.com/rust-lang/miri/blob/master/src/shims/intrinsics.rs> to
13 //! `compiler/rustc_mir/src/interpret/intrinsics.rs` and add a
14 //! `#[rustc_const_unstable(feature = "foo", issue = "01234")]` to the intrinsic.
16 //! If an intrinsic is supposed to be used from a `const fn` with a `rustc_const_stable` attribute,
17 //! the intrinsic's attribute must be `rustc_const_stable`, too. Such a change should not be done
18 //! without T-lang consultation, because it bakes a feature into the language that cannot be
19 //! replicated in user code without compiler support.
23 //! The volatile intrinsics provide operations intended to act on I/O
24 //! memory, which are guaranteed to not be reordered by the compiler
25 //! across other volatile intrinsics. See the LLVM documentation on
28 //! [volatile]: https://llvm.org/docs/LangRef.html#volatile-memory-accesses
32 //! The atomic intrinsics provide common atomic operations on machine
33 //! words, with multiple possible memory orderings. They obey the same
34 //! semantics as C++11. See the LLVM documentation on [[atomics]].
36 //! [atomics]: https://llvm.org/docs/Atomics.html
38 //! A quick refresher on memory ordering:
40 //! * Acquire - a barrier for acquiring a lock. Subsequent reads and writes
41 //! take place after the barrier.
42 //! * Release - a barrier for releasing a lock. Preceding reads and writes
43 //! take place before the barrier.
44 //! * Sequentially consistent - sequentially consistent operations are
45 //! guaranteed to happen in order. This is the standard mode for working
46 //! with atomic types and is equivalent to Java's `volatile`.
49 feature = "core_intrinsics",
50 reason = "intrinsics are unlikely to ever be stabilized, instead \
51 they should be used through stabilized interfaces \
52 in the rest of the standard library",
55 #![allow(missing_docs)]
57 use crate::marker::DiscriminantKind;
60 // These imports are used for simplifying intra-doc links
61 #[allow(unused_imports)]
62 #[cfg(all(target_has_atomic = "8", target_has_atomic = "32", target_has_atomic = "ptr"))]
63 use crate::sync::atomic::{self, AtomicBool, AtomicI32, AtomicIsize, AtomicU32, Ordering};
65 #[stable(feature = "drop_in_place", since = "1.8.0")]
67 reason = "no longer an intrinsic - use `ptr::drop_in_place` directly",
71 pub unsafe fn drop_in_place<T: ?Sized>(to_drop: *mut T) {
72 // SAFETY: see `ptr::drop_in_place`
73 unsafe { crate::ptr::drop_in_place(to_drop) }
76 extern "rust-intrinsic" {
77 // N.B., these intrinsics take raw pointers because they mutate aliased
78 // memory, which is not valid for either `&` or `&mut`.
80 /// Stores a value if the current value is the same as the `old` value.
82 /// The stabilized version of this intrinsic is available on the
83 /// [`atomic`] types via the `compare_exchange` method by passing
84 /// [`Ordering::SeqCst`] as both the `success` and `failure` parameters.
85 /// For example, [`AtomicBool::compare_exchange`].
86 pub fn atomic_cxchg<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
87 /// Stores a value if the current value is the same as the `old` value.
89 /// The stabilized version of this intrinsic is available on the
90 /// [`atomic`] types via the `compare_exchange` method by passing
91 /// [`Ordering::Acquire`] as both the `success` and `failure` parameters.
92 /// For example, [`AtomicBool::compare_exchange`].
93 pub fn atomic_cxchg_acq<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
94 /// Stores a value if the current value is the same as the `old` value.
96 /// The stabilized version of this intrinsic is available on the
97 /// [`atomic`] types via the `compare_exchange` method by passing
98 /// [`Ordering::Release`] as the `success` and [`Ordering::Relaxed`] as the
99 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
100 pub fn atomic_cxchg_rel<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
101 /// Stores a value if the current value is the same as the `old` value.
103 /// The stabilized version of this intrinsic is available on the
104 /// [`atomic`] types via the `compare_exchange` method by passing
105 /// [`Ordering::AcqRel`] as the `success` and [`Ordering::Acquire`] as the
106 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
107 pub fn atomic_cxchg_acqrel<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
108 /// Stores a value if the current value is the same as the `old` value.
110 /// The stabilized version of this intrinsic is available on the
111 /// [`atomic`] types via the `compare_exchange` method by passing
112 /// [`Ordering::Relaxed`] as both the `success` and `failure` parameters.
113 /// For example, [`AtomicBool::compare_exchange`].
114 pub fn atomic_cxchg_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
115 /// Stores a value if the current value is the same as the `old` value.
117 /// The stabilized version of this intrinsic is available on the
118 /// [`atomic`] types via the `compare_exchange` method by passing
119 /// [`Ordering::SeqCst`] as the `success` and [`Ordering::Relaxed`] as the
120 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
121 pub fn atomic_cxchg_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
122 /// Stores a value if the current value is the same as the `old` value.
124 /// The stabilized version of this intrinsic is available on the
125 /// [`atomic`] types via the `compare_exchange` method by passing
126 /// [`Ordering::SeqCst`] as the `success` and [`Ordering::Acquire`] as the
127 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
128 pub fn atomic_cxchg_failacq<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
129 /// Stores a value if the current value is the same as the `old` value.
131 /// The stabilized version of this intrinsic is available on the
132 /// [`atomic`] types via the `compare_exchange` method by passing
133 /// [`Ordering::Acquire`] as the `success` and [`Ordering::Relaxed`] as the
134 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
135 pub fn atomic_cxchg_acq_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
136 /// Stores a value if the current value is the same as the `old` value.
138 /// The stabilized version of this intrinsic is available on the
139 /// [`atomic`] types via the `compare_exchange` method by passing
140 /// [`Ordering::AcqRel`] as the `success` and [`Ordering::Relaxed`] as the
141 /// `failure` parameters. For example, [`AtomicBool::compare_exchange`].
142 pub fn atomic_cxchg_acqrel_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
144 /// Stores a value if the current value is the same as the `old` value.
146 /// The stabilized version of this intrinsic is available on the
147 /// [`atomic`] types via the `compare_exchange_weak` method by passing
148 /// [`Ordering::SeqCst`] as both the `success` and `failure` parameters.
149 /// For example, [`AtomicBool::compare_exchange_weak`].
150 pub fn atomic_cxchgweak<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
151 /// Stores a value if the current value is the same as the `old` value.
153 /// The stabilized version of this intrinsic is available on the
154 /// [`atomic`] types via the `compare_exchange_weak` method by passing
155 /// [`Ordering::Acquire`] as both the `success` and `failure` parameters.
156 /// For example, [`AtomicBool::compare_exchange_weak`].
157 pub fn atomic_cxchgweak_acq<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
158 /// Stores a value if the current value is the same as the `old` value.
160 /// The stabilized version of this intrinsic is available on the
161 /// [`atomic`] types via the `compare_exchange_weak` method by passing
162 /// [`Ordering::Release`] as the `success` and [`Ordering::Relaxed`] as the
163 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
164 pub fn atomic_cxchgweak_rel<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
165 /// Stores a value if the current value is the same as the `old` value.
167 /// The stabilized version of this intrinsic is available on the
168 /// [`atomic`] types via the `compare_exchange_weak` method by passing
169 /// [`Ordering::AcqRel`] as the `success` and [`Ordering::Acquire`] as the
170 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
171 pub fn atomic_cxchgweak_acqrel<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
172 /// Stores a value if the current value is the same as the `old` value.
174 /// The stabilized version of this intrinsic is available on the
175 /// [`atomic`] types via the `compare_exchange_weak` method by passing
176 /// [`Ordering::Relaxed`] as both the `success` and `failure` parameters.
177 /// For example, [`AtomicBool::compare_exchange_weak`].
178 pub fn atomic_cxchgweak_relaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
179 /// Stores a value if the current value is the same as the `old` value.
181 /// The stabilized version of this intrinsic is available on the
182 /// [`atomic`] types via the `compare_exchange_weak` method by passing
183 /// [`Ordering::SeqCst`] as the `success` and [`Ordering::Relaxed`] as the
184 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
185 pub fn atomic_cxchgweak_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
186 /// Stores a value if the current value is the same as the `old` value.
188 /// The stabilized version of this intrinsic is available on the
189 /// [`atomic`] types via the `compare_exchange_weak` method by passing
190 /// [`Ordering::SeqCst`] as the `success` and [`Ordering::Acquire`] as the
191 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
192 pub fn atomic_cxchgweak_failacq<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
193 /// Stores a value if the current value is the same as the `old` value.
195 /// The stabilized version of this intrinsic is available on the
196 /// [`atomic`] types via the `compare_exchange_weak` method by passing
197 /// [`Ordering::Acquire`] as the `success` and [`Ordering::Relaxed`] as the
198 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
199 pub fn atomic_cxchgweak_acq_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
200 /// Stores a value if the current value is the same as the `old` value.
202 /// The stabilized version of this intrinsic is available on the
203 /// [`atomic`] types via the `compare_exchange_weak` method by passing
204 /// [`Ordering::AcqRel`] as the `success` and [`Ordering::Relaxed`] as the
205 /// `failure` parameters. For example, [`AtomicBool::compare_exchange_weak`].
206 pub fn atomic_cxchgweak_acqrel_failrelaxed<T: Copy>(dst: *mut T, old: T, src: T) -> (T, bool);
208 /// Loads the current value of the pointer.
210 /// The stabilized version of this intrinsic is available on the
211 /// [`atomic`] types via the `load` method by passing
212 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::load`].
213 pub fn atomic_load<T: Copy>(src: *const T) -> T;
214 /// Loads the current value of the pointer.
216 /// The stabilized version of this intrinsic is available on the
217 /// [`atomic`] types via the `load` method by passing
218 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::load`].
219 pub fn atomic_load_acq<T: Copy>(src: *const T) -> T;
220 /// Loads the current value of the pointer.
222 /// The stabilized version of this intrinsic is available on the
223 /// [`atomic`] types via the `load` method by passing
224 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::load`].
225 pub fn atomic_load_relaxed<T: Copy>(src: *const T) -> T;
226 pub fn atomic_load_unordered<T: Copy>(src: *const T) -> T;
228 /// Stores the value at the specified memory location.
230 /// The stabilized version of this intrinsic is available on the
231 /// [`atomic`] types via the `store` method by passing
232 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::store`].
233 pub fn atomic_store<T: Copy>(dst: *mut T, val: T);
234 /// Stores the value at the specified memory location.
236 /// The stabilized version of this intrinsic is available on the
237 /// [`atomic`] types via the `store` method by passing
238 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::store`].
239 pub fn atomic_store_rel<T: Copy>(dst: *mut T, val: T);
240 /// Stores the value at the specified memory location.
242 /// The stabilized version of this intrinsic is available on the
243 /// [`atomic`] types via the `store` method by passing
244 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::store`].
245 pub fn atomic_store_relaxed<T: Copy>(dst: *mut T, val: T);
246 pub fn atomic_store_unordered<T: Copy>(dst: *mut T, val: T);
248 /// Stores the value at the specified memory location, returning the old value.
250 /// The stabilized version of this intrinsic is available on the
251 /// [`atomic`] types via the `swap` method by passing
252 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::swap`].
253 pub fn atomic_xchg<T: Copy>(dst: *mut T, src: T) -> T;
254 /// Stores the value at the specified memory location, returning the old value.
256 /// The stabilized version of this intrinsic is available on the
257 /// [`atomic`] types via the `swap` method by passing
258 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::swap`].
259 pub fn atomic_xchg_acq<T: Copy>(dst: *mut T, src: T) -> T;
260 /// Stores the value at the specified memory location, returning the old value.
262 /// The stabilized version of this intrinsic is available on the
263 /// [`atomic`] types via the `swap` method by passing
264 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::swap`].
265 pub fn atomic_xchg_rel<T: Copy>(dst: *mut T, src: T) -> T;
266 /// Stores the value at the specified memory location, returning the old value.
268 /// The stabilized version of this intrinsic is available on the
269 /// [`atomic`] types via the `swap` method by passing
270 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicBool::swap`].
271 pub fn atomic_xchg_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
272 /// Stores the value at the specified memory location, returning the old value.
274 /// The stabilized version of this intrinsic is available on the
275 /// [`atomic`] types via the `swap` method by passing
276 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::swap`].
277 pub fn atomic_xchg_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
279 /// Adds to the current value, returning the previous value.
281 /// The stabilized version of this intrinsic is available on the
282 /// [`atomic`] types via the `fetch_add` method by passing
283 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicIsize::fetch_add`].
284 pub fn atomic_xadd<T: Copy>(dst: *mut T, src: T) -> T;
285 /// Adds to the current value, returning the previous value.
287 /// The stabilized version of this intrinsic is available on the
288 /// [`atomic`] types via the `fetch_add` method by passing
289 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicIsize::fetch_add`].
290 pub fn atomic_xadd_acq<T: Copy>(dst: *mut T, src: T) -> T;
291 /// Adds to the current value, returning the previous value.
293 /// The stabilized version of this intrinsic is available on the
294 /// [`atomic`] types via the `fetch_add` method by passing
295 /// [`Ordering::Release`] as the `order`. For example, [`AtomicIsize::fetch_add`].
296 pub fn atomic_xadd_rel<T: Copy>(dst: *mut T, src: T) -> T;
297 /// Adds to the current value, returning the previous value.
299 /// The stabilized version of this intrinsic is available on the
300 /// [`atomic`] types via the `fetch_add` method by passing
301 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicIsize::fetch_add`].
302 pub fn atomic_xadd_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
303 /// Adds to the current value, returning the previous value.
305 /// The stabilized version of this intrinsic is available on the
306 /// [`atomic`] types via the `fetch_add` method by passing
307 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicIsize::fetch_add`].
308 pub fn atomic_xadd_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
310 /// Subtract from the current value, returning the previous value.
312 /// The stabilized version of this intrinsic is available on the
313 /// [`atomic`] types via the `fetch_sub` method by passing
314 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicIsize::fetch_sub`].
315 pub fn atomic_xsub<T: Copy>(dst: *mut T, src: T) -> T;
316 /// Subtract from the current value, returning the previous value.
318 /// The stabilized version of this intrinsic is available on the
319 /// [`atomic`] types via the `fetch_sub` method by passing
320 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicIsize::fetch_sub`].
321 pub fn atomic_xsub_acq<T: Copy>(dst: *mut T, src: T) -> T;
322 /// Subtract from the current value, returning the previous value.
324 /// The stabilized version of this intrinsic is available on the
325 /// [`atomic`] types via the `fetch_sub` method by passing
326 /// [`Ordering::Release`] as the `order`. For example, [`AtomicIsize::fetch_sub`].
327 pub fn atomic_xsub_rel<T: Copy>(dst: *mut T, src: T) -> T;
328 /// Subtract from the current value, returning the previous value.
330 /// The stabilized version of this intrinsic is available on the
331 /// [`atomic`] types via the `fetch_sub` method by passing
332 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicIsize::fetch_sub`].
333 pub fn atomic_xsub_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
334 /// Subtract from the current value, returning the previous value.
336 /// The stabilized version of this intrinsic is available on the
337 /// [`atomic`] types via the `fetch_sub` method by passing
338 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicIsize::fetch_sub`].
339 pub fn atomic_xsub_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
341 /// Bitwise and with the current value, returning the previous value.
343 /// The stabilized version of this intrinsic is available on the
344 /// [`atomic`] types via the `fetch_and` method by passing
345 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::fetch_and`].
346 pub fn atomic_and<T: Copy>(dst: *mut T, src: T) -> T;
347 /// Bitwise and with the current value, returning the previous value.
349 /// The stabilized version of this intrinsic is available on the
350 /// [`atomic`] types via the `fetch_and` method by passing
351 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::fetch_and`].
352 pub fn atomic_and_acq<T: Copy>(dst: *mut T, src: T) -> T;
353 /// Bitwise and with the current value, returning the previous value.
355 /// The stabilized version of this intrinsic is available on the
356 /// [`atomic`] types via the `fetch_and` method by passing
357 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::fetch_and`].
358 pub fn atomic_and_rel<T: Copy>(dst: *mut T, src: T) -> T;
359 /// Bitwise and with the current value, returning the previous value.
361 /// The stabilized version of this intrinsic is available on the
362 /// [`atomic`] types via the `fetch_and` method by passing
363 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicBool::fetch_and`].
364 pub fn atomic_and_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
365 /// Bitwise and with the current value, returning the previous value.
367 /// The stabilized version of this intrinsic is available on the
368 /// [`atomic`] types via the `fetch_and` method by passing
369 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::fetch_and`].
370 pub fn atomic_and_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
372 /// Bitwise nand with the current value, returning the previous value.
374 /// The stabilized version of this intrinsic is available on the
375 /// [`AtomicBool`] type via the `fetch_nand` method by passing
376 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::fetch_nand`].
377 pub fn atomic_nand<T: Copy>(dst: *mut T, src: T) -> T;
378 /// Bitwise nand with the current value, returning the previous value.
380 /// The stabilized version of this intrinsic is available on the
381 /// [`AtomicBool`] type via the `fetch_nand` method by passing
382 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::fetch_nand`].
383 pub fn atomic_nand_acq<T: Copy>(dst: *mut T, src: T) -> T;
384 /// Bitwise nand with the current value, returning the previous value.
386 /// The stabilized version of this intrinsic is available on the
387 /// [`AtomicBool`] type via the `fetch_nand` method by passing
388 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::fetch_nand`].
389 pub fn atomic_nand_rel<T: Copy>(dst: *mut T, src: T) -> T;
390 /// Bitwise nand with the current value, returning the previous value.
392 /// The stabilized version of this intrinsic is available on the
393 /// [`AtomicBool`] type via the `fetch_nand` method by passing
394 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicBool::fetch_nand`].
395 pub fn atomic_nand_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
396 /// Bitwise nand with the current value, returning the previous value.
398 /// The stabilized version of this intrinsic is available on the
399 /// [`AtomicBool`] type via the `fetch_nand` method by passing
400 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::fetch_nand`].
401 pub fn atomic_nand_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
403 /// Bitwise or with the current value, returning the previous value.
405 /// The stabilized version of this intrinsic is available on the
406 /// [`atomic`] types via the `fetch_or` method by passing
407 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::fetch_or`].
408 pub fn atomic_or<T: Copy>(dst: *mut T, src: T) -> T;
409 /// Bitwise or with the current value, returning the previous value.
411 /// The stabilized version of this intrinsic is available on the
412 /// [`atomic`] types via the `fetch_or` method by passing
413 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::fetch_or`].
414 pub fn atomic_or_acq<T: Copy>(dst: *mut T, src: T) -> T;
415 /// Bitwise or with the current value, returning the previous value.
417 /// The stabilized version of this intrinsic is available on the
418 /// [`atomic`] types via the `fetch_or` method by passing
419 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::fetch_or`].
420 pub fn atomic_or_rel<T: Copy>(dst: *mut T, src: T) -> T;
421 /// Bitwise or with the current value, returning the previous value.
423 /// The stabilized version of this intrinsic is available on the
424 /// [`atomic`] types via the `fetch_or` method by passing
425 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicBool::fetch_or`].
426 pub fn atomic_or_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
427 /// Bitwise or with the current value, returning the previous value.
429 /// The stabilized version of this intrinsic is available on the
430 /// [`atomic`] types via the `fetch_or` method by passing
431 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::fetch_or`].
432 pub fn atomic_or_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
434 /// Bitwise xor with the current value, returning the previous value.
436 /// The stabilized version of this intrinsic is available on the
437 /// [`atomic`] types via the `fetch_xor` method by passing
438 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicBool::fetch_xor`].
439 pub fn atomic_xor<T: Copy>(dst: *mut T, src: T) -> T;
440 /// Bitwise xor with the current value, returning the previous value.
442 /// The stabilized version of this intrinsic is available on the
443 /// [`atomic`] types via the `fetch_xor` method by passing
444 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicBool::fetch_xor`].
445 pub fn atomic_xor_acq<T: Copy>(dst: *mut T, src: T) -> T;
446 /// Bitwise xor with the current value, returning the previous value.
448 /// The stabilized version of this intrinsic is available on the
449 /// [`atomic`] types via the `fetch_xor` method by passing
450 /// [`Ordering::Release`] as the `order`. For example, [`AtomicBool::fetch_xor`].
451 pub fn atomic_xor_rel<T: Copy>(dst: *mut T, src: T) -> T;
452 /// Bitwise xor with the current value, returning the previous value.
454 /// The stabilized version of this intrinsic is available on the
455 /// [`atomic`] types via the `fetch_xor` method by passing
456 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicBool::fetch_xor`].
457 pub fn atomic_xor_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
458 /// Bitwise xor with the current value, returning the previous value.
460 /// The stabilized version of this intrinsic is available on the
461 /// [`atomic`] types via the `fetch_xor` method by passing
462 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicBool::fetch_xor`].
463 pub fn atomic_xor_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
465 /// Maximum with the current value using a signed comparison.
467 /// The stabilized version of this intrinsic is available on the
468 /// [`atomic`] signed integer types via the `fetch_max` method by passing
469 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicI32::fetch_max`].
470 pub fn atomic_max<T: Copy>(dst: *mut T, src: T) -> T;
471 /// Maximum with the current value using a signed comparison.
473 /// The stabilized version of this intrinsic is available on the
474 /// [`atomic`] signed integer types via the `fetch_max` method by passing
475 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicI32::fetch_max`].
476 pub fn atomic_max_acq<T: Copy>(dst: *mut T, src: T) -> T;
477 /// Maximum with the current value using a signed comparison.
479 /// The stabilized version of this intrinsic is available on the
480 /// [`atomic`] signed integer types via the `fetch_max` method by passing
481 /// [`Ordering::Release`] as the `order`. For example, [`AtomicI32::fetch_max`].
482 pub fn atomic_max_rel<T: Copy>(dst: *mut T, src: T) -> T;
483 /// Maximum with the current value using a signed comparison.
485 /// The stabilized version of this intrinsic is available on the
486 /// [`atomic`] signed integer types via the `fetch_max` method by passing
487 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicI32::fetch_max`].
488 pub fn atomic_max_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
489 /// Maximum with the current value.
491 /// The stabilized version of this intrinsic is available on the
492 /// [`atomic`] signed integer types via the `fetch_max` method by passing
493 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicI32::fetch_max`].
494 pub fn atomic_max_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
496 /// Minimum with the current value using a signed comparison.
498 /// The stabilized version of this intrinsic is available on the
499 /// [`atomic`] signed integer types via the `fetch_min` method by passing
500 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicI32::fetch_min`].
501 pub fn atomic_min<T: Copy>(dst: *mut T, src: T) -> T;
502 /// Minimum with the current value using a signed comparison.
504 /// The stabilized version of this intrinsic is available on the
505 /// [`atomic`] signed integer types via the `fetch_min` method by passing
506 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicI32::fetch_min`].
507 pub fn atomic_min_acq<T: Copy>(dst: *mut T, src: T) -> T;
508 /// Minimum with the current value using a signed comparison.
510 /// The stabilized version of this intrinsic is available on the
511 /// [`atomic`] signed integer types via the `fetch_min` method by passing
512 /// [`Ordering::Release`] as the `order`. For example, [`AtomicI32::fetch_min`].
513 pub fn atomic_min_rel<T: Copy>(dst: *mut T, src: T) -> T;
514 /// Minimum with the current value using a signed comparison.
516 /// The stabilized version of this intrinsic is available on the
517 /// [`atomic`] signed integer types via the `fetch_min` method by passing
518 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicI32::fetch_min`].
519 pub fn atomic_min_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
520 /// Minimum with the current value using a signed comparison.
522 /// The stabilized version of this intrinsic is available on the
523 /// [`atomic`] signed integer types via the `fetch_min` method by passing
524 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicI32::fetch_min`].
525 pub fn atomic_min_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
527 /// Minimum with the current value using an unsigned comparison.
529 /// The stabilized version of this intrinsic is available on the
530 /// [`atomic`] unsigned integer types via the `fetch_min` method by passing
531 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicU32::fetch_min`].
532 pub fn atomic_umin<T: Copy>(dst: *mut T, src: T) -> T;
533 /// Minimum with the current value using an unsigned comparison.
535 /// The stabilized version of this intrinsic is available on the
536 /// [`atomic`] unsigned integer types via the `fetch_min` method by passing
537 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicU32::fetch_min`].
538 pub fn atomic_umin_acq<T: Copy>(dst: *mut T, src: T) -> T;
539 /// Minimum with the current value using an unsigned comparison.
541 /// The stabilized version of this intrinsic is available on the
542 /// [`atomic`] unsigned integer types via the `fetch_min` method by passing
543 /// [`Ordering::Release`] as the `order`. For example, [`AtomicU32::fetch_min`].
544 pub fn atomic_umin_rel<T: Copy>(dst: *mut T, src: T) -> T;
545 /// Minimum with the current value using an unsigned comparison.
547 /// The stabilized version of this intrinsic is available on the
548 /// [`atomic`] unsigned integer types via the `fetch_min` method by passing
549 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicU32::fetch_min`].
550 pub fn atomic_umin_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
551 /// Minimum with the current value using an unsigned comparison.
553 /// The stabilized version of this intrinsic is available on the
554 /// [`atomic`] unsigned integer types via the `fetch_min` method by passing
555 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicU32::fetch_min`].
556 pub fn atomic_umin_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
558 /// Maximum with the current value using an unsigned comparison.
560 /// The stabilized version of this intrinsic is available on the
561 /// [`atomic`] unsigned integer types via the `fetch_max` method by passing
562 /// [`Ordering::SeqCst`] as the `order`. For example, [`AtomicU32::fetch_max`].
563 pub fn atomic_umax<T: Copy>(dst: *mut T, src: T) -> T;
564 /// Maximum with the current value using an unsigned comparison.
566 /// The stabilized version of this intrinsic is available on the
567 /// [`atomic`] unsigned integer types via the `fetch_max` method by passing
568 /// [`Ordering::Acquire`] as the `order`. For example, [`AtomicU32::fetch_max`].
569 pub fn atomic_umax_acq<T: Copy>(dst: *mut T, src: T) -> T;
570 /// Maximum with the current value using an unsigned comparison.
572 /// The stabilized version of this intrinsic is available on the
573 /// [`atomic`] unsigned integer types via the `fetch_max` method by passing
574 /// [`Ordering::Release`] as the `order`. For example, [`AtomicU32::fetch_max`].
575 pub fn atomic_umax_rel<T: Copy>(dst: *mut T, src: T) -> T;
576 /// Maximum with the current value using an unsigned comparison.
578 /// The stabilized version of this intrinsic is available on the
579 /// [`atomic`] unsigned integer types via the `fetch_max` method by passing
580 /// [`Ordering::AcqRel`] as the `order`. For example, [`AtomicU32::fetch_max`].
581 pub fn atomic_umax_acqrel<T: Copy>(dst: *mut T, src: T) -> T;
582 /// Maximum with the current value using an unsigned comparison.
584 /// The stabilized version of this intrinsic is available on the
585 /// [`atomic`] unsigned integer types via the `fetch_max` method by passing
586 /// [`Ordering::Relaxed`] as the `order`. For example, [`AtomicU32::fetch_max`].
587 pub fn atomic_umax_relaxed<T: Copy>(dst: *mut T, src: T) -> T;
589 /// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
590 /// if supported; otherwise, it is a no-op.
591 /// Prefetches have no effect on the behavior of the program but can change its performance
594 /// The `locality` argument must be a constant integer and is a temporal locality specifier
595 /// ranging from (0) - no locality, to (3) - extremely local keep in cache.
597 /// This intrinsic does not have a stable counterpart.
598 pub fn prefetch_read_data<T>(data: *const T, locality: i32);
599 /// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
600 /// if supported; otherwise, it is a no-op.
601 /// Prefetches have no effect on the behavior of the program but can change its performance
604 /// The `locality` argument must be a constant integer and is a temporal locality specifier
605 /// ranging from (0) - no locality, to (3) - extremely local keep in cache.
607 /// This intrinsic does not have a stable counterpart.
608 pub fn prefetch_write_data<T>(data: *const T, locality: i32);
609 /// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
610 /// if supported; otherwise, it is a no-op.
611 /// Prefetches have no effect on the behavior of the program but can change its performance
614 /// The `locality` argument must be a constant integer and is a temporal locality specifier
615 /// ranging from (0) - no locality, to (3) - extremely local keep in cache.
617 /// This intrinsic does not have a stable counterpart.
618 pub fn prefetch_read_instruction<T>(data: *const T, locality: i32);
619 /// The `prefetch` intrinsic is a hint to the code generator to insert a prefetch instruction
620 /// if supported; otherwise, it is a no-op.
621 /// Prefetches have no effect on the behavior of the program but can change its performance
624 /// The `locality` argument must be a constant integer and is a temporal locality specifier
625 /// ranging from (0) - no locality, to (3) - extremely local keep in cache.
627 /// This intrinsic does not have a stable counterpart.
628 pub fn prefetch_write_instruction<T>(data: *const T, locality: i32);
631 extern "rust-intrinsic" {
634 /// The stabilized version of this intrinsic is available in
635 /// [`atomic::fence`] by passing [`Ordering::SeqCst`]
637 pub fn atomic_fence();
640 /// The stabilized version of this intrinsic is available in
641 /// [`atomic::fence`] by passing [`Ordering::Acquire`]
643 pub fn atomic_fence_acq();
646 /// The stabilized version of this intrinsic is available in
647 /// [`atomic::fence`] by passing [`Ordering::Release`]
649 pub fn atomic_fence_rel();
652 /// The stabilized version of this intrinsic is available in
653 /// [`atomic::fence`] by passing [`Ordering::AcqRel`]
655 pub fn atomic_fence_acqrel();
657 /// A compiler-only memory barrier.
659 /// Memory accesses will never be reordered across this barrier by the
660 /// compiler, but no instructions will be emitted for it. This is
661 /// appropriate for operations on the same thread that may be preempted,
662 /// such as when interacting with signal handlers.
664 /// The stabilized version of this intrinsic is available in
665 /// [`atomic::compiler_fence`] by passing [`Ordering::SeqCst`]
667 pub fn atomic_singlethreadfence();
668 /// A compiler-only memory barrier.
670 /// Memory accesses will never be reordered across this barrier by the
671 /// compiler, but no instructions will be emitted for it. This is
672 /// appropriate for operations on the same thread that may be preempted,
673 /// such as when interacting with signal handlers.
675 /// The stabilized version of this intrinsic is available in
676 /// [`atomic::compiler_fence`] by passing [`Ordering::Acquire`]
678 pub fn atomic_singlethreadfence_acq();
679 /// A compiler-only memory barrier.
681 /// Memory accesses will never be reordered across this barrier by the
682 /// compiler, but no instructions will be emitted for it. This is
683 /// appropriate for operations on the same thread that may be preempted,
684 /// such as when interacting with signal handlers.
686 /// The stabilized version of this intrinsic is available in
687 /// [`atomic::compiler_fence`] by passing [`Ordering::Release`]
689 pub fn atomic_singlethreadfence_rel();
690 /// A compiler-only memory barrier.
692 /// Memory accesses will never be reordered across this barrier by the
693 /// compiler, but no instructions will be emitted for it. This is
694 /// appropriate for operations on the same thread that may be preempted,
695 /// such as when interacting with signal handlers.
697 /// The stabilized version of this intrinsic is available in
698 /// [`atomic::compiler_fence`] by passing [`Ordering::AcqRel`]
700 pub fn atomic_singlethreadfence_acqrel();
702 /// Magic intrinsic that derives its meaning from attributes
703 /// attached to the function.
705 /// For example, dataflow uses this to inject static assertions so
706 /// that `rustc_peek(potentially_uninitialized)` would actually
707 /// double-check that dataflow did indeed compute that it is
708 /// uninitialized at that point in the control flow.
710 /// This intrinsic should not be used outside of the compiler.
711 pub fn rustc_peek<T>(_: T) -> T;
713 /// Aborts the execution of the process.
715 /// Note that, unlike most intrinsics, this is safe to call;
716 /// it does not require an `unsafe` block.
717 /// Therefore, implementations must not require the user to uphold
718 /// any safety invariants.
720 /// [`std::process::abort`](../../std/process/fn.abort.html) is to be preferred if possible,
721 /// as its behavior is more user-friendly and more stable.
723 /// The current implementation of `intrinsics::abort` is to invoke an invalid instruction,
724 /// on most platforms.
726 /// process will probably terminate with a signal like `SIGABRT`, `SIGILL`, `SIGTRAP`, `SIGSEGV` or
727 /// `SIGBUS`. The precise behaviour is not guaranteed and not stable.
730 /// Informs the optimizer that this point in the code is not reachable,
731 /// enabling further optimizations.
733 /// N.B., this is very different from the `unreachable!()` macro: Unlike the
734 /// macro, which panics when it is executed, it is *undefined behavior* to
735 /// reach code marked with this function.
737 /// The stabilized version of this intrinsic is [`core::hint::unreachable_unchecked`].
738 #[rustc_const_stable(feature = "const_unreachable_unchecked", since = "1.57.0")]
739 pub fn unreachable() -> !;
741 /// Informs the optimizer that a condition is always true.
742 /// If the condition is false, the behavior is undefined.
744 /// No code is generated for this intrinsic, but the optimizer will try
745 /// to preserve it (and its condition) between passes, which may interfere
746 /// with optimization of surrounding code and reduce performance. It should
747 /// not be used if the invariant can be discovered by the optimizer on its
748 /// own, or if it does not enable any significant optimizations.
750 /// This intrinsic does not have a stable counterpart.
751 #[rustc_const_unstable(feature = "const_assume", issue = "76972")]
752 pub fn assume(b: bool);
754 /// Hints to the compiler that branch condition is likely to be true.
755 /// Returns the value passed to it.
757 /// Any use other than with `if` statements will probably not have an effect.
759 /// Note that, unlike most intrinsics, this is safe to call;
760 /// it does not require an `unsafe` block.
761 /// Therefore, implementations must not require the user to uphold
762 /// any safety invariants.
764 /// This intrinsic does not have a stable counterpart.
765 #[rustc_const_unstable(feature = "const_likely", issue = "none")]
766 pub fn likely(b: bool) -> bool;
768 /// Hints to the compiler that branch condition is likely to be false.
769 /// Returns the value passed to it.
771 /// Any use other than with `if` statements will probably not have an effect.
773 /// Note that, unlike most intrinsics, this is safe to call;
774 /// it does not require an `unsafe` block.
775 /// Therefore, implementations must not require the user to uphold
776 /// any safety invariants.
778 /// This intrinsic does not have a stable counterpart.
779 #[rustc_const_unstable(feature = "const_likely", issue = "none")]
780 pub fn unlikely(b: bool) -> bool;
782 /// Executes a breakpoint trap, for inspection by a debugger.
784 /// This intrinsic does not have a stable counterpart.
787 /// The size of a type in bytes.
789 /// Note that, unlike most intrinsics, this is safe to call;
790 /// it does not require an `unsafe` block.
791 /// Therefore, implementations must not require the user to uphold
792 /// any safety invariants.
794 /// More specifically, this is the offset in bytes between successive
795 /// items of the same type, including alignment padding.
797 /// The stabilized version of this intrinsic is [`core::mem::size_of`].
798 #[rustc_const_stable(feature = "const_size_of", since = "1.40.0")]
799 pub fn size_of<T>() -> usize;
801 /// The minimum alignment of a type.
803 /// Note that, unlike most intrinsics, this is safe to call;
804 /// it does not require an `unsafe` block.
805 /// Therefore, implementations must not require the user to uphold
806 /// any safety invariants.
808 /// The stabilized version of this intrinsic is [`core::mem::align_of`].
809 #[rustc_const_stable(feature = "const_min_align_of", since = "1.40.0")]
810 pub fn min_align_of<T>() -> usize;
811 /// The preferred alignment of a type.
813 /// This intrinsic does not have a stable counterpart.
814 #[rustc_const_unstable(feature = "const_pref_align_of", issue = "none")]
815 pub fn pref_align_of<T>() -> usize;
817 /// The size of the referenced value in bytes.
819 /// The stabilized version of this intrinsic is [`mem::size_of_val`].
820 #[rustc_const_unstable(feature = "const_size_of_val", issue = "46571")]
821 pub fn size_of_val<T: ?Sized>(_: *const T) -> usize;
822 /// The required alignment of the referenced value.
824 /// The stabilized version of this intrinsic is [`core::mem::align_of_val`].
825 #[rustc_const_unstable(feature = "const_align_of_val", issue = "46571")]
826 pub fn min_align_of_val<T: ?Sized>(_: *const T) -> usize;
828 /// Gets a static string slice containing the name of a type.
830 /// Note that, unlike most intrinsics, this is safe to call;
831 /// it does not require an `unsafe` block.
832 /// Therefore, implementations must not require the user to uphold
833 /// any safety invariants.
835 /// The stabilized version of this intrinsic is [`core::any::type_name`].
836 #[rustc_const_unstable(feature = "const_type_name", issue = "63084")]
837 pub fn type_name<T: ?Sized>() -> &'static str;
839 /// Gets an identifier which is globally unique to the specified type. This
840 /// function will return the same value for a type regardless of whichever
841 /// crate it is invoked in.
843 /// Note that, unlike most intrinsics, this is safe to call;
844 /// it does not require an `unsafe` block.
845 /// Therefore, implementations must not require the user to uphold
846 /// any safety invariants.
848 /// The stabilized version of this intrinsic is [`core::any::TypeId::of`].
849 #[rustc_const_unstable(feature = "const_type_id", issue = "77125")]
850 pub fn type_id<T: ?Sized + 'static>() -> u64;
852 /// A guard for unsafe functions that cannot ever be executed if `T` is uninhabited:
853 /// This will statically either panic, or do nothing.
855 /// This intrinsic does not have a stable counterpart.
856 #[rustc_const_stable(feature = "const_assert_type", since = "1.59.0")]
857 pub fn assert_inhabited<T>();
859 /// A guard for unsafe functions that cannot ever be executed if `T` does not permit
860 /// zero-initialization: This will statically either panic, or do nothing.
862 /// This intrinsic does not have a stable counterpart.
863 #[rustc_const_unstable(feature = "const_assert_type2", issue = "none")]
864 pub fn assert_zero_valid<T>();
866 /// A guard for unsafe functions that cannot ever be executed if `T` has invalid
867 /// bit patterns: This will statically either panic, or do nothing.
869 /// This intrinsic does not have a stable counterpart.
870 #[rustc_const_unstable(feature = "const_assert_type2", issue = "none")]
871 pub fn assert_uninit_valid<T>();
873 /// Gets a reference to a static `Location` indicating where it was called.
875 /// Note that, unlike most intrinsics, this is safe to call;
876 /// it does not require an `unsafe` block.
877 /// Therefore, implementations must not require the user to uphold
878 /// any safety invariants.
880 /// Consider using [`core::panic::Location::caller`] instead.
881 #[rustc_const_unstable(feature = "const_caller_location", issue = "76156")]
882 pub fn caller_location() -> &'static crate::panic::Location<'static>;
884 /// Moves a value out of scope without running drop glue.
886 /// This exists solely for [`mem::forget_unsized`]; normal `forget` uses
887 /// `ManuallyDrop` instead.
889 /// Note that, unlike most intrinsics, this is safe to call;
890 /// it does not require an `unsafe` block.
891 /// Therefore, implementations must not require the user to uphold
892 /// any safety invariants.
893 #[rustc_const_unstable(feature = "const_intrinsic_forget", issue = "none")]
894 pub fn forget<T: ?Sized>(_: T);
896 /// Reinterprets the bits of a value of one type as another type.
898 /// Both types must have the same size. Neither the original, nor the result,
899 /// may be an [invalid value](../../nomicon/what-unsafe-does.html).
901 /// `transmute` is semantically equivalent to a bitwise move of one type
902 /// into another. It copies the bits from the source value into the
903 /// destination value, then forgets the original. It's equivalent to C's
904 /// `memcpy` under the hood, just like `transmute_copy`.
906 /// Because `transmute` is a by-value operation, alignment of the *transmuted values
907 /// themselves* is not a concern. As with any other function, the compiler already ensures
908 /// both `T` and `U` are properly aligned. However, when transmuting values that *point
909 /// elsewhere* (such as pointers, references, boxes…), the caller has to ensure proper
910 /// alignment of the pointed-to values.
912 /// `transmute` is **incredibly** unsafe. There are a vast number of ways to
913 /// cause [undefined behavior][ub] with this function. `transmute` should be
914 /// the absolute last resort.
916 /// Transmuting pointers to integers in a `const` context is [undefined behavior][ub].
917 /// Any attempt to use the resulting value for integer operations will abort const-evaluation.
919 /// The [nomicon](../../nomicon/transmutes.html) has additional
922 /// [ub]: ../../reference/behavior-considered-undefined.html
926 /// There are a few things that `transmute` is really useful for.
928 /// Turning a pointer into a function pointer. This is *not* portable to
929 /// machines where function pointers and data pointers have different sizes.
932 /// fn foo() -> i32 {
935 /// let pointer = foo as *const ();
936 /// let function = unsafe {
937 /// std::mem::transmute::<*const (), fn() -> i32>(pointer)
939 /// assert_eq!(function(), 0);
942 /// Extending a lifetime, or shortening an invariant lifetime. This is
943 /// advanced, very unsafe Rust!
946 /// struct R<'a>(&'a i32);
947 /// unsafe fn extend_lifetime<'b>(r: R<'b>) -> R<'static> {
948 /// std::mem::transmute::<R<'b>, R<'static>>(r)
951 /// unsafe fn shorten_invariant_lifetime<'b, 'c>(r: &'b mut R<'static>)
952 /// -> &'b mut R<'c> {
953 /// std::mem::transmute::<&'b mut R<'static>, &'b mut R<'c>>(r)
959 /// Don't despair: many uses of `transmute` can be achieved through other means.
960 /// Below are common applications of `transmute` which can be replaced with safer
963 /// Turning raw bytes(`&[u8]`) to `u32`, `f64`, etc.:
966 /// let raw_bytes = [0x78, 0x56, 0x34, 0x12];
968 /// let num = unsafe {
969 /// std::mem::transmute::<[u8; 4], u32>(raw_bytes)
972 /// // use `u32::from_ne_bytes` instead
973 /// let num = u32::from_ne_bytes(raw_bytes);
974 /// // or use `u32::from_le_bytes` or `u32::from_be_bytes` to specify the endianness
975 /// let num = u32::from_le_bytes(raw_bytes);
976 /// assert_eq!(num, 0x12345678);
977 /// let num = u32::from_be_bytes(raw_bytes);
978 /// assert_eq!(num, 0x78563412);
981 /// Turning a pointer into a `usize`:
985 /// let ptr_num_transmute = unsafe {
986 /// std::mem::transmute::<&i32, usize>(ptr)
989 /// // Use an `as` cast instead
990 /// let ptr_num_cast = ptr as *const i32 as usize;
993 /// Turning a `*mut T` into an `&mut T`:
996 /// let ptr: *mut i32 = &mut 0;
997 /// let ref_transmuted = unsafe {
998 /// std::mem::transmute::<*mut i32, &mut i32>(ptr)
1001 /// // Use a reborrow instead
1002 /// let ref_casted = unsafe { &mut *ptr };
1005 /// Turning an `&mut T` into an `&mut U`:
1008 /// let ptr = &mut 0;
1009 /// let val_transmuted = unsafe {
1010 /// std::mem::transmute::<&mut i32, &mut u32>(ptr)
1013 /// // Now, put together `as` and reborrowing - note the chaining of `as`
1014 /// // `as` is not transitive
1015 /// let val_casts = unsafe { &mut *(ptr as *mut i32 as *mut u32) };
1018 /// Turning an `&str` into a `&[u8]`:
1021 /// // this is not a good way to do this.
1022 /// let slice = unsafe { std::mem::transmute::<&str, &[u8]>("Rust") };
1023 /// assert_eq!(slice, &[82, 117, 115, 116]);
1025 /// // You could use `str::as_bytes`
1026 /// let slice = "Rust".as_bytes();
1027 /// assert_eq!(slice, &[82, 117, 115, 116]);
1029 /// // Or, just use a byte string, if you have control over the string
1031 /// assert_eq!(b"Rust", &[82, 117, 115, 116]);
1034 /// Turning a `Vec<&T>` into a `Vec<Option<&T>>`.
1036 /// To transmute the inner type of the contents of a container, you must make sure to not
1037 /// violate any of the container's invariants. For `Vec`, this means that both the size
1038 /// *and alignment* of the inner types have to match. Other containers might rely on the
1039 /// size of the type, alignment, or even the `TypeId`, in which case transmuting wouldn't
1040 /// be possible at all without violating the container invariants.
1043 /// let store = [0, 1, 2, 3];
1044 /// let v_orig = store.iter().collect::<Vec<&i32>>();
1046 /// // clone the vector as we will reuse them later
1047 /// let v_clone = v_orig.clone();
1049 /// // Using transmute: this relies on the unspecified data layout of `Vec`, which is a
1050 /// // bad idea and could cause Undefined Behavior.
1051 /// // However, it is no-copy.
1052 /// let v_transmuted = unsafe {
1053 /// std::mem::transmute::<Vec<&i32>, Vec<Option<&i32>>>(v_clone)
1056 /// let v_clone = v_orig.clone();
1058 /// // This is the suggested, safe way.
1059 /// // It does copy the entire vector, though, into a new array.
1060 /// let v_collected = v_clone.into_iter()
1062 /// .collect::<Vec<Option<&i32>>>();
1064 /// let v_clone = v_orig.clone();
1066 /// // This is the proper no-copy, unsafe way of "transmuting" a `Vec`, without relying on the
1067 /// // data layout. Instead of literally calling `transmute`, we perform a pointer cast, but
1068 /// // in terms of converting the original inner type (`&i32`) to the new one (`Option<&i32>`),
1069 /// // this has all the same caveats. Besides the information provided above, also consult the
1070 /// // [`from_raw_parts`] documentation.
1071 /// let v_from_raw = unsafe {
1072 // FIXME Update this when vec_into_raw_parts is stabilized
1073 /// // Ensure the original vector is not dropped.
1074 /// let mut v_clone = std::mem::ManuallyDrop::new(v_clone);
1075 /// Vec::from_raw_parts(v_clone.as_mut_ptr() as *mut Option<&i32>,
1077 /// v_clone.capacity())
1081 /// [`from_raw_parts`]: ../../std/vec/struct.Vec.html#method.from_raw_parts
1083 /// Implementing `split_at_mut`:
1086 /// use std::{slice, mem};
1088 /// // There are multiple ways to do this, and there are multiple problems
1089 /// // with the following (transmute) way.
1090 /// fn split_at_mut_transmute<T>(slice: &mut [T], mid: usize)
1091 /// -> (&mut [T], &mut [T]) {
1092 /// let len = slice.len();
1093 /// assert!(mid <= len);
1095 /// let slice2 = mem::transmute::<&mut [T], &mut [T]>(slice);
1096 /// // first: transmute is not type safe; all it checks is that T and
1097 /// // U are of the same size. Second, right here, you have two
1098 /// // mutable references pointing to the same memory.
1099 /// (&mut slice[0..mid], &mut slice2[mid..len])
1103 /// // This gets rid of the type safety problems; `&mut *` will *only* give
1104 /// // you an `&mut T` from an `&mut T` or `*mut T`.
1105 /// fn split_at_mut_casts<T>(slice: &mut [T], mid: usize)
1106 /// -> (&mut [T], &mut [T]) {
1107 /// let len = slice.len();
1108 /// assert!(mid <= len);
1110 /// let slice2 = &mut *(slice as *mut [T]);
1111 /// // however, you still have two mutable references pointing to
1112 /// // the same memory.
1113 /// (&mut slice[0..mid], &mut slice2[mid..len])
1117 /// // This is how the standard library does it. This is the best method, if
1118 /// // you need to do something like this
1119 /// fn split_at_stdlib<T>(slice: &mut [T], mid: usize)
1120 /// -> (&mut [T], &mut [T]) {
1121 /// let len = slice.len();
1122 /// assert!(mid <= len);
1124 /// let ptr = slice.as_mut_ptr();
1125 /// // This now has three mutable references pointing at the same
1126 /// // memory. `slice`, the rvalue ret.0, and the rvalue ret.1.
1127 /// // `slice` is never used after `let ptr = ...`, and so one can
1128 /// // treat it as "dead", and therefore, you only have two real
1129 /// // mutable slices.
1130 /// (slice::from_raw_parts_mut(ptr, mid),
1131 /// slice::from_raw_parts_mut(ptr.add(mid), len - mid))
1135 #[stable(feature = "rust1", since = "1.0.0")]
1136 #[rustc_const_stable(feature = "const_transmute", since = "1.46.0")]
1137 #[rustc_diagnostic_item = "transmute"]
1138 pub fn transmute<T, U>(e: T) -> U;
1140 /// Returns `true` if the actual type given as `T` requires drop
1141 /// glue; returns `false` if the actual type provided for `T`
1142 /// implements `Copy`.
1144 /// If the actual type neither requires drop glue nor implements
1145 /// `Copy`, then the return value of this function is unspecified.
1147 /// Note that, unlike most intrinsics, this is safe to call;
1148 /// it does not require an `unsafe` block.
1149 /// Therefore, implementations must not require the user to uphold
1150 /// any safety invariants.
1152 /// The stabilized version of this intrinsic is [`mem::needs_drop`](crate::mem::needs_drop).
1153 #[rustc_const_stable(feature = "const_needs_drop", since = "1.40.0")]
1154 pub fn needs_drop<T>() -> bool;
1156 /// Calculates the offset from a pointer.
1158 /// This is implemented as an intrinsic to avoid converting to and from an
1159 /// integer, since the conversion would throw away aliasing information.
1163 /// Both the starting and resulting pointer must be either in bounds or one
1164 /// byte past the end of an allocated object. If either pointer is out of
1165 /// bounds or arithmetic overflow occurs then any further use of the
1166 /// returned value will result in undefined behavior.
1168 /// The stabilized version of this intrinsic is [`pointer::offset`].
1169 #[must_use = "returns a new pointer rather than modifying its argument"]
1170 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
1171 pub fn offset<T>(dst: *const T, offset: isize) -> *const T;
1173 /// Calculates the offset from a pointer, potentially wrapping.
1175 /// This is implemented as an intrinsic to avoid converting to and from an
1176 /// integer, since the conversion inhibits certain optimizations.
1180 /// Unlike the `offset` intrinsic, this intrinsic does not restrict the
1181 /// resulting pointer to point into or one byte past the end of an allocated
1182 /// object, and it wraps with two's complement arithmetic. The resulting
1183 /// value is not necessarily valid to be used to actually access memory.
1185 /// The stabilized version of this intrinsic is [`pointer::wrapping_offset`].
1186 #[must_use = "returns a new pointer rather than modifying its argument"]
1187 #[rustc_const_unstable(feature = "const_ptr_offset", issue = "71499")]
1188 pub fn arith_offset<T>(dst: *const T, offset: isize) -> *const T;
1190 /// Equivalent to the appropriate `llvm.memcpy.p0i8.0i8.*` intrinsic, with
1191 /// a size of `count` * `size_of::<T>()` and an alignment of
1192 /// `min_align_of::<T>()`
1194 /// The volatile parameter is set to `true`, so it will not be optimized out
1195 /// unless size is equal to zero.
1197 /// This intrinsic does not have a stable counterpart.
1198 pub fn volatile_copy_nonoverlapping_memory<T>(dst: *mut T, src: *const T, count: usize);
1199 /// Equivalent to the appropriate `llvm.memmove.p0i8.0i8.*` intrinsic, with
1200 /// a size of `count * size_of::<T>()` and an alignment of
1201 /// `min_align_of::<T>()`
1203 /// The volatile parameter is set to `true`, so it will not be optimized out
1204 /// unless size is equal to zero.
1206 /// This intrinsic does not have a stable counterpart.
1207 pub fn volatile_copy_memory<T>(dst: *mut T, src: *const T, count: usize);
1208 /// Equivalent to the appropriate `llvm.memset.p0i8.*` intrinsic, with a
1209 /// size of `count * size_of::<T>()` and an alignment of
1210 /// `min_align_of::<T>()`.
1212 /// The volatile parameter is set to `true`, so it will not be optimized out
1213 /// unless size is equal to zero.
1215 /// This intrinsic does not have a stable counterpart.
1216 pub fn volatile_set_memory<T>(dst: *mut T, val: u8, count: usize);
1218 /// Performs a volatile load from the `src` pointer.
1220 /// The stabilized version of this intrinsic is [`core::ptr::read_volatile`].
1221 pub fn volatile_load<T>(src: *const T) -> T;
1222 /// Performs a volatile store to the `dst` pointer.
1224 /// The stabilized version of this intrinsic is [`core::ptr::write_volatile`].
1225 pub fn volatile_store<T>(dst: *mut T, val: T);
1227 /// Performs a volatile load from the `src` pointer
1228 /// The pointer is not required to be aligned.
1230 /// This intrinsic does not have a stable counterpart.
1231 pub fn unaligned_volatile_load<T>(src: *const T) -> T;
1232 /// Performs a volatile store to the `dst` pointer.
1233 /// The pointer is not required to be aligned.
1235 /// This intrinsic does not have a stable counterpart.
1236 pub fn unaligned_volatile_store<T>(dst: *mut T, val: T);
1238 /// Returns the square root of an `f32`
1240 /// The stabilized version of this intrinsic is
1241 /// [`f32::sqrt`](../../std/primitive.f32.html#method.sqrt)
1242 pub fn sqrtf32(x: f32) -> f32;
1243 /// Returns the square root of an `f64`
1245 /// The stabilized version of this intrinsic is
1246 /// [`f64::sqrt`](../../std/primitive.f64.html#method.sqrt)
1247 pub fn sqrtf64(x: f64) -> f64;
1249 /// Raises an `f32` to an integer power.
1251 /// The stabilized version of this intrinsic is
1252 /// [`f32::powi`](../../std/primitive.f32.html#method.powi)
1253 pub fn powif32(a: f32, x: i32) -> f32;
1254 /// Raises an `f64` to an integer power.
1256 /// The stabilized version of this intrinsic is
1257 /// [`f64::powi`](../../std/primitive.f64.html#method.powi)
1258 pub fn powif64(a: f64, x: i32) -> f64;
1260 /// Returns the sine of an `f32`.
1262 /// The stabilized version of this intrinsic is
1263 /// [`f32::sin`](../../std/primitive.f32.html#method.sin)
1264 pub fn sinf32(x: f32) -> f32;
1265 /// Returns the sine of an `f64`.
1267 /// The stabilized version of this intrinsic is
1268 /// [`f64::sin`](../../std/primitive.f64.html#method.sin)
1269 pub fn sinf64(x: f64) -> f64;
1271 /// Returns the cosine of an `f32`.
1273 /// The stabilized version of this intrinsic is
1274 /// [`f32::cos`](../../std/primitive.f32.html#method.cos)
1275 pub fn cosf32(x: f32) -> f32;
1276 /// Returns the cosine of an `f64`.
1278 /// The stabilized version of this intrinsic is
1279 /// [`f64::cos`](../../std/primitive.f64.html#method.cos)
1280 pub fn cosf64(x: f64) -> f64;
1282 /// Raises an `f32` to an `f32` power.
1284 /// The stabilized version of this intrinsic is
1285 /// [`f32::powf`](../../std/primitive.f32.html#method.powf)
1286 pub fn powf32(a: f32, x: f32) -> f32;
1287 /// Raises an `f64` to an `f64` power.
1289 /// The stabilized version of this intrinsic is
1290 /// [`f64::powf`](../../std/primitive.f64.html#method.powf)
1291 pub fn powf64(a: f64, x: f64) -> f64;
1293 /// Returns the exponential of an `f32`.
1295 /// The stabilized version of this intrinsic is
1296 /// [`f32::exp`](../../std/primitive.f32.html#method.exp)
1297 pub fn expf32(x: f32) -> f32;
1298 /// Returns the exponential of an `f64`.
1300 /// The stabilized version of this intrinsic is
1301 /// [`f64::exp`](../../std/primitive.f64.html#method.exp)
1302 pub fn expf64(x: f64) -> f64;
1304 /// Returns 2 raised to the power of an `f32`.
1306 /// The stabilized version of this intrinsic is
1307 /// [`f32::exp2`](../../std/primitive.f32.html#method.exp2)
1308 pub fn exp2f32(x: f32) -> f32;
1309 /// Returns 2 raised to the power of an `f64`.
1311 /// The stabilized version of this intrinsic is
1312 /// [`f64::exp2`](../../std/primitive.f64.html#method.exp2)
1313 pub fn exp2f64(x: f64) -> f64;
1315 /// Returns the natural logarithm of an `f32`.
1317 /// The stabilized version of this intrinsic is
1318 /// [`f32::ln`](../../std/primitive.f32.html#method.ln)
1319 pub fn logf32(x: f32) -> f32;
1320 /// Returns the natural logarithm of an `f64`.
1322 /// The stabilized version of this intrinsic is
1323 /// [`f64::ln`](../../std/primitive.f64.html#method.ln)
1324 pub fn logf64(x: f64) -> f64;
1326 /// Returns the base 10 logarithm of an `f32`.
1328 /// The stabilized version of this intrinsic is
1329 /// [`f32::log10`](../../std/primitive.f32.html#method.log10)
1330 pub fn log10f32(x: f32) -> f32;
1331 /// Returns the base 10 logarithm of an `f64`.
1333 /// The stabilized version of this intrinsic is
1334 /// [`f64::log10`](../../std/primitive.f64.html#method.log10)
1335 pub fn log10f64(x: f64) -> f64;
1337 /// Returns the base 2 logarithm of an `f32`.
1339 /// The stabilized version of this intrinsic is
1340 /// [`f32::log2`](../../std/primitive.f32.html#method.log2)
1341 pub fn log2f32(x: f32) -> f32;
1342 /// Returns the base 2 logarithm of an `f64`.
1344 /// The stabilized version of this intrinsic is
1345 /// [`f64::log2`](../../std/primitive.f64.html#method.log2)
1346 pub fn log2f64(x: f64) -> f64;
1348 /// Returns `a * b + c` for `f32` values.
1350 /// The stabilized version of this intrinsic is
1351 /// [`f32::mul_add`](../../std/primitive.f32.html#method.mul_add)
1352 pub fn fmaf32(a: f32, b: f32, c: f32) -> f32;
1353 /// Returns `a * b + c` for `f64` values.
1355 /// The stabilized version of this intrinsic is
1356 /// [`f64::mul_add`](../../std/primitive.f64.html#method.mul_add)
1357 pub fn fmaf64(a: f64, b: f64, c: f64) -> f64;
1359 /// Returns the absolute value of an `f32`.
1361 /// The stabilized version of this intrinsic is
1362 /// [`f32::abs`](../../std/primitive.f32.html#method.abs)
1363 pub fn fabsf32(x: f32) -> f32;
1364 /// Returns the absolute value of an `f64`.
1366 /// The stabilized version of this intrinsic is
1367 /// [`f64::abs`](../../std/primitive.f64.html#method.abs)
1368 pub fn fabsf64(x: f64) -> f64;
1370 /// Returns the minimum of two `f32` values.
1372 /// Note that, unlike most intrinsics, this is safe to call;
1373 /// it does not require an `unsafe` block.
1374 /// Therefore, implementations must not require the user to uphold
1375 /// any safety invariants.
1377 /// The stabilized version of this intrinsic is
1379 pub fn minnumf32(x: f32, y: f32) -> f32;
1380 /// Returns the minimum of two `f64` values.
1382 /// Note that, unlike most intrinsics, this is safe to call;
1383 /// it does not require an `unsafe` block.
1384 /// Therefore, implementations must not require the user to uphold
1385 /// any safety invariants.
1387 /// The stabilized version of this intrinsic is
1389 pub fn minnumf64(x: f64, y: f64) -> f64;
1390 /// Returns the maximum of two `f32` values.
1392 /// Note that, unlike most intrinsics, this is safe to call;
1393 /// it does not require an `unsafe` block.
1394 /// Therefore, implementations must not require the user to uphold
1395 /// any safety invariants.
1397 /// The stabilized version of this intrinsic is
1399 pub fn maxnumf32(x: f32, y: f32) -> f32;
1400 /// Returns the maximum of two `f64` values.
1402 /// Note that, unlike most intrinsics, this is safe to call;
1403 /// it does not require an `unsafe` block.
1404 /// Therefore, implementations must not require the user to uphold
1405 /// any safety invariants.
1407 /// The stabilized version of this intrinsic is
1409 pub fn maxnumf64(x: f64, y: f64) -> f64;
1411 /// Copies the sign from `y` to `x` for `f32` values.
1413 /// The stabilized version of this intrinsic is
1414 /// [`f32::copysign`](../../std/primitive.f32.html#method.copysign)
1415 pub fn copysignf32(x: f32, y: f32) -> f32;
1416 /// Copies the sign from `y` to `x` for `f64` values.
1418 /// The stabilized version of this intrinsic is
1419 /// [`f64::copysign`](../../std/primitive.f64.html#method.copysign)
1420 pub fn copysignf64(x: f64, y: f64) -> f64;
1422 /// Returns the largest integer less than or equal to an `f32`.
1424 /// The stabilized version of this intrinsic is
1425 /// [`f32::floor`](../../std/primitive.f32.html#method.floor)
1426 pub fn floorf32(x: f32) -> f32;
1427 /// Returns the largest integer less than or equal to an `f64`.
1429 /// The stabilized version of this intrinsic is
1430 /// [`f64::floor`](../../std/primitive.f64.html#method.floor)
1431 pub fn floorf64(x: f64) -> f64;
1433 /// Returns the smallest integer greater than or equal to an `f32`.
1435 /// The stabilized version of this intrinsic is
1436 /// [`f32::ceil`](../../std/primitive.f32.html#method.ceil)
1437 pub fn ceilf32(x: f32) -> f32;
1438 /// Returns the smallest integer greater than or equal to an `f64`.
1440 /// The stabilized version of this intrinsic is
1441 /// [`f64::ceil`](../../std/primitive.f64.html#method.ceil)
1442 pub fn ceilf64(x: f64) -> f64;
1444 /// Returns the integer part of an `f32`.
1446 /// The stabilized version of this intrinsic is
1447 /// [`f32::trunc`](../../std/primitive.f32.html#method.trunc)
1448 pub fn truncf32(x: f32) -> f32;
1449 /// Returns the integer part of an `f64`.
1451 /// The stabilized version of this intrinsic is
1452 /// [`f64::trunc`](../../std/primitive.f64.html#method.trunc)
1453 pub fn truncf64(x: f64) -> f64;
1455 /// Returns the nearest integer to an `f32`. May raise an inexact floating-point exception
1456 /// if the argument is not an integer.
1457 pub fn rintf32(x: f32) -> f32;
1458 /// Returns the nearest integer to an `f64`. May raise an inexact floating-point exception
1459 /// if the argument is not an integer.
1460 pub fn rintf64(x: f64) -> f64;
1462 /// Returns the nearest integer to an `f32`.
1464 /// This intrinsic does not have a stable counterpart.
1465 pub fn nearbyintf32(x: f32) -> f32;
1466 /// Returns the nearest integer to an `f64`.
1468 /// This intrinsic does not have a stable counterpart.
1469 pub fn nearbyintf64(x: f64) -> f64;
1471 /// Returns the nearest integer to an `f32`. Rounds half-way cases away from zero.
1473 /// The stabilized version of this intrinsic is
1474 /// [`f32::round`](../../std/primitive.f32.html#method.round)
1475 pub fn roundf32(x: f32) -> f32;
1476 /// Returns the nearest integer to an `f64`. Rounds half-way cases away from zero.
1478 /// The stabilized version of this intrinsic is
1479 /// [`f64::round`](../../std/primitive.f64.html#method.round)
1480 pub fn roundf64(x: f64) -> f64;
1482 /// Float addition that allows optimizations based on algebraic rules.
1483 /// May assume inputs are finite.
1485 /// This intrinsic does not have a stable counterpart.
1486 pub fn fadd_fast<T: Copy>(a: T, b: T) -> T;
1488 /// Float subtraction that allows optimizations based on algebraic rules.
1489 /// May assume inputs are finite.
1491 /// This intrinsic does not have a stable counterpart.
1492 pub fn fsub_fast<T: Copy>(a: T, b: T) -> T;
1494 /// Float multiplication that allows optimizations based on algebraic rules.
1495 /// May assume inputs are finite.
1497 /// This intrinsic does not have a stable counterpart.
1498 pub fn fmul_fast<T: Copy>(a: T, b: T) -> T;
1500 /// Float division that allows optimizations based on algebraic rules.
1501 /// May assume inputs are finite.
1503 /// This intrinsic does not have a stable counterpart.
1504 pub fn fdiv_fast<T: Copy>(a: T, b: T) -> T;
1506 /// Float remainder that allows optimizations based on algebraic rules.
1507 /// May assume inputs are finite.
1509 /// This intrinsic does not have a stable counterpart.
1510 pub fn frem_fast<T: Copy>(a: T, b: T) -> T;
1512 /// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range
1513 /// (<https://github.com/rust-lang/rust/issues/10184>)
1515 /// Stabilized as [`f32::to_int_unchecked`] and [`f64::to_int_unchecked`].
1516 pub fn float_to_int_unchecked<Float: Copy, Int: Copy>(value: Float) -> Int;
1518 /// Returns the number of bits set in an integer type `T`
1520 /// Note that, unlike most intrinsics, this is safe to call;
1521 /// it does not require an `unsafe` block.
1522 /// Therefore, implementations must not require the user to uphold
1523 /// any safety invariants.
1525 /// The stabilized versions of this intrinsic are available on the integer
1526 /// primitives via the `count_ones` method. For example,
1527 /// [`u32::count_ones`]
1528 #[rustc_const_stable(feature = "const_ctpop", since = "1.40.0")]
1529 pub fn ctpop<T: Copy>(x: T) -> T;
1531 /// Returns the number of leading unset bits (zeroes) in an integer type `T`.
1533 /// Note that, unlike most intrinsics, this is safe to call;
1534 /// it does not require an `unsafe` block.
1535 /// Therefore, implementations must not require the user to uphold
1536 /// any safety invariants.
1538 /// The stabilized versions of this intrinsic are available on the integer
1539 /// primitives via the `leading_zeros` method. For example,
1540 /// [`u32::leading_zeros`]
1545 /// #![feature(core_intrinsics)]
1547 /// use std::intrinsics::ctlz;
1549 /// let x = 0b0001_1100_u8;
1550 /// let num_leading = ctlz(x);
1551 /// assert_eq!(num_leading, 3);
1554 /// An `x` with value `0` will return the bit width of `T`.
1557 /// #![feature(core_intrinsics)]
1559 /// use std::intrinsics::ctlz;
1562 /// let num_leading = ctlz(x);
1563 /// assert_eq!(num_leading, 16);
1565 #[rustc_const_stable(feature = "const_ctlz", since = "1.40.0")]
1566 pub fn ctlz<T: Copy>(x: T) -> T;
1568 /// Like `ctlz`, but extra-unsafe as it returns `undef` when
1569 /// given an `x` with value `0`.
1571 /// This intrinsic does not have a stable counterpart.
1576 /// #![feature(core_intrinsics)]
1578 /// use std::intrinsics::ctlz_nonzero;
1580 /// let x = 0b0001_1100_u8;
1581 /// let num_leading = unsafe { ctlz_nonzero(x) };
1582 /// assert_eq!(num_leading, 3);
1584 #[rustc_const_stable(feature = "constctlz", since = "1.50.0")]
1585 pub fn ctlz_nonzero<T: Copy>(x: T) -> T;
1587 /// Returns the number of trailing unset bits (zeroes) in an integer type `T`.
1589 /// Note that, unlike most intrinsics, this is safe to call;
1590 /// it does not require an `unsafe` block.
1591 /// Therefore, implementations must not require the user to uphold
1592 /// any safety invariants.
1594 /// The stabilized versions of this intrinsic are available on the integer
1595 /// primitives via the `trailing_zeros` method. For example,
1596 /// [`u32::trailing_zeros`]
1601 /// #![feature(core_intrinsics)]
1603 /// use std::intrinsics::cttz;
1605 /// let x = 0b0011_1000_u8;
1606 /// let num_trailing = cttz(x);
1607 /// assert_eq!(num_trailing, 3);
1610 /// An `x` with value `0` will return the bit width of `T`:
1613 /// #![feature(core_intrinsics)]
1615 /// use std::intrinsics::cttz;
1618 /// let num_trailing = cttz(x);
1619 /// assert_eq!(num_trailing, 16);
1621 #[rustc_const_stable(feature = "const_cttz", since = "1.40.0")]
1622 pub fn cttz<T: Copy>(x: T) -> T;
1624 /// Like `cttz`, but extra-unsafe as it returns `undef` when
1625 /// given an `x` with value `0`.
1627 /// This intrinsic does not have a stable counterpart.
1632 /// #![feature(core_intrinsics)]
1634 /// use std::intrinsics::cttz_nonzero;
1636 /// let x = 0b0011_1000_u8;
1637 /// let num_trailing = unsafe { cttz_nonzero(x) };
1638 /// assert_eq!(num_trailing, 3);
1640 #[rustc_const_stable(feature = "const_cttz", since = "1.53.0")]
1641 pub fn cttz_nonzero<T: Copy>(x: T) -> T;
1643 /// Reverses the bytes in an integer type `T`.
1645 /// Note that, unlike most intrinsics, this is safe to call;
1646 /// it does not require an `unsafe` block.
1647 /// Therefore, implementations must not require the user to uphold
1648 /// any safety invariants.
1650 /// The stabilized versions of this intrinsic are available on the integer
1651 /// primitives via the `swap_bytes` method. For example,
1652 /// [`u32::swap_bytes`]
1653 #[rustc_const_stable(feature = "const_bswap", since = "1.40.0")]
1654 pub fn bswap<T: Copy>(x: T) -> T;
1656 /// Reverses the bits in an integer type `T`.
1658 /// Note that, unlike most intrinsics, this is safe to call;
1659 /// it does not require an `unsafe` block.
1660 /// Therefore, implementations must not require the user to uphold
1661 /// any safety invariants.
1663 /// The stabilized versions of this intrinsic are available on the integer
1664 /// primitives via the `reverse_bits` method. For example,
1665 /// [`u32::reverse_bits`]
1666 #[rustc_const_stable(feature = "const_bitreverse", since = "1.40.0")]
1667 pub fn bitreverse<T: Copy>(x: T) -> T;
1669 /// Performs checked integer addition.
1671 /// Note that, unlike most intrinsics, this is safe to call;
1672 /// it does not require an `unsafe` block.
1673 /// Therefore, implementations must not require the user to uphold
1674 /// any safety invariants.
1676 /// The stabilized versions of this intrinsic are available on the integer
1677 /// primitives via the `overflowing_add` method. For example,
1678 /// [`u32::overflowing_add`]
1679 #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")]
1680 pub fn add_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1682 /// Performs checked integer subtraction
1684 /// Note that, unlike most intrinsics, this is safe to call;
1685 /// it does not require an `unsafe` block.
1686 /// Therefore, implementations must not require the user to uphold
1687 /// any safety invariants.
1689 /// The stabilized versions of this intrinsic are available on the integer
1690 /// primitives via the `overflowing_sub` method. For example,
1691 /// [`u32::overflowing_sub`]
1692 #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")]
1693 pub fn sub_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1695 /// Performs checked integer multiplication
1697 /// Note that, unlike most intrinsics, this is safe to call;
1698 /// it does not require an `unsafe` block.
1699 /// Therefore, implementations must not require the user to uphold
1700 /// any safety invariants.
1702 /// The stabilized versions of this intrinsic are available on the integer
1703 /// primitives via the `overflowing_mul` method. For example,
1704 /// [`u32::overflowing_mul`]
1705 #[rustc_const_stable(feature = "const_int_overflow", since = "1.40.0")]
1706 pub fn mul_with_overflow<T: Copy>(x: T, y: T) -> (T, bool);
1708 /// Performs an exact division, resulting in undefined behavior where
1709 /// `x % y != 0` or `y == 0` or `x == T::MIN && y == -1`
1711 /// This intrinsic does not have a stable counterpart.
1712 pub fn exact_div<T: Copy>(x: T, y: T) -> T;
1714 /// Performs an unchecked division, resulting in undefined behavior
1715 /// where `y == 0` or `x == T::MIN && y == -1`
1717 /// Safe wrappers for this intrinsic are available on the integer
1718 /// primitives via the `checked_div` method. For example,
1719 /// [`u32::checked_div`]
1720 #[rustc_const_stable(feature = "const_int_unchecked_arith", since = "1.52.0")]
1721 pub fn unchecked_div<T: Copy>(x: T, y: T) -> T;
1722 /// Returns the remainder of an unchecked division, resulting in
1723 /// undefined behavior when `y == 0` or `x == T::MIN && y == -1`
1725 /// Safe wrappers for this intrinsic are available on the integer
1726 /// primitives via the `checked_rem` method. For example,
1727 /// [`u32::checked_rem`]
1728 #[rustc_const_stable(feature = "const_int_unchecked_arith", since = "1.52.0")]
1729 pub fn unchecked_rem<T: Copy>(x: T, y: T) -> T;
1731 /// Performs an unchecked left shift, resulting in undefined behavior when
1732 /// `y < 0` or `y >= N`, where N is the width of T in bits.
1734 /// Safe wrappers for this intrinsic are available on the integer
1735 /// primitives via the `checked_shl` method. For example,
1736 /// [`u32::checked_shl`]
1737 #[rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0")]
1738 pub fn unchecked_shl<T: Copy>(x: T, y: T) -> T;
1739 /// Performs an unchecked right shift, resulting in undefined behavior when
1740 /// `y < 0` or `y >= N`, where N is the width of T in bits.
1742 /// Safe wrappers for this intrinsic are available on the integer
1743 /// primitives via the `checked_shr` method. For example,
1744 /// [`u32::checked_shr`]
1745 #[rustc_const_stable(feature = "const_int_unchecked", since = "1.40.0")]
1746 pub fn unchecked_shr<T: Copy>(x: T, y: T) -> T;
1748 /// Returns the result of an unchecked addition, resulting in
1749 /// undefined behavior when `x + y > T::MAX` or `x + y < T::MIN`.
1751 /// This intrinsic does not have a stable counterpart.
1752 #[rustc_const_unstable(feature = "const_int_unchecked_arith", issue = "none")]
1753 pub fn unchecked_add<T: Copy>(x: T, y: T) -> T;
1755 /// Returns the result of an unchecked subtraction, resulting in
1756 /// undefined behavior when `x - y > T::MAX` or `x - y < T::MIN`.
1758 /// This intrinsic does not have a stable counterpart.
1759 #[rustc_const_unstable(feature = "const_int_unchecked_arith", issue = "none")]
1760 pub fn unchecked_sub<T: Copy>(x: T, y: T) -> T;
1762 /// Returns the result of an unchecked multiplication, resulting in
1763 /// undefined behavior when `x * y > T::MAX` or `x * y < T::MIN`.
1765 /// This intrinsic does not have a stable counterpart.
1766 #[rustc_const_unstable(feature = "const_int_unchecked_arith", issue = "none")]
1767 pub fn unchecked_mul<T: Copy>(x: T, y: T) -> T;
1769 /// Performs rotate left.
1771 /// Note that, unlike most intrinsics, this is safe to call;
1772 /// it does not require an `unsafe` block.
1773 /// Therefore, implementations must not require the user to uphold
1774 /// any safety invariants.
1776 /// The stabilized versions of this intrinsic are available on the integer
1777 /// primitives via the `rotate_left` method. For example,
1778 /// [`u32::rotate_left`]
1779 #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")]
1780 pub fn rotate_left<T: Copy>(x: T, y: T) -> T;
1782 /// Performs rotate right.
1784 /// Note that, unlike most intrinsics, this is safe to call;
1785 /// it does not require an `unsafe` block.
1786 /// Therefore, implementations must not require the user to uphold
1787 /// any safety invariants.
1789 /// The stabilized versions of this intrinsic are available on the integer
1790 /// primitives via the `rotate_right` method. For example,
1791 /// [`u32::rotate_right`]
1792 #[rustc_const_stable(feature = "const_int_rotate", since = "1.40.0")]
1793 pub fn rotate_right<T: Copy>(x: T, y: T) -> T;
1795 /// Returns (a + b) mod 2<sup>N</sup>, where N is the width of T in bits.
1797 /// Note that, unlike most intrinsics, this is safe to call;
1798 /// it does not require an `unsafe` block.
1799 /// Therefore, implementations must not require the user to uphold
1800 /// any safety invariants.
1802 /// The stabilized versions of this intrinsic are available on the integer
1803 /// primitives via the `wrapping_add` method. For example,
1804 /// [`u32::wrapping_add`]
1805 #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")]
1806 pub fn wrapping_add<T: Copy>(a: T, b: T) -> T;
1807 /// Returns (a - b) mod 2<sup>N</sup>, where N is the width of T in bits.
1809 /// Note that, unlike most intrinsics, this is safe to call;
1810 /// it does not require an `unsafe` block.
1811 /// Therefore, implementations must not require the user to uphold
1812 /// any safety invariants.
1814 /// The stabilized versions of this intrinsic are available on the integer
1815 /// primitives via the `wrapping_sub` method. For example,
1816 /// [`u32::wrapping_sub`]
1817 #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")]
1818 pub fn wrapping_sub<T: Copy>(a: T, b: T) -> T;
1819 /// Returns (a * b) mod 2<sup>N</sup>, where N is the width of T in bits.
1821 /// Note that, unlike most intrinsics, this is safe to call;
1822 /// it does not require an `unsafe` block.
1823 /// Therefore, implementations must not require the user to uphold
1824 /// any safety invariants.
1826 /// The stabilized versions of this intrinsic are available on the integer
1827 /// primitives via the `wrapping_mul` method. For example,
1828 /// [`u32::wrapping_mul`]
1829 #[rustc_const_stable(feature = "const_int_wrapping", since = "1.40.0")]
1830 pub fn wrapping_mul<T: Copy>(a: T, b: T) -> T;
1832 /// Computes `a + b`, saturating at numeric bounds.
1834 /// Note that, unlike most intrinsics, this is safe to call;
1835 /// it does not require an `unsafe` block.
1836 /// Therefore, implementations must not require the user to uphold
1837 /// any safety invariants.
1839 /// The stabilized versions of this intrinsic are available on the integer
1840 /// primitives via the `saturating_add` method. For example,
1841 /// [`u32::saturating_add`]
1842 #[rustc_const_stable(feature = "const_int_saturating", since = "1.40.0")]
1843 pub fn saturating_add<T: Copy>(a: T, b: T) -> T;
1844 /// Computes `a - b`, saturating at numeric bounds.
1846 /// Note that, unlike most intrinsics, this is safe to call;
1847 /// it does not require an `unsafe` block.
1848 /// Therefore, implementations must not require the user to uphold
1849 /// any safety invariants.
1851 /// The stabilized versions of this intrinsic are available on the integer
1852 /// primitives via the `saturating_sub` method. For example,
1853 /// [`u32::saturating_sub`]
1854 #[rustc_const_stable(feature = "const_int_saturating", since = "1.40.0")]
1855 pub fn saturating_sub<T: Copy>(a: T, b: T) -> T;
1857 /// Returns the value of the discriminant for the variant in 'v';
1858 /// if `T` has no discriminant, returns `0`.
1860 /// Note that, unlike most intrinsics, this is safe to call;
1861 /// it does not require an `unsafe` block.
1862 /// Therefore, implementations must not require the user to uphold
1863 /// any safety invariants.
1865 /// The stabilized version of this intrinsic is [`core::mem::discriminant`].
1866 #[rustc_const_unstable(feature = "const_discriminant", issue = "69821")]
1867 pub fn discriminant_value<T>(v: &T) -> <T as DiscriminantKind>::Discriminant;
1869 /// Returns the number of variants of the type `T` cast to a `usize`;
1870 /// if `T` has no variants, returns `0`. Uninhabited variants will be counted.
1872 /// Note that, unlike most intrinsics, this is safe to call;
1873 /// it does not require an `unsafe` block.
1874 /// Therefore, implementations must not require the user to uphold
1875 /// any safety invariants.
1877 /// The to-be-stabilized version of this intrinsic is [`mem::variant_count`].
1878 #[rustc_const_unstable(feature = "variant_count", issue = "73662")]
1879 pub fn variant_count<T>() -> usize;
1881 /// Rust's "try catch" construct which invokes the function pointer `try_fn`
1882 /// with the data pointer `data`.
1884 /// The third argument is a function called if a panic occurs. This function
1885 /// takes the data pointer and a pointer to the target-specific exception
1886 /// object that was caught. For more information see the compiler's
1887 /// source as well as std's catch implementation.
1888 pub fn r#try(try_fn: fn(*mut u8), data: *mut u8, catch_fn: fn(*mut u8, *mut u8)) -> i32;
1890 /// Emits a `!nontemporal` store according to LLVM (see their docs).
1891 /// Probably will never become stable.
1892 pub fn nontemporal_store<T>(ptr: *mut T, val: T);
1894 /// See documentation of `<*const T>::offset_from` for details.
1895 #[rustc_const_unstable(feature = "const_ptr_offset_from", issue = "41079")]
1896 pub fn ptr_offset_from<T>(ptr: *const T, base: *const T) -> isize;
1898 /// See documentation of `<*const T>::guaranteed_eq` for details.
1900 /// Note that, unlike most intrinsics, this is safe to call;
1901 /// it does not require an `unsafe` block.
1902 /// Therefore, implementations must not require the user to uphold
1903 /// any safety invariants.
1904 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
1905 pub fn ptr_guaranteed_eq<T>(ptr: *const T, other: *const T) -> bool;
1907 /// See documentation of `<*const T>::guaranteed_ne` for details.
1909 /// Note that, unlike most intrinsics, this is safe to call;
1910 /// it does not require an `unsafe` block.
1911 /// Therefore, implementations must not require the user to uphold
1912 /// any safety invariants.
1913 #[rustc_const_unstable(feature = "const_raw_ptr_comparison", issue = "53020")]
1914 pub fn ptr_guaranteed_ne<T>(ptr: *const T, other: *const T) -> bool;
1916 /// Allocate at compile time. Should not be called at runtime.
1917 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1918 pub fn const_allocate(size: usize, align: usize) -> *mut u8;
1920 /// Determines whether the raw bytes of the two values are equal.
1922 /// The is particularly handy for arrays, since it allows things like just
1923 /// comparing `i96`s instead of forcing `alloca`s for `[6 x i16]`.
1925 /// Above some backend-decided threshold this will emit calls to `memcmp`,
1926 /// like slice equality does, instead of causing massive code size.
1930 /// It's UB to call this if any of the *bytes* in `*a` or `*b` are uninitialized.
1931 /// Note that this is a stricter criterion than just the *values* being
1932 /// fully-initialized: if `T` has padding, it's UB to call this intrinsic.
1934 /// (The implementation is allowed to branch on the results of comparisons,
1935 /// which is UB if any of their inputs are `undef`.)
1936 #[rustc_const_unstable(feature = "const_intrinsic_raw_eq", issue = "none")]
1937 pub fn raw_eq<T>(a: &T, b: &T) -> bool;
1939 /// See documentation of [`std::hint::black_box`] for details.
1941 /// [`std::hint::black_box`]: crate::hint::black_box
1942 pub fn black_box<T>(dummy: T) -> T;
1945 // Some functions are defined here because they accidentally got made
1946 // available in this module on stable. See <https://github.com/rust-lang/rust/issues/15702>.
1947 // (`transmute` also falls into this category, but it cannot be wrapped due to the
1948 // check that `T` and `U` have the same size.)
1950 /// Checks whether `ptr` is properly aligned with respect to
1951 /// `align_of::<T>()`.
1952 pub(crate) fn is_aligned_and_not_null<T>(ptr: *const T) -> bool {
1953 !ptr.is_null() && ptr as usize % mem::align_of::<T>() == 0
1956 /// Checks whether the regions of memory starting at `src` and `dst` of size
1957 /// `count * size_of::<T>()` do *not* overlap.
1958 #[cfg(debug_assertions)]
1959 pub(crate) fn is_nonoverlapping<T>(src: *const T, dst: *const T, count: usize) -> bool {
1960 let src_usize = src as usize;
1961 let dst_usize = dst as usize;
1962 let size = mem::size_of::<T>().checked_mul(count).unwrap();
1963 let diff = if src_usize > dst_usize { src_usize - dst_usize } else { dst_usize - src_usize };
1964 // If the absolute distance between the ptrs is at least as big as the size of the buffer,
1965 // they do not overlap.
1969 /// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
1970 /// and destination must *not* overlap.
1972 /// For regions of memory which might overlap, use [`copy`] instead.
1974 /// `copy_nonoverlapping` is semantically equivalent to C's [`memcpy`], but
1975 /// with the argument order swapped.
1977 /// [`memcpy`]: https://en.cppreference.com/w/c/string/byte/memcpy
1981 /// Behavior is undefined if any of the following conditions are violated:
1983 /// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes.
1985 /// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes.
1987 /// * Both `src` and `dst` must be properly aligned.
1989 /// * The region of memory beginning at `src` with a size of `count *
1990 /// size_of::<T>()` bytes must *not* overlap with the region of memory
1991 /// beginning at `dst` with the same size.
1993 /// Like [`read`], `copy_nonoverlapping` creates a bitwise copy of `T`, regardless of
1994 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using *both* the values
1995 /// in the region beginning at `*src` and the region beginning at `*dst` can
1996 /// [violate memory safety][read-ownership].
1998 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is
1999 /// `0`, the pointers must be non-null and properly aligned.
2001 /// [`read`]: crate::ptr::read
2002 /// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
2003 /// [valid]: crate::ptr#safety
2007 /// Manually implement [`Vec::append`]:
2012 /// /// Moves all the elements of `src` into `dst`, leaving `src` empty.
2013 /// fn append<T>(dst: &mut Vec<T>, src: &mut Vec<T>) {
2014 /// let src_len = src.len();
2015 /// let dst_len = dst.len();
2017 /// // Ensure that `dst` has enough capacity to hold all of `src`.
2018 /// dst.reserve(src_len);
2021 /// // The call to offset is always safe because `Vec` will never
2022 /// // allocate more than `isize::MAX` bytes.
2023 /// let dst_ptr = dst.as_mut_ptr().offset(dst_len as isize);
2024 /// let src_ptr = src.as_ptr();
2026 /// // Truncate `src` without dropping its contents. We do this first,
2027 /// // to avoid problems in case something further down panics.
2030 /// // The two regions cannot overlap because mutable references do
2031 /// // not alias, and two different vectors cannot own the same
2033 /// ptr::copy_nonoverlapping(src_ptr, dst_ptr, src_len);
2035 /// // Notify `dst` that it now holds the contents of `src`.
2036 /// dst.set_len(dst_len + src_len);
2040 /// let mut a = vec!['r'];
2041 /// let mut b = vec!['u', 's', 't'];
2043 /// append(&mut a, &mut b);
2045 /// assert_eq!(a, &['r', 'u', 's', 't']);
2046 /// assert!(b.is_empty());
2049 /// [`Vec::append`]: ../../std/vec/struct.Vec.html#method.append
2050 #[doc(alias = "memcpy")]
2051 #[stable(feature = "rust1", since = "1.0.0")]
2052 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
2054 pub const unsafe fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize) {
2055 extern "rust-intrinsic" {
2056 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
2057 pub fn copy_nonoverlapping<T>(src: *const T, dst: *mut T, count: usize);
2060 #[cfg(debug_assertions)]
2061 fn runtime_check<T>(src: *const T, dst: *mut T, count: usize) {
2062 if !is_aligned_and_not_null(src)
2063 || !is_aligned_and_not_null(dst)
2064 || !is_nonoverlapping(src, dst, count)
2066 // Not panicking to keep codegen impact smaller.
2070 #[cfg(debug_assertions)]
2071 const fn compiletime_check<T>(_src: *const T, _dst: *mut T, _count: usize) {}
2072 #[cfg(debug_assertions)]
2073 // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to
2074 // not do them during compile time
2076 const_eval_select((src, dst, count), compiletime_check, runtime_check);
2079 // SAFETY: the safety contract for `copy_nonoverlapping` must be
2080 // upheld by the caller.
2081 unsafe { copy_nonoverlapping(src, dst, count) }
2084 /// Copies `count * size_of::<T>()` bytes from `src` to `dst`. The source
2085 /// and destination may overlap.
2087 /// If the source and destination will *never* overlap,
2088 /// [`copy_nonoverlapping`] can be used instead.
2090 /// `copy` is semantically equivalent to C's [`memmove`], but with the argument
2091 /// order swapped. Copying takes place as if the bytes were copied from `src`
2092 /// to a temporary array and then copied from the array to `dst`.
2094 /// [`memmove`]: https://en.cppreference.com/w/c/string/byte/memmove
2098 /// Behavior is undefined if any of the following conditions are violated:
2100 /// * `src` must be [valid] for reads of `count * size_of::<T>()` bytes.
2102 /// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes.
2104 /// * Both `src` and `dst` must be properly aligned.
2106 /// Like [`read`], `copy` creates a bitwise copy of `T`, regardless of
2107 /// whether `T` is [`Copy`]. If `T` is not [`Copy`], using both the values
2108 /// in the region beginning at `*src` and the region beginning at `*dst` can
2109 /// [violate memory safety][read-ownership].
2111 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is
2112 /// `0`, the pointers must be non-null and properly aligned.
2114 /// [`read`]: crate::ptr::read
2115 /// [read-ownership]: crate::ptr::read#ownership-of-the-returned-value
2116 /// [valid]: crate::ptr#safety
2120 /// Efficiently create a Rust vector from an unsafe buffer:
2127 /// /// * `ptr` must be correctly aligned for its type and non-zero.
2128 /// /// * `ptr` must be valid for reads of `elts` contiguous elements of type `T`.
2129 /// /// * Those elements must not be used after calling this function unless `T: Copy`.
2130 /// # #[allow(dead_code)]
2131 /// unsafe fn from_buf_raw<T>(ptr: *const T, elts: usize) -> Vec<T> {
2132 /// let mut dst = Vec::with_capacity(elts);
2134 /// // SAFETY: Our precondition ensures the source is aligned and valid,
2135 /// // and `Vec::with_capacity` ensures that we have usable space to write them.
2136 /// ptr::copy(ptr, dst.as_mut_ptr(), elts);
2138 /// // SAFETY: We created it with this much capacity earlier,
2139 /// // and the previous `copy` has initialized these elements.
2140 /// dst.set_len(elts);
2144 #[doc(alias = "memmove")]
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
2148 pub const unsafe fn copy<T>(src: *const T, dst: *mut T, count: usize) {
2149 extern "rust-intrinsic" {
2150 #[rustc_const_unstable(feature = "const_intrinsic_copy", issue = "80697")]
2151 fn copy<T>(src: *const T, dst: *mut T, count: usize);
2154 #[cfg(debug_assertions)]
2155 fn runtime_check<T>(src: *const T, dst: *mut T) {
2156 if !is_aligned_and_not_null(src) || !is_aligned_and_not_null(dst) {
2157 // Not panicking to keep codegen impact smaller.
2161 #[cfg(debug_assertions)]
2162 const fn compiletime_check<T>(_src: *const T, _dst: *mut T) {}
2163 #[cfg(debug_assertions)]
2164 // SAFETY: runtime debug-assertions are a best-effort basis; it's fine to
2165 // not do them during compile time
2167 const_eval_select((src, dst), compiletime_check, runtime_check);
2170 // SAFETY: the safety contract for `copy` must be upheld by the caller.
2171 unsafe { copy(src, dst, count) }
2174 /// Sets `count * size_of::<T>()` bytes of memory starting at `dst` to
2177 /// `write_bytes` is similar to C's [`memset`], but sets `count *
2178 /// size_of::<T>()` bytes to `val`.
2180 /// [`memset`]: https://en.cppreference.com/w/c/string/byte/memset
2184 /// Behavior is undefined if any of the following conditions are violated:
2186 /// * `dst` must be [valid] for writes of `count * size_of::<T>()` bytes.
2188 /// * `dst` must be properly aligned.
2190 /// Additionally, the caller must ensure that writing `count *
2191 /// size_of::<T>()` bytes to the given region of memory results in a valid
2192 /// value of `T`. Using a region of memory typed as a `T` that contains an
2193 /// invalid value of `T` is undefined behavior.
2195 /// Note that even if the effectively copied size (`count * size_of::<T>()`) is
2196 /// `0`, the pointer must be non-null and properly aligned.
2198 /// [valid]: crate::ptr#safety
2207 /// let mut vec = vec![0u32; 4];
2209 /// let vec_ptr = vec.as_mut_ptr();
2210 /// ptr::write_bytes(vec_ptr, 0xfe, 2);
2212 /// assert_eq!(vec, [0xfefefefe, 0xfefefefe, 0, 0]);
2215 /// Creating an invalid value:
2220 /// let mut v = Box::new(0i32);
2223 /// // Leaks the previously held value by overwriting the `Box<T>` with
2224 /// // a null pointer.
2225 /// ptr::write_bytes(&mut v as *mut Box<i32>, 0, 1);
2228 /// // At this point, using or dropping `v` results in undefined behavior.
2229 /// // drop(v); // ERROR
2231 /// // Even leaking `v` "uses" it, and hence is undefined behavior.
2232 /// // mem::forget(v); // ERROR
2234 /// // In fact, `v` is invalid according to basic type layout invariants, so *any*
2235 /// // operation touching it is undefined behavior.
2236 /// // let v2 = v; // ERROR
2239 /// // Let us instead put in a valid value
2240 /// ptr::write(&mut v as *mut Box<i32>, Box::new(42i32));
2243 /// // Now the box is fine
2244 /// assert_eq!(*v, 42);
2246 #[stable(feature = "rust1", since = "1.0.0")]
2248 pub unsafe fn write_bytes<T>(dst: *mut T, val: u8, count: usize) {
2249 extern "rust-intrinsic" {
2250 fn write_bytes<T>(dst: *mut T, val: u8, count: usize);
2253 debug_assert!(is_aligned_and_not_null(dst), "attempt to write to unaligned or null pointer");
2255 // SAFETY: the safety contract for `write_bytes` must be upheld by the caller.
2256 unsafe { write_bytes(dst, val, count) }
2259 /// Selects which function to call depending on the context.
2261 /// If this function is evaluated at compile-time, then a call to this
2262 /// intrinsic will be replaced with a call to `called_in_const`. It gets
2263 /// replaced with a call to `called_at_rt` otherwise.
2265 /// # Type Requirements
2267 /// The two functions must be both function items. They cannot be function
2268 /// pointers or closures.
2270 /// `arg` will be the arguments that will be passed to either one of the
2271 /// two functions, therefore, both functions must accept the same type of
2272 /// arguments. Both functions must return RET.
2276 /// This intrinsic allows breaking [referential transparency] in `const fn`
2277 /// and is therefore `unsafe`.
2279 /// Code that uses this intrinsic must be extremely careful to ensure that
2280 /// `const fn`s remain referentially-transparent independently of when they
2283 /// The Rust compiler assumes that it is sound to replace a call to a `const
2284 /// fn` with the result produced by evaluating it at compile-time. If
2285 /// evaluating the function at run-time were to produce a different result,
2286 /// or have any other observable side-effects, the behavior is undefined.
2288 /// [referential transparency]: https://en.wikipedia.org/wiki/Referential_transparency
2290 feature = "const_eval_select",
2292 reason = "const_eval_select will never be stable"
2294 #[rustc_const_unstable(feature = "const_eval_select", issue = "none")]
2295 #[lang = "const_eval_select"]
2296 #[rustc_do_not_const_check]
2297 pub const unsafe fn const_eval_select<ARG, F, G, RET>(
2299 _called_in_const: F,
2303 F: ~const FnOnce<ARG, Output = RET>,
2304 G: FnOnce<ARG, Output = RET> + ~const Drop,
2306 called_at_rt.call_once(arg)
2310 feature = "const_eval_select",
2312 reason = "const_eval_select will never be stable"
2314 #[rustc_const_unstable(feature = "const_eval_select", issue = "none")]
2315 #[lang = "const_eval_select_ct"]
2316 pub const unsafe fn const_eval_select_ct<ARG, F, G, RET>(
2322 F: ~const FnOnce<ARG, Output = RET>,
2323 G: FnOnce<ARG, Output = RET> + ~const Drop,
2325 called_in_const.call_once(arg)