core/
primitive_docs.rs

1#[rustc_doc_primitive = "bool"]
2#[doc(alias = "true")]
3#[doc(alias = "false")]
4/// The boolean type.
5///
6/// The `bool` represents a value, which could only be either [`true`] or [`false`]. If you cast
7/// a `bool` into an integer, [`true`] will be 1 and [`false`] will be 0.
8///
9/// # Basic usage
10///
11/// `bool` implements various traits, such as [`BitAnd`], [`BitOr`], [`Not`], etc.,
12/// which allow us to perform boolean operations using `&`, `|` and `!`.
13///
14/// [`if`] requires a `bool` value as its conditional. [`assert!`], which is an
15/// important macro in testing, checks whether an expression is [`true`] and panics
16/// if it isn't.
17///
18/// ```
19/// let bool_val = true & false | false;
20/// assert!(!bool_val);
21/// ```
22///
23/// [`true`]: ../std/keyword.true.html
24/// [`false`]: ../std/keyword.false.html
25/// [`BitAnd`]: ops::BitAnd
26/// [`BitOr`]: ops::BitOr
27/// [`Not`]: ops::Not
28/// [`if`]: ../std/keyword.if.html
29///
30/// # Examples
31///
32/// A trivial example of the usage of `bool`:
33///
34/// ```
35/// let praise_the_borrow_checker = true;
36///
37/// // using the `if` conditional
38/// if praise_the_borrow_checker {
39///     println!("oh, yeah!");
40/// } else {
41///     println!("what?!!");
42/// }
43///
44/// // ... or, a match pattern
45/// match praise_the_borrow_checker {
46///     true => println!("keep praising!"),
47///     false => println!("you should praise!"),
48/// }
49/// ```
50///
51/// Also, since `bool` implements the [`Copy`] trait, we don't
52/// have to worry about the move semantics (just like the integer and float primitives).
53///
54/// Now an example of `bool` cast to integer type:
55///
56/// ```
57/// assert_eq!(true as i32, 1);
58/// assert_eq!(false as i32, 0);
59/// ```
60#[stable(feature = "rust1", since = "1.0.0")]
61mod prim_bool {}
62
63#[rustc_doc_primitive = "never"]
64#[doc(alias = "!")]
65//
66/// The `!` type, also called "never".
67///
68/// `!` represents the type of computations which never resolve to any value at all. For example,
69/// the [`exit`] function `fn exit(code: i32) -> !` exits the process without ever returning, and
70/// so returns `!`.
71///
72/// `break`, `continue` and `return` expressions also have type `!`. For example we are allowed to
73/// write:
74///
75/// ```
76/// #![feature(never_type)]
77/// # fn foo() -> u32 {
78/// let x: ! = {
79///     return 123
80/// };
81/// # }
82/// ```
83///
84/// Although the `let` is pointless here, it illustrates the meaning of `!`. Since `x` is never
85/// assigned a value (because `return` returns from the entire function), `x` can be given type
86/// `!`. We could also replace `return 123` with a `panic!` or a never-ending `loop` and this code
87/// would still be valid.
88///
89/// A more realistic usage of `!` is in this code:
90///
91/// ```
92/// # fn get_a_number() -> Option<u32> { None }
93/// # loop {
94/// let num: u32 = match get_a_number() {
95///     Some(num) => num,
96///     None => break,
97/// };
98/// # }
99/// ```
100///
101/// Both match arms must produce values of type [`u32`], but since `break` never produces a value
102/// at all we know it can never produce a value which isn't a [`u32`]. This illustrates another
103/// behavior of the `!` type - expressions with type `!` will coerce into any other type.
104///
105/// [`u32`]: prim@u32
106/// [`exit`]: ../std/process/fn.exit.html
107///
108/// # `!` and generics
109///
110/// ## Infallible errors
111///
112/// The main place you'll see `!` used explicitly is in generic code. Consider the [`FromStr`]
113/// trait:
114///
115/// ```
116/// trait FromStr: Sized {
117///     type Err;
118///     fn from_str(s: &str) -> Result<Self, Self::Err>;
119/// }
120/// ```
121///
122/// When implementing this trait for [`String`] we need to pick a type for [`Err`]. And since
123/// converting a string into a string will never result in an error, the appropriate type is `!`.
124/// (Currently the type actually used is an enum with no variants, though this is only because `!`
125/// was added to Rust at a later date and it may change in the future.) With an [`Err`] type of
126/// `!`, if we have to call [`String::from_str`] for some reason the result will be a
127/// [`Result<String, !>`] which we can unpack like this:
128///
129/// ```
130/// use std::str::FromStr;
131/// let Ok(s) = String::from_str("hello");
132/// ```
133///
134/// Since the [`Err`] variant contains a `!`, it can never occur. This means we can exhaustively
135/// match on [`Result<T, !>`] by just taking the [`Ok`] variant. This illustrates another behavior
136/// of `!` - it can be used to "delete" certain enum variants from generic types like `Result`.
137///
138/// ## Infinite loops
139///
140/// While [`Result<T, !>`] is very useful for removing errors, `!` can also be used to remove
141/// successes as well. If we think of [`Result<T, !>`] as "if this function returns, it has not
142/// errored," we get a very intuitive idea of [`Result<!, E>`] as well: if the function returns, it
143/// *has* errored.
144///
145/// For example, consider the case of a simple web server, which can be simplified to:
146///
147/// ```ignore (hypothetical-example)
148/// loop {
149///     let (client, request) = get_request().expect("disconnected");
150///     let response = request.process();
151///     response.send(client);
152/// }
153/// ```
154///
155/// Currently, this isn't ideal, because we simply panic whenever we fail to get a new connection.
156/// Instead, we'd like to keep track of this error, like this:
157///
158/// ```ignore (hypothetical-example)
159/// loop {
160///     match get_request() {
161///         Err(err) => break err,
162///         Ok((client, request)) => {
163///             let response = request.process();
164///             response.send(client);
165///         },
166///     }
167/// }
168/// ```
169///
170/// Now, when the server disconnects, we exit the loop with an error instead of panicking. While it
171/// might be intuitive to simply return the error, we might want to wrap it in a [`Result<!, E>`]
172/// instead:
173///
174/// ```ignore (hypothetical-example)
175/// fn server_loop() -> Result<!, ConnectionError> {
176///     loop {
177///         let (client, request) = get_request()?;
178///         let response = request.process();
179///         response.send(client);
180///     }
181/// }
182/// ```
183///
184/// Now, we can use `?` instead of `match`, and the return type makes a lot more sense: if the loop
185/// ever stops, it means that an error occurred. We don't even have to wrap the loop in an `Ok`
186/// because `!` coerces to `Result<!, ConnectionError>` automatically.
187///
188/// [`String::from_str`]: str::FromStr::from_str
189/// [`String`]: ../std/string/struct.String.html
190/// [`FromStr`]: str::FromStr
191///
192/// # `!` and traits
193///
194/// When writing your own traits, `!` should have an `impl` whenever there is an obvious `impl`
195/// which doesn't `panic!`. The reason is that functions returning an `impl Trait` where `!`
196/// does not have an `impl` of `Trait` cannot diverge as their only possible code path. In other
197/// words, they can't return `!` from every code path. As an example, this code doesn't compile:
198///
199/// ```compile_fail
200/// use std::ops::Add;
201///
202/// fn foo() -> impl Add<u32> {
203///     unimplemented!()
204/// }
205/// ```
206///
207/// But this code does:
208///
209/// ```
210/// use std::ops::Add;
211///
212/// fn foo() -> impl Add<u32> {
213///     if true {
214///         unimplemented!()
215///     } else {
216///         0
217///     }
218/// }
219/// ```
220///
221/// The reason is that, in the first example, there are many possible types that `!` could coerce
222/// to, because many types implement `Add<u32>`. However, in the second example,
223/// the `else` branch returns a `0`, which the compiler infers from the return type to be of type
224/// `u32`. Since `u32` is a concrete type, `!` can and will be coerced to it. See issue [#36375]
225/// for more information on this quirk of `!`.
226///
227/// [#36375]: https://github.com/rust-lang/rust/issues/36375
228///
229/// As it turns out, though, most traits can have an `impl` for `!`. Take [`Debug`]
230/// for example:
231///
232/// ```
233/// #![feature(never_type)]
234/// # use std::fmt;
235/// # trait Debug {
236/// #     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result;
237/// # }
238/// impl Debug for ! {
239///     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
240///         *self
241///     }
242/// }
243/// ```
244///
245/// Once again we're using `!`'s ability to coerce into any other type, in this case
246/// [`fmt::Result`]. Since this method takes a `&!` as an argument we know that it can never be
247/// called (because there is no value of type `!` for it to be called with). Writing `*self`
248/// essentially tells the compiler "We know that this code can never be run, so just treat the
249/// entire function body as having type [`fmt::Result`]". This pattern can be used a lot when
250/// implementing traits for `!`. Generally, any trait which only has methods which take a `self`
251/// parameter should have such an impl.
252///
253/// On the other hand, one trait which would not be appropriate to implement is [`Default`]:
254///
255/// ```
256/// trait Default {
257///     fn default() -> Self;
258/// }
259/// ```
260///
261/// Since `!` has no values, it has no default value either. It's true that we could write an
262/// `impl` for this which simply panics, but the same is true for any type (we could `impl
263/// Default` for (eg.) [`File`] by just making [`default()`] panic.)
264///
265/// [`File`]: ../std/fs/struct.File.html
266/// [`Debug`]: fmt::Debug
267/// [`default()`]: Default::default
268///
269/// # Never type fallback
270///
271/// When the compiler sees a value of type `!` in a [coercion site], it implicitly inserts a
272/// coercion to allow the type checker to infer any type:
273///
274/// ```rust,ignore (illustrative-and-has-placeholders)
275/// // this
276/// let x: u8 = panic!();
277///
278/// // is (essentially) turned by the compiler into
279/// let x: u8 = absurd(panic!());
280///
281/// // where absurd is a function with the following signature
282/// // (it's sound, because `!` always marks unreachable code):
283/// fn absurd<T>(_: !) -> T { ... }
284// FIXME: use `core::convert::absurd` here instead, once it's merged
285/// ```
286///
287/// This can lead to compilation errors if the type cannot be inferred:
288///
289/// ```compile_fail
290/// // this
291/// { panic!() };
292///
293/// // gets turned into this
294/// { absurd(panic!()) }; // error: can't infer the type of `absurd`
295/// ```
296///
297/// To prevent such errors, the compiler remembers where it inserted `absurd` calls, and
298/// if it can't infer the type, it uses the fallback type instead:
299/// ```rust, ignore
300/// type Fallback = /* An arbitrarily selected type! */;
301/// { absurd::<Fallback>(panic!()) }
302/// ```
303///
304/// This is what is known as "never type fallback".
305///
306/// Historically, the fallback type was [`()`], causing confusing behavior where `!` spontaneously
307/// coerced to `()`, even when it would not infer `()` without the fallback. The fallback was changed
308/// to `!` in the [2024 edition], and will be changed in all editions at a later date.
309///
310/// [coercion site]: <https://doc.rust-lang.org/reference/type-coercions.html#coercion-sites>
311/// [`()`]: prim@unit
312/// [2024 edition]: <https://doc.rust-lang.org/edition-guide/rust-2024/never-type-fallback.html>
313///
314#[unstable(feature = "never_type", issue = "35121")]
315#[cfg(not(feature = "ferrocene_certified"))]
316mod prim_never {}
317
318// Required to make auto trait impls render.
319// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
320#[doc(hidden)]
321impl ! {}
322
323#[rustc_doc_primitive = "char"]
324#[allow(rustdoc::invalid_rust_codeblocks)]
325/// A character type.
326///
327/// The `char` type represents a single character. More specifically, since
328/// 'character' isn't a well-defined concept in Unicode, `char` is a '[Unicode
329/// scalar value]'.
330///
331/// This documentation describes a number of methods and trait implementations on the
332/// `char` type. For technical reasons, there is additional, separate
333/// documentation in [the `std::char` module](char/index.html) as well.
334///
335/// # Validity and Layout
336///
337/// A `char` is a '[Unicode scalar value]', which is any '[Unicode code point]'
338/// other than a [surrogate code point]. This has a fixed numerical definition:
339/// code points are in the range 0 to 0x10FFFF, inclusive.
340/// Surrogate code points, used by UTF-16, are in the range 0xD800 to 0xDFFF.
341///
342/// No `char` may be constructed, whether as a literal or at runtime, that is not a
343/// Unicode scalar value. Violating this rule causes undefined behavior.
344///
345/// ```compile_fail
346/// // Each of these is a compiler error
347/// ['\u{D800}', '\u{DFFF}', '\u{110000}'];
348/// ```
349///
350/// ```should_panic
351/// // Panics; from_u32 returns None.
352/// char::from_u32(0xDE01).unwrap();
353/// ```
354///
355/// ```no_run
356/// // Undefined behavior
357/// let _ = unsafe { char::from_u32_unchecked(0x110000) };
358/// ```
359///
360/// Unicode scalar values are also the exact set of values that may be encoded in UTF-8. Because
361/// `char` values are Unicode scalar values and functions may assume [incoming `str` values are
362/// valid UTF-8](primitive.str.html#invariant), it is safe to store any `char` in a `str` or read
363/// any character from a `str` as a `char`.
364///
365/// The gap in valid `char` values is understood by the compiler, so in the
366/// below example the two ranges are understood to cover the whole range of
367/// possible `char` values and there is no error for a [non-exhaustive match].
368///
369/// ```
370/// let c: char = 'a';
371/// match c {
372///     '\0' ..= '\u{D7FF}' => false,
373///     '\u{E000}' ..= '\u{10FFFF}' => true,
374/// };
375/// ```
376///
377/// All Unicode scalar values are valid `char` values, but not all of them represent a real
378/// character. Many Unicode scalar values are not currently assigned to a character, but may be in
379/// the future ("reserved"); some will never be a character ("noncharacters"); and some may be given
380/// different meanings by different users ("private use").
381///
382/// `char` is guaranteed to have the same size, alignment, and function call ABI as `u32` on all
383/// platforms.
384/// ```
385/// use std::alloc::Layout;
386/// assert_eq!(Layout::new::<char>(), Layout::new::<u32>());
387/// ```
388///
389/// [Unicode code point]: https://www.unicode.org/glossary/#code_point
390/// [Unicode scalar value]: https://www.unicode.org/glossary/#unicode_scalar_value
391/// [non-exhaustive match]: ../book/ch06-02-match.html#matches-are-exhaustive
392/// [surrogate code point]: https://www.unicode.org/glossary/#surrogate_code_point
393///
394/// # Representation
395///
396/// `char` is always four bytes in size. This is a different representation than
397/// a given character would have as part of a [`String`]. For example:
398///
399/// ```
400/// let v = vec!['h', 'e', 'l', 'l', 'o'];
401///
402/// // five elements times four bytes for each element
403/// assert_eq!(20, v.len() * size_of::<char>());
404///
405/// let s = String::from("hello");
406///
407/// // five elements times one byte per element
408/// assert_eq!(5, s.len() * size_of::<u8>());
409/// ```
410///
411/// [`String`]: ../std/string/struct.String.html
412///
413/// As always, remember that a human intuition for 'character' might not map to
414/// Unicode's definitions. For example, despite looking similar, the 'é'
415/// character is one Unicode code point while 'é' is two Unicode code points:
416///
417/// ```
418/// let mut chars = "é".chars();
419/// // U+00e9: 'latin small letter e with acute'
420/// assert_eq!(Some('\u{00e9}'), chars.next());
421/// assert_eq!(None, chars.next());
422///
423/// let mut chars = "é".chars();
424/// // U+0065: 'latin small letter e'
425/// assert_eq!(Some('\u{0065}'), chars.next());
426/// // U+0301: 'combining acute accent'
427/// assert_eq!(Some('\u{0301}'), chars.next());
428/// assert_eq!(None, chars.next());
429/// ```
430///
431/// This means that the contents of the first string above _will_ fit into a
432/// `char` while the contents of the second string _will not_. Trying to create
433/// a `char` literal with the contents of the second string gives an error:
434///
435/// ```text
436/// error: character literal may only contain one codepoint: 'é'
437/// let c = 'é';
438///         ^^^
439/// ```
440///
441/// Another implication of the 4-byte fixed size of a `char` is that
442/// per-`char` processing can end up using a lot more memory:
443///
444/// ```
445/// let s = String::from("love: ❤️");
446/// let v: Vec<char> = s.chars().collect();
447///
448/// assert_eq!(12, size_of_val(&s[..]));
449/// assert_eq!(32, size_of_val(&v[..]));
450/// ```
451#[stable(feature = "rust1", since = "1.0.0")]
452#[cfg(not(feature = "ferrocene_certified"))]
453mod prim_char {}
454
455#[rustc_doc_primitive = "unit"]
456#[doc(alias = "(")]
457#[doc(alias = ")")]
458#[doc(alias = "()")]
459//
460/// The `()` type, also called "unit".
461///
462/// The `()` type has exactly one value `()`, and is used when there
463/// is no other meaningful value that could be returned. `()` is most
464/// commonly seen implicitly: functions without a `-> ...` implicitly
465/// have return type `()`, that is, these are equivalent:
466///
467/// ```rust
468/// fn long() -> () {}
469///
470/// fn short() {}
471/// ```
472///
473/// The semicolon `;` can be used to discard the result of an
474/// expression at the end of a block, making the expression (and thus
475/// the block) evaluate to `()`. For example,
476///
477/// ```rust
478/// fn returns_i64() -> i64 {
479///     1i64
480/// }
481/// fn returns_unit() {
482///     1i64;
483/// }
484///
485/// let is_i64 = {
486///     returns_i64()
487/// };
488/// let is_unit = {
489///     returns_i64();
490/// };
491/// ```
492///
493#[stable(feature = "rust1", since = "1.0.0")]
494#[cfg(not(feature = "ferrocene_certified"))]
495mod prim_unit {}
496
497// Required to make auto trait impls render.
498// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
499#[doc(hidden)]
500#[cfg(not(feature = "ferrocene_certified"))]
501impl () {}
502
503#[rustc_doc_primitive = "pointer"]
504#[doc(alias = "ptr")]
505#[doc(alias = "*")]
506#[doc(alias = "*const")]
507#[doc(alias = "*mut")]
508//
509/// Raw, unsafe pointers, `*const T`, and `*mut T`.
510///
511/// *[See also the `std::ptr` module](ptr).*
512///
513/// Working with raw pointers in Rust is uncommon, typically limited to a few patterns. Raw pointers
514/// can be out-of-bounds, unaligned, or [`null`]. However, when loading from or storing to a raw
515/// pointer, it must be [valid] for the given access and aligned. When using a field expression,
516/// tuple index expression, or array/slice index expression on a raw pointer, it follows the rules
517/// of [in-bounds pointer arithmetic][`offset`].
518///
519/// Storing through a raw pointer using `*ptr = data` calls `drop` on the old value, so
520/// [`write`] must be used if the type has drop glue and memory is not already
521/// initialized - otherwise `drop` would be called on the uninitialized memory.
522///
523/// Use the [`null`] and [`null_mut`] functions to create null pointers, and the
524/// [`is_null`] method of the `*const T` and `*mut T` types to check for null.
525/// The `*const T` and `*mut T` types also define the [`offset`] method, for
526/// pointer math.
527///
528/// # Common ways to create raw pointers
529///
530/// ## 1. Coerce a reference (`&T`) or mutable reference (`&mut T`).
531///
532/// ```
533/// let my_num: i32 = 10;
534/// let my_num_ptr: *const i32 = &my_num;
535/// let mut my_speed: i32 = 88;
536/// let my_speed_ptr: *mut i32 = &mut my_speed;
537/// ```
538///
539/// To get a pointer to a boxed value, dereference the box:
540///
541/// ```
542/// let my_num: Box<i32> = Box::new(10);
543/// let my_num_ptr: *const i32 = &*my_num;
544/// let mut my_speed: Box<i32> = Box::new(88);
545/// let my_speed_ptr: *mut i32 = &mut *my_speed;
546/// ```
547///
548/// This does not take ownership of the original allocation
549/// and requires no resource management later,
550/// but you must not use the pointer after its lifetime.
551///
552/// ## 2. Consume a box (`Box<T>`).
553///
554/// The [`into_raw`] function consumes a box and returns
555/// the raw pointer. It doesn't destroy `T` or deallocate any memory.
556///
557/// ```
558/// let my_speed: Box<i32> = Box::new(88);
559/// let my_speed: *mut i32 = Box::into_raw(my_speed);
560///
561/// // By taking ownership of the original `Box<T>` though
562/// // we are obligated to put it together later to be destroyed.
563/// unsafe {
564///     drop(Box::from_raw(my_speed));
565/// }
566/// ```
567///
568/// Note that here the call to [`drop`] is for clarity - it indicates
569/// that we are done with the given value and it should be destroyed.
570///
571/// ## 3. Create it using `&raw`
572///
573/// Instead of coercing a reference to a raw pointer, you can use the raw borrow
574/// operators `&raw const` (for `*const T`) and `&raw mut` (for `*mut T`).
575/// These operators allow you to create raw pointers to fields to which you cannot
576/// create a reference (without causing undefined behavior), such as an
577/// unaligned field. This might be necessary if packed structs or uninitialized
578/// memory is involved.
579///
580/// ```
581/// #[derive(Debug, Default, Copy, Clone)]
582/// #[repr(C, packed)]
583/// struct S {
584///     aligned: u8,
585///     unaligned: u32,
586/// }
587/// let s = S::default();
588/// let p = &raw const s.unaligned; // not allowed with coercion
589/// ```
590///
591/// ## 4. Get it from C.
592///
593/// ```
594/// # mod libc {
595/// # pub unsafe fn malloc(_size: usize) -> *mut core::ffi::c_void { core::ptr::NonNull::dangling().as_ptr() }
596/// # pub unsafe fn free(_ptr: *mut core::ffi::c_void) {}
597/// # }
598/// # #[cfg(any())]
599/// #[allow(unused_extern_crates)]
600/// extern crate libc;
601///
602/// unsafe {
603///     let my_num: *mut i32 = libc::malloc(size_of::<i32>()) as *mut i32;
604///     if my_num.is_null() {
605///         panic!("failed to allocate memory");
606///     }
607///     libc::free(my_num as *mut core::ffi::c_void);
608/// }
609/// ```
610///
611/// Usually you wouldn't literally use `malloc` and `free` from Rust,
612/// but C APIs hand out a lot of pointers generally, so are a common source
613/// of raw pointers in Rust.
614///
615/// [`null`]: ptr::null
616/// [`null_mut`]: ptr::null_mut
617/// [`is_null`]: pointer::is_null
618/// [`offset`]: pointer::offset
619/// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
620/// [`write`]: ptr::write
621/// [valid]: ptr#safety
622#[stable(feature = "rust1", since = "1.0.0")]
623#[cfg(not(feature = "ferrocene_certified"))]
624mod prim_pointer {}
625
626#[rustc_doc_primitive = "array"]
627#[doc(alias = "[]")]
628#[doc(alias = "[T;N]")] // unfortunately, rustdoc doesn't have fuzzy search for aliases
629#[doc(alias = "[T; N]")]
630/// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
631/// non-negative compile-time constant size, `N`.
632///
633/// There are two syntactic forms for creating an array:
634///
635/// * A list with each element, i.e., `[x, y, z]`.
636/// * A repeat expression `[expr; N]` where `N` is how many times to repeat `expr` in the array. `expr` must either be:
637///
638///   * A value of a type implementing the [`Copy`] trait
639///   * A `const` value
640///
641/// Note that `[expr; 0]` is allowed, and produces an empty array.
642/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
643/// be mindful of side effects.
644///
645/// Arrays of *any* size implement the following traits if the element type allows it:
646///
647/// - [`Copy`]
648/// - [`Clone`]
649/// - [`Debug`]
650/// - [`IntoIterator`] (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
651/// - [`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`]
652/// - [`Hash`]
653/// - [`AsRef`], [`AsMut`]
654/// - [`Borrow`], [`BorrowMut`]
655///
656/// Arrays of sizes from 0 to 32 (inclusive) implement the [`Default`] trait
657/// if the element type allows it. As a stopgap, trait implementations are
658/// statically generated up to size 32.
659///
660/// Arrays of sizes from 1 to 12 (inclusive) implement [`From<Tuple>`], where `Tuple`
661/// is a homogeneous [prim@tuple] of appropriate length.
662///
663/// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
664/// an array. Indeed, this provides most of the API for working with arrays.
665///
666/// Slices have a dynamic size and do not coerce to arrays. Instead, use
667/// `slice.try_into().unwrap()` or `<ArrayType>::try_from(slice).unwrap()`.
668///
669/// Array's `try_from(slice)` implementations (and the corresponding `slice.try_into()`
670/// array implementations) succeed if the input slice length is the same as the result
671/// array length. They optimize especially well when the optimizer can easily determine
672/// the slice length, e.g. `<[u8; 4]>::try_from(&slice[4..8]).unwrap()`. Array implements
673/// [TryFrom](crate::convert::TryFrom) returning:
674///
675/// - `[T; N]` copies from the slice's elements
676/// - `&[T; N]` references the original slice's elements
677/// - `&mut [T; N]` references the original slice's elements
678///
679/// You can move elements out of an array with a [slice pattern]. If you want
680/// one element, see [`mem::replace`].
681///
682/// # Examples
683///
684/// ```
685/// let mut array: [i32; 3] = [0; 3];
686///
687/// array[1] = 1;
688/// array[2] = 2;
689///
690/// assert_eq!([1, 2], &array[1..]);
691///
692/// // This loop prints: 0 1 2
693/// for x in array {
694///     print!("{x} ");
695/// }
696/// ```
697///
698/// You can also iterate over reference to the array's elements:
699///
700/// ```
701/// let array: [i32; 3] = [0; 3];
702///
703/// for x in &array { }
704/// ```
705///
706/// You can use `<ArrayType>::try_from(slice)` or `slice.try_into()` to get an array from
707/// a slice:
708///
709/// ```
710/// let bytes: [u8; 3] = [1, 0, 2];
711/// assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap()));
712/// assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap()));
713/// ```
714///
715/// You can use a [slice pattern] to move elements out of an array:
716///
717/// ```
718/// fn move_away(_: String) { /* Do interesting things. */ }
719///
720/// let [john, roa] = ["John".to_string(), "Roa".to_string()];
721/// move_away(john);
722/// move_away(roa);
723/// ```
724///
725/// Arrays can be created from homogeneous tuples of appropriate length:
726///
727/// ```
728/// let tuple: (u32, u32, u32) = (1, 2, 3);
729/// let array: [u32; 3] = tuple.into();
730/// ```
731///
732/// # Editions
733///
734/// Prior to Rust 1.53, arrays did not implement [`IntoIterator`] by value, so the method call
735/// `array.into_iter()` auto-referenced into a [slice iterator](slice::iter). Right now, the old
736/// behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring
737/// [`IntoIterator`] by value. In the future, the behavior on the 2015 and 2018 edition
738/// might be made consistent to the behavior of later editions.
739///
740/// ```rust,edition2018
741/// // Rust 2015 and 2018:
742///
743/// # #![allow(array_into_iter)] // override our `deny(warnings)`
744/// let array: [i32; 3] = [0; 3];
745///
746/// // This creates a slice iterator, producing references to each value.
747/// for item in array.into_iter().enumerate() {
748///     let (i, x): (usize, &i32) = item;
749///     println!("array[{i}] = {x}");
750/// }
751///
752/// // The `array_into_iter` lint suggests this change for future compatibility:
753/// for item in array.iter().enumerate() {
754///     let (i, x): (usize, &i32) = item;
755///     println!("array[{i}] = {x}");
756/// }
757///
758/// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
759/// for item in IntoIterator::into_iter(array).enumerate() {
760///     let (i, x): (usize, i32) = item;
761///     println!("array[{i}] = {x}");
762/// }
763/// ```
764///
765/// Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate
766/// by value, and `iter()` should be used to iterate by reference like previous editions.
767///
768/// ```rust,edition2021
769/// // Rust 2021:
770///
771/// let array: [i32; 3] = [0; 3];
772///
773/// // This iterates by reference:
774/// for item in array.iter().enumerate() {
775///     let (i, x): (usize, &i32) = item;
776///     println!("array[{i}] = {x}");
777/// }
778///
779/// // This iterates by value:
780/// for item in array.into_iter().enumerate() {
781///     let (i, x): (usize, i32) = item;
782///     println!("array[{i}] = {x}");
783/// }
784/// ```
785///
786/// Future language versions might start treating the `array.into_iter()`
787/// syntax on editions 2015 and 2018 the same as on edition 2021. So code using
788/// those older editions should still be written with this change in mind, to
789/// prevent breakage in the future. The safest way to accomplish this is to
790/// avoid the `into_iter` syntax on those editions. If an edition update is not
791/// viable/desired, there are multiple alternatives:
792/// * use `iter`, equivalent to the old behavior, creating references
793/// * use [`IntoIterator::into_iter`], equivalent to the post-2021 behavior (Rust 1.53+)
794/// * replace `for ... in array.into_iter() {` with `for ... in array {`,
795///   equivalent to the post-2021 behavior (Rust 1.53+)
796///
797/// ```rust,edition2018
798/// // Rust 2015 and 2018:
799///
800/// let array: [i32; 3] = [0; 3];
801///
802/// // This iterates by reference:
803/// for item in array.iter() {
804///     let x: &i32 = item;
805///     println!("{x}");
806/// }
807///
808/// // This iterates by value:
809/// for item in IntoIterator::into_iter(array) {
810///     let x: i32 = item;
811///     println!("{x}");
812/// }
813///
814/// // This iterates by value:
815/// for item in array {
816///     let x: i32 = item;
817///     println!("{x}");
818/// }
819///
820/// // IntoIter can also start a chain.
821/// // This iterates by value:
822/// for item in IntoIterator::into_iter(array).enumerate() {
823///     let (i, x): (usize, i32) = item;
824///     println!("array[{i}] = {x}");
825/// }
826/// ```
827///
828/// [slice]: prim@slice
829/// [`Debug`]: fmt::Debug
830/// [`Hash`]: hash::Hash
831/// [`Borrow`]: borrow::Borrow
832/// [`BorrowMut`]: borrow::BorrowMut
833/// [slice pattern]: ../reference/patterns.html#slice-patterns
834/// [`From<Tuple>`]: convert::From
835#[stable(feature = "rust1", since = "1.0.0")]
836mod prim_array {}
837
838#[rustc_doc_primitive = "slice"]
839#[doc(alias = "[")]
840#[doc(alias = "]")]
841#[doc(alias = "[]")]
842/// A dynamically-sized view into a contiguous sequence, `[T]`.
843///
844/// Contiguous here means that elements are laid out so that every element is the same
845/// distance from its neighbors.
846///
847/// *[See also the `std::slice` module](crate::slice).*
848///
849/// Slices are a view into a block of memory represented as a pointer and a
850/// length.
851///
852/// ```
853/// // slicing a Vec
854/// let vec = vec![1, 2, 3];
855/// let int_slice = &vec[..];
856/// // coercing an array to a slice
857/// let str_slice: &[&str] = &["one", "two", "three"];
858/// ```
859///
860/// Slices are either mutable or shared. The shared slice type is `&[T]`,
861/// while the mutable slice type is `&mut [T]`, where `T` represents the element
862/// type. For example, you can mutate the block of memory that a mutable slice
863/// points to:
864///
865/// ```
866/// let mut x = [1, 2, 3];
867/// let x = &mut x[..]; // Take a full slice of `x`.
868/// x[1] = 7;
869/// assert_eq!(x, &[1, 7, 3]);
870/// ```
871///
872/// It is possible to slice empty subranges of slices by using empty ranges (including `slice.len()..slice.len()`):
873/// ```
874/// let x = [1, 2, 3];
875/// let empty = &x[0..0];   // subslice before the first element
876/// assert_eq!(empty, &[]);
877/// let empty = &x[..0];    // same as &x[0..0]
878/// assert_eq!(empty, &[]);
879/// let empty = &x[1..1];   // empty subslice in the middle
880/// assert_eq!(empty, &[]);
881/// let empty = &x[3..3];   // subslice after the last element
882/// assert_eq!(empty, &[]);
883/// let empty = &x[3..];    // same as &x[3..3]
884/// assert_eq!(empty, &[]);
885/// ```
886///
887/// It is not allowed to use subranges that start with lower bound bigger than `slice.len()`:
888/// ```should_panic
889/// let x = vec![1, 2, 3];
890/// let _ = &x[4..4];
891/// ```
892///
893/// As slices store the length of the sequence they refer to, they have twice
894/// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
895/// Also see the reference on
896/// [dynamically sized types](../reference/dynamically-sized-types.html).
897///
898/// ```
899/// # use std::rc::Rc;
900/// let pointer_size = size_of::<&u8>();
901/// assert_eq!(2 * pointer_size, size_of::<&[u8]>());
902/// assert_eq!(2 * pointer_size, size_of::<*const [u8]>());
903/// assert_eq!(2 * pointer_size, size_of::<Box<[u8]>>());
904/// assert_eq!(2 * pointer_size, size_of::<Rc<[u8]>>());
905/// ```
906///
907/// ## Trait Implementations
908///
909/// Some traits are implemented for slices if the element type implements
910/// that trait. This includes [`Eq`], [`Hash`] and [`Ord`].
911///
912/// ## Iteration
913///
914/// The slices implement `IntoIterator`. The iterator yields references to the
915/// slice elements.
916///
917/// ```
918/// let numbers: &[i32] = &[0, 1, 2];
919/// for n in numbers {
920///     println!("{n} is a number!");
921/// }
922/// ```
923///
924/// The mutable slice yields mutable references to the elements:
925///
926/// ```
927/// let mut scores: &mut [i32] = &mut [7, 8, 9];
928/// for score in scores {
929///     *score += 1;
930/// }
931/// ```
932///
933/// This iterator yields mutable references to the slice's elements, so while
934/// the element type of the slice is `i32`, the element type of the iterator is
935/// `&mut i32`.
936///
937/// * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
938///   iterators.
939/// * Further methods that return iterators are [`.split`], [`.splitn`],
940///   [`.chunks`], [`.windows`] and more.
941///
942/// [`Hash`]: core::hash::Hash
943/// [`.iter`]: slice::iter
944/// [`.iter_mut`]: slice::iter_mut
945/// [`.split`]: slice::split
946/// [`.splitn`]: slice::splitn
947/// [`.chunks`]: slice::chunks
948/// [`.windows`]: slice::windows
949#[stable(feature = "rust1", since = "1.0.0")]
950#[cfg(not(feature = "ferrocene_certified"))]
951mod prim_slice {}
952
953#[rustc_doc_primitive = "str"]
954/// String slices.
955///
956/// *[See also the `std::str` module](crate::str).*
957///
958/// The `str` type, also called a 'string slice', is the most primitive string
959/// type. It is usually seen in its borrowed form, `&str`. It is also the type
960/// of string literals, `&'static str`.
961///
962/// # Basic Usage
963///
964/// String literals are string slices:
965///
966/// ```
967/// let hello_world = "Hello, World!";
968/// ```
969///
970/// Here we have declared a string slice initialized with a string literal.
971/// String literals have a static lifetime, which means the string `hello_world`
972/// is guaranteed to be valid for the duration of the entire program.
973/// We can explicitly specify `hello_world`'s lifetime as well:
974///
975/// ```
976/// let hello_world: &'static str = "Hello, world!";
977/// ```
978///
979/// # Representation
980///
981/// A `&str` is made up of two components: a pointer to some bytes, and a
982/// length. You can look at these with the [`as_ptr`] and [`len`] methods:
983///
984/// ```
985/// use std::slice;
986/// use std::str;
987///
988/// let story = "Once upon a time...";
989///
990/// let ptr = story.as_ptr();
991/// let len = story.len();
992///
993/// // story has nineteen bytes
994/// assert_eq!(19, len);
995///
996/// // We can re-build a str out of ptr and len. This is all unsafe because
997/// // we are responsible for making sure the two components are valid:
998/// let s = unsafe {
999///     // First, we build a &[u8]...
1000///     let slice = slice::from_raw_parts(ptr, len);
1001///
1002///     // ... and then convert that slice into a string slice
1003///     str::from_utf8(slice)
1004/// };
1005///
1006/// assert_eq!(s, Ok(story));
1007/// ```
1008///
1009/// [`as_ptr`]: str::as_ptr
1010/// [`len`]: str::len
1011///
1012/// Note: This example shows the internals of `&str`. `unsafe` should not be
1013/// used to get a string slice under normal circumstances. Use `as_str`
1014/// instead.
1015///
1016/// # Invariant
1017///
1018/// Rust libraries may assume that string slices are always valid UTF-8.
1019///
1020/// Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any function
1021/// called on a string slice may assume that it is valid UTF-8, which means that a non-UTF-8 string
1022/// slice can lead to undefined behavior down the road.
1023#[stable(feature = "rust1", since = "1.0.0")]
1024#[cfg(not(feature = "ferrocene_certified"))]
1025mod prim_str {}
1026
1027#[rustc_doc_primitive = "tuple"]
1028#[doc(alias = "(")]
1029#[doc(alias = ")")]
1030#[doc(alias = "()")]
1031//
1032/// A finite heterogeneous sequence, `(T, U, ..)`.
1033///
1034/// Let's cover each of those in turn:
1035///
1036/// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
1037/// of length `3`:
1038///
1039/// ```
1040/// ("hello", 5, 'c');
1041/// ```
1042///
1043/// 'Length' is also sometimes called 'arity' here; each tuple of a different
1044/// length is a different, distinct type.
1045///
1046/// Tuples are *heterogeneous*. This means that each element of the tuple can
1047/// have a different type. In that tuple above, it has the type:
1048///
1049/// ```
1050/// # let _:
1051/// (&'static str, i32, char)
1052/// # = ("hello", 5, 'c');
1053/// ```
1054///
1055/// Tuples are a *sequence*. This means that they can be accessed by position;
1056/// this is called 'tuple indexing', and it looks like this:
1057///
1058/// ```rust
1059/// let tuple = ("hello", 5, 'c');
1060///
1061/// assert_eq!(tuple.0, "hello");
1062/// assert_eq!(tuple.1, 5);
1063/// assert_eq!(tuple.2, 'c');
1064/// ```
1065///
1066/// The sequential nature of the tuple applies to its implementations of various
1067/// traits. For example, in [`PartialOrd`] and [`Ord`], the elements are compared
1068/// sequentially until the first non-equal set is found.
1069///
1070/// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
1071///
1072// Hardcoded anchor in src/librustdoc/html/format.rs
1073// linked to as `#trait-implementations-1`
1074/// # Trait implementations
1075///
1076/// In this documentation the shorthand `(T₁, T₂, …, Tₙ)` is used to represent tuples of varying
1077/// length. When that is used, any trait bound expressed on `T` applies to each element of the
1078/// tuple independently. Note that this is a convenience notation to avoid repetitive
1079/// documentation, not valid Rust syntax.
1080///
1081/// Due to a temporary restriction in Rust’s type system, the following traits are only
1082/// implemented on tuples of arity 12 or less. In the future, this may change:
1083///
1084/// * [`PartialEq`]
1085/// * [`Eq`]
1086/// * [`PartialOrd`]
1087/// * [`Ord`]
1088/// * [`Debug`]
1089/// * [`Default`]
1090/// * [`Hash`]
1091/// * [`From<[T; N]>`][from]
1092///
1093/// [from]: convert::From
1094/// [`Debug`]: fmt::Debug
1095/// [`Hash`]: hash::Hash
1096///
1097/// The following traits are implemented for tuples of any length. These traits have
1098/// implementations that are automatically generated by the compiler, so are not limited by
1099/// missing language features.
1100///
1101/// * [`Clone`]
1102/// * [`Copy`]
1103/// * [`Send`]
1104/// * [`Sync`]
1105/// * [`Unpin`]
1106/// * [`UnwindSafe`]
1107/// * [`RefUnwindSafe`]
1108///
1109/// [`UnwindSafe`]: panic::UnwindSafe
1110/// [`RefUnwindSafe`]: panic::RefUnwindSafe
1111///
1112/// # Examples
1113///
1114/// Basic usage:
1115///
1116/// ```
1117/// let tuple = ("hello", 5, 'c');
1118///
1119/// assert_eq!(tuple.0, "hello");
1120/// ```
1121///
1122/// Tuples are often used as a return type when you want to return more than
1123/// one value:
1124///
1125/// ```
1126/// fn calculate_point() -> (i32, i32) {
1127///     // Don't do a calculation, that's not the point of the example
1128///     (4, 5)
1129/// }
1130///
1131/// let point = calculate_point();
1132///
1133/// assert_eq!(point.0, 4);
1134/// assert_eq!(point.1, 5);
1135///
1136/// // Combining this with patterns can be nicer.
1137///
1138/// let (x, y) = calculate_point();
1139///
1140/// assert_eq!(x, 4);
1141/// assert_eq!(y, 5);
1142/// ```
1143///
1144/// Homogeneous tuples can be created from arrays of appropriate length:
1145///
1146/// ```
1147/// let array: [u32; 3] = [1, 2, 3];
1148/// let tuple: (u32, u32, u32) = array.into();
1149/// ```
1150///
1151#[stable(feature = "rust1", since = "1.0.0")]
1152#[cfg(not(feature = "ferrocene_certified"))]
1153mod prim_tuple {}
1154
1155// Required to make auto trait impls render.
1156// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1157#[doc(hidden)]
1158impl<T> (T,) {}
1159
1160#[rustc_doc_primitive = "f16"]
1161#[doc(alias = "half")]
1162/// A 16-bit floating-point type (specifically, the "binary16" type defined in IEEE 754-2008).
1163///
1164/// This type is very similar to [`prim@f32`] but has decreased precision because it uses half as many
1165/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on half-precision
1166/// values][wikipedia] for more information.
1167///
1168/// Note that most common platforms will not support `f16` in hardware without enabling extra target
1169/// features, with the notable exception of Apple Silicon (also known as M1, M2, etc.) processors.
1170/// Hardware support on x86/x86-64 requires the avx512fp16 or avx10.1 features, while RISC-V requires
1171/// Zfh, and Arm/AArch64 requires FEAT_FP16.  Usually the fallback implementation will be to use `f32`
1172/// hardware if it exists, and convert between `f16` and `f32` when performing math.
1173///
1174/// *[See also the `std::f16::consts` module](crate::f16::consts).*
1175///
1176/// [wikipedia]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
1177#[unstable(feature = "f16", issue = "116909")]
1178#[cfg(not(feature = "ferrocene_certified"))]
1179mod prim_f16 {}
1180
1181#[rustc_doc_primitive = "f32"]
1182#[doc(alias = "single")]
1183/// A 32-bit floating-point type (specifically, the "binary32" type defined in IEEE 754-2008).
1184///
1185/// This type can represent a wide range of decimal numbers, like `3.5`, `27`,
1186/// `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types
1187/// (such as `i32`), floating-point types can represent non-integer numbers,
1188/// too.
1189///
1190/// However, being able to represent this wide range of numbers comes at the
1191/// cost of precision: floats can only represent some of the real numbers and
1192/// calculation with floats round to a nearby representable number. For example,
1193/// `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results
1194/// in `0.20000000298023223876953125` since `0.2` cannot be exactly represented
1195/// as `f32`. Note, however, that printing floats with `println` and friends will
1196/// often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will
1197/// print `0.2`.
1198///
1199/// Additionally, `f32` can represent some special values:
1200///
1201/// - −0.0: IEEE 754 floating-point numbers have a bit that indicates their sign, so −0.0 is a
1202///   possible value. For comparison −0.0 = +0.0, but floating-point operations can carry
1203///   the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and
1204///   a negative number rounded to a value smaller than a float can represent also produces −0.0.
1205/// - [∞](#associatedconstant.INFINITY) and
1206///   [−∞](#associatedconstant.NEG_INFINITY): these result from calculations
1207///   like `1.0 / 0.0`.
1208/// - [NaN (not a number)](#associatedconstant.NAN): this value results from
1209///   calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected
1210///   behavior:
1211///   - It is not equal to any float, including itself! This is the reason `f32`
1212///     doesn't implement the `Eq` trait.
1213///   - It is also neither smaller nor greater than any float, making it
1214///     impossible to sort by the default comparison operation, which is the
1215///     reason `f32` doesn't implement the `Ord` trait.
1216///   - It is also considered *infectious* as almost all calculations where one
1217///     of the operands is NaN will also result in NaN. The explanations on this
1218///     page only explicitly document behavior on NaN operands if this default
1219///     is deviated from.
1220///   - Lastly, there are multiple bit patterns that are considered NaN.
1221///     Rust does not currently guarantee that the bit patterns of NaN are
1222///     preserved over arithmetic operations, and they are not guaranteed to be
1223///     portable or even fully deterministic! This means that there may be some
1224///     surprising results upon inspecting the bit patterns,
1225///     as the same calculations might produce NaNs with different bit patterns.
1226///     This also affects the sign of the NaN: checking `is_sign_positive` or `is_sign_negative` on
1227///     a NaN is the most common way to run into these surprising results.
1228///     (Checking `x >= 0.0` or `x <= 0.0` avoids those surprises, but also how negative/positive
1229///     zero are treated.)
1230///     See the section below for what exactly is guaranteed about the bit pattern of a NaN.
1231///
1232/// When a primitive operation (addition, subtraction, multiplication, or
1233/// division) is performed on this type, the result is rounded according to the
1234/// roundTiesToEven direction defined in IEEE 754-2008. That means:
1235///
1236/// - The result is the representable value closest to the true value, if there
1237///   is a unique closest representable value.
1238/// - If the true value is exactly half-way between two representable values,
1239///   the result is the one with an even least-significant binary digit.
1240/// - If the true value's magnitude is ≥ `f32::MAX` + 2<sup>(`f32::MAX_EXP` −
1241///   `f32::MANTISSA_DIGITS` − 1)</sup>, the result is ∞ or −∞ (preserving the
1242///   true value's sign).
1243/// - If the result of a sum exactly equals zero, the outcome is +0.0 unless
1244///   both arguments were negative, then it is -0.0. Subtraction `a - b` is
1245///   regarded as a sum `a + (-b)`.
1246///
1247/// For more information on floating-point numbers, see [Wikipedia][wikipedia].
1248///
1249/// *[See also the `std::f32::consts` module](crate::f32::consts).*
1250///
1251/// [wikipedia]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
1252///
1253/// # NaN bit patterns
1254///
1255/// This section defines the possible NaN bit patterns returned by floating-point operations.
1256///
1257/// The bit pattern of a floating-point NaN value is defined by:
1258/// - a sign bit.
1259/// - a quiet/signaling bit. Rust assumes that the quiet/signaling bit being set to `1` indicates a
1260///   quiet NaN (QNaN), and a value of `0` indicates a signaling NaN (SNaN). In the following we
1261///   will hence just call it the "quiet bit".
1262/// - a payload, which makes up the rest of the significand (i.e., the mantissa) except for the
1263///   quiet bit.
1264///
1265/// The rules for NaN values differ between *arithmetic* and *non-arithmetic* (or "bitwise")
1266/// operations. The non-arithmetic operations are unary `-`, `abs`, `copysign`, `signum`,
1267/// `{to,from}_bits`, `{to,from}_{be,le,ne}_bytes` and `is_sign_{positive,negative}`. These
1268/// operations are guaranteed to exactly preserve the bit pattern of their input except for possibly
1269/// changing the sign bit.
1270///
1271/// The following rules apply when a NaN value is returned from an arithmetic operation:
1272/// - The result has a non-deterministic sign.
1273/// - The quiet bit and payload are non-deterministically chosen from
1274///   the following set of options:
1275///
1276///   - **Preferred NaN**: The quiet bit is set and the payload is all-zero.
1277///   - **Quieting NaN propagation**: The quiet bit is set and the payload is copied from any input
1278///     operand that is a NaN. If the inputs and outputs do not have the same payload size (i.e., for
1279///     `as` casts), then
1280///     - If the output is smaller than the input, low-order bits of the payload get dropped.
1281///     - If the output is larger than the input, the payload gets filled up with 0s in the low-order
1282///       bits.
1283///   - **Unchanged NaN propagation**: The quiet bit and payload are copied from any input operand
1284///     that is a NaN. If the inputs and outputs do not have the same size (i.e., for `as` casts), the
1285///     same rules as for "quieting NaN propagation" apply, with one caveat: if the output is smaller
1286///     than the input, dropping the low-order bits may result in a payload of 0; a payload of 0 is not
1287///     possible with a signaling NaN (the all-0 significand encodes an infinity) so unchanged NaN
1288///     propagation cannot occur with some inputs.
1289///   - **Target-specific NaN**: The quiet bit is set and the payload is picked from a target-specific
1290///     set of "extra" possible NaN payloads. The set can depend on the input operand values.
1291///     See the table below for the concrete NaNs this set contains on various targets.
1292///
1293/// In particular, if all input NaNs are quiet (or if there are no input NaNs), then the output NaN
1294/// is definitely quiet. Signaling NaN outputs can only occur if they are provided as an input
1295/// value. Similarly, if all input NaNs are preferred (or if there are no input NaNs) and the target
1296/// does not have any "extra" NaN payloads, then the output NaN is guaranteed to be preferred.
1297///
1298/// The non-deterministic choice happens when the operation is executed; i.e., the result of a
1299/// NaN-producing floating-point operation is a stable bit pattern (looking at these bits multiple
1300/// times will yield consistent results), but running the same operation twice with the same inputs
1301/// can produce different results.
1302///
1303/// These guarantees are neither stronger nor weaker than those of IEEE 754: IEEE 754 guarantees
1304/// that an operation never returns a signaling NaN, whereas it is possible for operations like
1305/// `SNAN * 1.0` to return a signaling NaN in Rust. Conversely, IEEE 754 makes no statement at all
1306/// about which quiet NaN is returned, whereas Rust restricts the set of possible results to the
1307/// ones listed above.
1308///
1309/// Unless noted otherwise, the same rules also apply to NaNs returned by other library functions
1310/// (e.g. `min`, `minimum`, `max`, `maximum`); other aspects of their semantics and which IEEE 754
1311/// operation they correspond to are documented with the respective functions.
1312///
1313/// When an arithmetic floating-point operation is executed in `const` context, the same rules
1314/// apply: no guarantee is made about which of the NaN bit patterns described above will be
1315/// returned. The result does not have to match what happens when executing the same code at
1316/// runtime, and the result can vary depending on factors such as compiler version and flags.
1317///
1318/// ### Target-specific "extra" NaN values
1319// FIXME: Is there a better place to put this?
1320///
1321/// | `target_arch` | Extra payloads possible on this platform |
1322/// |---------------|------------------------------------------|
1323// Sorted alphabetically
1324/// | `aarch64`, `arm`, `arm64ec`, `loongarch64`, `powerpc` (except when `target_abi = "spe"`), `powerpc64`, `riscv32`, `riscv64`, `s390x`, `x86`, `x86_64` | None |
1325/// | `nvptx64` | All payloads |
1326/// | `sparc`, `sparc64` | The all-one payload |
1327/// | `wasm32`, `wasm64` | If all input NaNs are quiet with all-zero payload: None.<br> Otherwise: all payloads. |
1328///
1329/// For targets not in this table, all payloads are possible.
1330///
1331/// # Algebraic operators
1332///
1333/// Algebraic operators of the form `a.algebraic_*(b)` allow the compiler to optimize
1334/// floating point operations using all the usual algebraic properties of real numbers --
1335/// despite the fact that those properties do *not* hold on floating point numbers.
1336/// This can give a great performance boost since it may unlock vectorization.
1337///
1338/// The exact set of optimizations is unspecified but typically allows combining operations,
1339/// rearranging series of operations based on mathematical properties, converting between division
1340/// and reciprocal multiplication, and disregarding the sign of zero. This means that the results of
1341/// elementary operations may have undefined precision, and "non-mathematical" values
1342/// such as NaN, +/-Inf, or -0.0 may behave in unexpected ways, but these operations
1343/// will never cause undefined behavior.
1344///
1345/// Because of the unpredictable nature of compiler optimizations, the same inputs may produce
1346/// different results even within a single program run. **Unsafe code must not rely on any property
1347/// of the return value for soundness.** However, implementations will generally do their best to
1348/// pick a reasonable tradeoff between performance and accuracy of the result.
1349///
1350/// For example:
1351///
1352/// ```
1353/// # #![feature(float_algebraic)]
1354/// # #![allow(unused_assignments)]
1355/// # let mut x: f32 = 0.0;
1356/// # let a: f32 = 1.0;
1357/// # let b: f32 = 2.0;
1358/// # let c: f32 = 3.0;
1359/// # let d: f32 = 4.0;
1360/// x = a.algebraic_add(b).algebraic_add(c).algebraic_add(d);
1361/// ```
1362///
1363/// May be rewritten as:
1364///
1365/// ```
1366/// # #![allow(unused_assignments)]
1367/// # let mut x: f32 = 0.0;
1368/// # let a: f32 = 1.0;
1369/// # let b: f32 = 2.0;
1370/// # let c: f32 = 3.0;
1371/// # let d: f32 = 4.0;
1372/// x = a + b + c + d; // As written
1373/// x = (a + c) + (b + d); // Reordered to shorten critical path and enable vectorization
1374/// ```
1375
1376#[stable(feature = "rust1", since = "1.0.0")]
1377mod prim_f32 {}
1378
1379#[rustc_doc_primitive = "f64"]
1380#[doc(alias = "double")]
1381/// A 64-bit floating-point type (specifically, the "binary64" type defined in IEEE 754-2008).
1382///
1383/// This type is very similar to [`prim@f32`], but has increased precision by using twice as many
1384/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on double-precision
1385/// values][wikipedia] for more information.
1386///
1387/// *[See also the `std::f64::consts` module](crate::f64::consts).*
1388///
1389/// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
1390#[stable(feature = "rust1", since = "1.0.0")]
1391mod prim_f64 {}
1392
1393#[rustc_doc_primitive = "f128"]
1394#[doc(alias = "quad")]
1395/// A 128-bit floating-point type (specifically, the "binary128" type defined in IEEE 754-2008).
1396///
1397/// This type is very similar to [`prim@f32`] and [`prim@f64`], but has increased precision by using twice
1398/// as many bits as `f64`. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on
1399/// quad-precision values][wikipedia] for more information.
1400///
1401/// Note that no platforms have hardware support for `f128` without enabling target specific features,
1402/// as for all instruction set architectures `f128` is considered an optional feature.  Only Power ISA
1403/// ("PowerPC") and RISC-V (via the Q extension) specify it, and only certain microarchitectures
1404/// actually implement it. For x86-64 and AArch64, ISA support is not even specified, so it will always
1405/// be a software implementation significantly slower than `f64`.
1406///
1407/// _Note: `f128` support is incomplete. Many platforms will not be able to link math functions. On
1408/// x86 in particular, these functions do link but their results are always incorrect._
1409///
1410/// *[See also the `std::f128::consts` module](crate::f128::consts).*
1411///
1412/// [wikipedia]: https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format
1413#[unstable(feature = "f128", issue = "116909")]
1414#[cfg(not(feature = "ferrocene_certified"))]
1415mod prim_f128 {}
1416
1417#[rustc_doc_primitive = "i8"]
1418//
1419/// The 8-bit signed integer type.
1420#[stable(feature = "rust1", since = "1.0.0")]
1421mod prim_i8 {}
1422
1423#[rustc_doc_primitive = "i16"]
1424//
1425/// The 16-bit signed integer type.
1426#[stable(feature = "rust1", since = "1.0.0")]
1427mod prim_i16 {}
1428
1429#[rustc_doc_primitive = "i32"]
1430//
1431/// The 32-bit signed integer type.
1432#[stable(feature = "rust1", since = "1.0.0")]
1433mod prim_i32 {}
1434
1435#[rustc_doc_primitive = "i64"]
1436//
1437/// The 64-bit signed integer type.
1438#[stable(feature = "rust1", since = "1.0.0")]
1439mod prim_i64 {}
1440
1441#[rustc_doc_primitive = "i128"]
1442//
1443/// The 128-bit signed integer type.
1444///
1445/// # ABI compatibility
1446///
1447/// Rust's `i128` is expected to be ABI-compatible with C's `__int128` on platforms where the type
1448/// is available, which includes most 64-bit architectures. If any platforms that do not specify
1449/// `__int128` are updated to introduce it, the Rust `i128` ABI on relevant targets will be changed
1450/// to match.
1451///
1452/// It is important to note that in C, `__int128` is _not_ the same as `_BitInt(128)`, and the two
1453/// types are allowed to have different ABIs. In particular, on x86, `__int128` and `_BitInt(128)`
1454/// do not use the same alignment. `i128` is intended to always match `__int128` and does not
1455/// attempt to match `_BitInt(128)` on platforms without `__int128`.
1456#[stable(feature = "i128", since = "1.26.0")]
1457mod prim_i128 {}
1458
1459#[rustc_doc_primitive = "u8"]
1460//
1461/// The 8-bit unsigned integer type.
1462#[stable(feature = "rust1", since = "1.0.0")]
1463mod prim_u8 {}
1464
1465#[rustc_doc_primitive = "u16"]
1466//
1467/// The 16-bit unsigned integer type.
1468#[stable(feature = "rust1", since = "1.0.0")]
1469mod prim_u16 {}
1470
1471#[rustc_doc_primitive = "u32"]
1472//
1473/// The 32-bit unsigned integer type.
1474#[stable(feature = "rust1", since = "1.0.0")]
1475mod prim_u32 {}
1476
1477#[rustc_doc_primitive = "u64"]
1478//
1479/// The 64-bit unsigned integer type.
1480#[stable(feature = "rust1", since = "1.0.0")]
1481mod prim_u64 {}
1482
1483#[rustc_doc_primitive = "u128"]
1484//
1485/// The 128-bit unsigned integer type.
1486///
1487/// Please see [the documentation for `i128`](prim@i128) for information on ABI compatibility.
1488#[stable(feature = "i128", since = "1.26.0")]
1489mod prim_u128 {}
1490
1491#[rustc_doc_primitive = "isize"]
1492//
1493/// The pointer-sized signed integer type.
1494///
1495/// The size of this primitive is how many bytes it takes to reference any
1496/// location in memory. For example, on a 32 bit target, this is 4 bytes
1497/// and on a 64 bit target, this is 8 bytes.
1498#[stable(feature = "rust1", since = "1.0.0")]
1499mod prim_isize {}
1500
1501#[rustc_doc_primitive = "usize"]
1502//
1503/// The pointer-sized unsigned integer type.
1504///
1505/// The size of this primitive is how many bytes it takes to reference any
1506/// location in memory. For example, on a 32 bit target, this is 4 bytes
1507/// and on a 64 bit target, this is 8 bytes.
1508#[stable(feature = "rust1", since = "1.0.0")]
1509mod prim_usize {}
1510
1511#[rustc_doc_primitive = "reference"]
1512#[doc(alias = "&")]
1513#[doc(alias = "&mut")]
1514//
1515/// References, `&T` and `&mut T`.
1516///
1517/// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
1518/// operators on a value, or by using a [`ref`](../std/keyword.ref.html) or
1519/// <code>[ref](../std/keyword.ref.html) [mut](../std/keyword.mut.html)</code> pattern.
1520///
1521/// For those familiar with pointers, a reference is just a pointer that is assumed to be
1522/// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
1523/// <code>&[bool]</code> can only point to an allocation containing the integer values `1`
1524/// ([`true`](../std/keyword.true.html)) or `0` ([`false`](../std/keyword.false.html)), but
1525/// creating a <code>&[bool]</code> that points to an allocation containing
1526/// the value `3` causes undefined behavior.
1527/// In fact, <code>[Option]\<&T></code> has the same memory representation as a
1528/// nullable but aligned pointer, and can be passed across FFI boundaries as such.
1529///
1530/// In most cases, references can be used much like the original value. Field access, method
1531/// calling, and indexing work the same (save for mutability rules, of course). In addition, the
1532/// comparison operators transparently defer to the referent's implementation, allowing references
1533/// to be compared the same as owned values.
1534///
1535/// References have a lifetime attached to them, which represents the scope for which the borrow is
1536/// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
1537/// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
1538/// total life of the program. For example, string literals have a `'static` lifetime because the
1539/// text data is embedded into the binary of the program, rather than in an allocation that needs
1540/// to be dynamically managed.
1541///
1542/// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
1543/// references with longer lifetimes can be freely coerced into references with shorter ones.
1544///
1545/// Reference equality by address, instead of comparing the values pointed to, is accomplished via
1546/// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
1547/// [`PartialEq`] compares values.
1548///
1549/// ```
1550/// use std::ptr;
1551///
1552/// let five = 5;
1553/// let other_five = 5;
1554/// let five_ref = &five;
1555/// let same_five_ref = &five;
1556/// let other_five_ref = &other_five;
1557///
1558/// assert!(five_ref == same_five_ref);
1559/// assert!(five_ref == other_five_ref);
1560///
1561/// assert!(ptr::eq(five_ref, same_five_ref));
1562/// assert!(!ptr::eq(five_ref, other_five_ref));
1563/// ```
1564///
1565/// For more information on how to use references, see [the book's section on "References and
1566/// Borrowing"][book-refs].
1567///
1568/// [book-refs]: ../book/ch04-02-references-and-borrowing.html
1569///
1570/// # Trait implementations
1571///
1572/// The following traits are implemented for all `&T`, regardless of the type of its referent:
1573///
1574/// * [`Copy`]
1575/// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
1576/// * [`Deref`]
1577/// * [`Borrow`]
1578/// * [`fmt::Pointer`]
1579///
1580/// [`Deref`]: ops::Deref
1581/// [`Borrow`]: borrow::Borrow
1582///
1583/// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
1584/// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
1585/// referent:
1586///
1587/// * [`DerefMut`]
1588/// * [`BorrowMut`]
1589///
1590/// [`DerefMut`]: ops::DerefMut
1591/// [`BorrowMut`]: borrow::BorrowMut
1592/// [bool]: prim@bool
1593///
1594/// The following traits are implemented on `&T` references if the underlying `T` also implements
1595/// that trait:
1596///
1597/// * All the traits in [`std::fmt`] except [`fmt::Pointer`] (which is implemented regardless of the type of its referent) and [`fmt::Write`]
1598/// * [`PartialOrd`]
1599/// * [`Ord`]
1600/// * [`PartialEq`]
1601/// * [`Eq`]
1602/// * [`AsRef`]
1603/// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
1604/// * [`Hash`]
1605/// * [`ToSocketAddrs`]
1606/// * [`Sync`]
1607///
1608/// [`std::fmt`]: fmt
1609/// [`Hash`]: hash::Hash
1610/// [`ToSocketAddrs`]: ../std/net/trait.ToSocketAddrs.html
1611///
1612/// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
1613/// implements that trait:
1614///
1615/// * [`AsMut`]
1616/// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
1617/// * [`fmt::Write`]
1618/// * [`Iterator`]
1619/// * [`DoubleEndedIterator`]
1620/// * [`ExactSizeIterator`]
1621/// * [`FusedIterator`]
1622/// * [`TrustedLen`]
1623/// * [`Send`]
1624/// * [`io::Write`]
1625/// * [`Read`]
1626/// * [`Seek`]
1627/// * [`BufRead`]
1628///
1629/// [`FusedIterator`]: iter::FusedIterator
1630/// [`TrustedLen`]: iter::TrustedLen
1631/// [`Seek`]: ../std/io/trait.Seek.html
1632/// [`BufRead`]: ../std/io/trait.BufRead.html
1633/// [`Read`]: ../std/io/trait.Read.html
1634/// [`io::Write`]: ../std/io/trait.Write.html
1635///
1636/// In addition, `&T` references implement [`Send`] if and only if `T` implements [`Sync`].
1637///
1638/// Note that due to method call deref coercion, simply calling a trait method will act like they
1639/// work on references as well as they do on owned values! The implementations described here are
1640/// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1641/// locally known.
1642///
1643/// # Safety
1644///
1645/// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, when such values cross an API
1646/// boundary, the following invariants must generally be upheld:
1647///
1648/// * `t` is non-null
1649/// * `t` is aligned to `align_of_val(t)`
1650/// * if `size_of_val(t) > 0`, then `t` is dereferenceable for `size_of_val(t)` many bytes
1651///
1652/// If `t` points at address `a`, being "dereferenceable" for N bytes means that the memory range
1653/// `[a, a + N)` is all contained within a single [allocation].
1654///
1655/// For instance, this means that unsafe code in a safe function may assume these invariants are
1656/// ensured of arguments passed by the caller, and it may assume that these invariants are ensured
1657/// of return values from any safe functions it calls.
1658///
1659/// For the other direction, things are more complicated: when unsafe code passes arguments
1660/// to safe functions or returns values from safe functions, they generally must *at least*
1661/// not violate these invariants. The full requirements are stronger, as the reference generally
1662/// must point to data that is safe to use at type `T`.
1663///
1664/// It is not decided yet whether unsafe code may violate these invariants temporarily on internal
1665/// data. As a consequence, unsafe code which violates these invariants temporarily on internal data
1666/// may be unsound or become unsound in future versions of Rust depending on how this question is
1667/// decided.
1668///
1669/// [allocation]: ptr#allocation
1670#[stable(feature = "rust1", since = "1.0.0")]
1671mod prim_ref {}
1672
1673#[rustc_doc_primitive = "fn"]
1674//
1675/// Function pointers, like `fn(usize) -> bool`.
1676///
1677/// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1678///
1679/// Function pointers are pointers that point to *code*, not data. They can be called
1680/// just like functions. Like references, function pointers are, among other things, assumed to
1681/// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
1682/// pointers, make your type [`Option<fn()>`](core::option#options-and-pointers-nullable-pointers)
1683/// with your required signature.
1684///
1685/// Note that FFI requires additional care to ensure that the ABI for both sides of the call match.
1686/// The exact requirements are not currently documented.
1687///
1688/// ### Safety
1689///
1690/// Plain function pointers are obtained by casting either plain functions, or closures that don't
1691/// capture an environment:
1692///
1693/// ```
1694/// fn add_one(x: usize) -> usize {
1695///     x + 1
1696/// }
1697///
1698/// let ptr: fn(usize) -> usize = add_one;
1699/// assert_eq!(ptr(5), 6);
1700///
1701/// let clos: fn(usize) -> usize = |x| x + 5;
1702/// assert_eq!(clos(5), 10);
1703/// ```
1704///
1705/// In addition to varying based on their signature, function pointers come in two flavors: safe
1706/// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1707/// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1708///
1709/// ```
1710/// fn add_one(x: usize) -> usize {
1711///     x + 1
1712/// }
1713///
1714/// unsafe fn add_one_unsafely(x: usize) -> usize {
1715///     x + 1
1716/// }
1717///
1718/// let safe_ptr: fn(usize) -> usize = add_one;
1719///
1720/// //ERROR: mismatched types: expected normal fn, found unsafe fn
1721/// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1722///
1723/// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1724/// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1725/// ```
1726///
1727/// ### ABI
1728///
1729/// On top of that, function pointers can vary based on what ABI they use. This
1730/// is achieved by adding the `extern` keyword before the type, followed by the
1731/// ABI in question. The default ABI is "Rust", i.e., `fn()` is the exact same
1732/// type as `extern "Rust" fn()`. A pointer to a function with C ABI would have
1733/// type `extern "C" fn()`.
1734///
1735/// `extern "ABI" { ... }` blocks declare functions with ABI "ABI". The default
1736/// here is "C", i.e., functions declared in an `extern {...}` block have "C"
1737/// ABI.
1738///
1739/// For more information and a list of supported ABIs, see [the nomicon's
1740/// section on foreign calling conventions][nomicon-abi].
1741///
1742/// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1743///
1744/// ### Variadic functions
1745///
1746/// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1747/// to be called with a variable number of arguments. Normal Rust functions, even those with an
1748/// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1749/// variadic functions][nomicon-variadic].
1750///
1751/// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1752///
1753/// ### Creating function pointers
1754///
1755/// When `bar` is the name of a function, then the expression `bar` is *not* a
1756/// function pointer. Rather, it denotes a value of an unnameable type that
1757/// uniquely identifies the function `bar`. The value is zero-sized because the
1758/// type already identifies the function. This has the advantage that "calling"
1759/// the value (it implements the `Fn*` traits) does not require dynamic
1760/// dispatch.
1761///
1762/// This zero-sized type *coerces* to a regular function pointer. For example:
1763///
1764/// ```rust
1765/// fn bar(x: i32) {}
1766///
1767/// let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
1768/// assert_eq!(size_of_val(&not_bar_ptr), 0);
1769///
1770/// let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
1771/// assert_eq!(size_of_val(&bar_ptr), size_of::<usize>());
1772///
1773/// let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
1774/// ```
1775///
1776/// The last line shows that `&bar` is not a function pointer either. Rather, it
1777/// is a reference to the function-specific ZST. `&bar` is basically never what you
1778/// want when `bar` is a function.
1779///
1780/// ### Casting to and from integers
1781///
1782/// You can cast function pointers directly to integers:
1783///
1784/// ```rust
1785/// let fnptr: fn(i32) -> i32 = |x| x+2;
1786/// let fnptr_addr = fnptr as usize;
1787/// ```
1788///
1789/// However, a direct cast back is not possible. You need to use `transmute`:
1790///
1791/// ```rust
1792/// # #[cfg(not(miri))] { // FIXME: use strict provenance APIs once they are stable, then remove this `cfg`
1793/// # let fnptr: fn(i32) -> i32 = |x| x+2;
1794/// # let fnptr_addr = fnptr as usize;
1795/// let fnptr = fnptr_addr as *const ();
1796/// let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
1797/// assert_eq!(fnptr(40), 42);
1798/// # }
1799/// ```
1800///
1801/// Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
1802/// This avoids an integer-to-pointer `transmute`, which can be problematic.
1803/// Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
1804///
1805/// Note that all of this is not portable to platforms where function pointers and data pointers
1806/// have different sizes.
1807///
1808/// ### ABI compatibility
1809///
1810/// Generally, when a function is declared with one signature and called via a function pointer with
1811/// a different signature, the two signatures must be *ABI-compatible* or else calling the function
1812/// via that function pointer is Undefined Behavior. ABI compatibility is a lot stricter than merely
1813/// having the same memory layout; for example, even if `i32` and `f32` have the same size and
1814/// alignment, they might be passed in different registers and hence not be ABI-compatible.
1815///
1816/// ABI compatibility as a concern only arises in code that alters the type of function pointers,
1817/// and code that imports functions via `extern` blocks. Altering the type of function pointers is
1818/// wildly unsafe (as in, a lot more unsafe than even [`transmute_copy`][mem::transmute_copy]), and
1819/// should only occur in the most exceptional circumstances. Most Rust code just imports functions
1820/// via `use`. So, most likely you do not have to worry about ABI compatibility.
1821///
1822/// But assuming such circumstances, what are the rules? For this section, we are only considering
1823/// the ABI of direct Rust-to-Rust calls (with both definition and callsite visible to the
1824/// Rust compiler), not linking in general -- once functions are imported via `extern` blocks, there
1825/// are more things to consider that we do not go into here. Note that this also applies to
1826/// passing/calling functions across language boundaries via function pointers.
1827///
1828/// **Nothing in this section should be taken as a guarantee for non-Rust-to-Rust calls, even with
1829/// types from `core::ffi` or `libc`**.
1830///
1831/// For two signatures to be considered *ABI-compatible*, they must use a compatible ABI string,
1832/// must take the same number of arguments, and the individual argument types and the return types
1833/// must be ABI-compatible. The ABI string is declared via `extern "ABI" fn(...) -> ...`; note that
1834/// `fn name(...) -> ...` implicitly uses the `"Rust"` ABI string and `extern fn name(...) -> ...`
1835/// implicitly uses the `"C"` ABI string.
1836///
1837/// The ABI strings are guaranteed to be compatible if they are the same, or if the caller ABI
1838/// string is `$X-unwind` and the callee ABI string is `$X`, where `$X` is one of the following:
1839/// "C", "aapcs", "fastcall", "stdcall", "system", "sysv64", "thiscall", "vectorcall", "win64".
1840///
1841/// The following types are guaranteed to be ABI-compatible:
1842///
1843/// - `*const T`, `*mut T`, `&T`, `&mut T`, `Box<T>` (specifically, only `Box<T, Global>`), and
1844///   `NonNull<T>` are all ABI-compatible with each other for all `T`. They are also ABI-compatible
1845///   with each other for _different_ `T` if they have the same metadata type (`<T as
1846///   Pointee>::Metadata`).
1847/// - `usize` is ABI-compatible with the `uN` integer type of the same size, and likewise `isize` is
1848///   ABI-compatible with the `iN` integer type of the same size.
1849/// - `char` is ABI-compatible with `u32`.
1850/// - Any two `fn` (function pointer) types are ABI-compatible with each other if they have the same
1851///   ABI string or the ABI string only differs in a trailing `-unwind`, independent of the rest of
1852///   their signature. (This means you can pass `fn()` to a function expecting `fn(i32)`, and the
1853///   call will be valid ABI-wise. The callee receives the result of transmuting the function pointer
1854///   from `fn()` to `fn(i32)`; that transmutation is itself a well-defined operation, it's just
1855///   almost certainly UB to later call that function pointer.)
1856/// - Any two types with size 0 and alignment 1 are ABI-compatible.
1857/// - A `repr(transparent)` type `T` is ABI-compatible with its unique non-trivial field, i.e., the
1858///   unique field that doesn't have size 0 and alignment 1 (if there is such a field).
1859/// - `i32` is ABI-compatible with `NonZero<i32>`, and similar for all other integer types.
1860/// - If `T` is guaranteed to be subject to the [null pointer
1861///   optimization](option/index.html#representation), and `E` is an enum satisfying the following
1862///   requirements, then `T` and `E` are ABI-compatible. Such an enum `E` is called "option-like".
1863///   - The enum `E` uses the [`Rust` representation], and is not modified by the `align` or
1864///     `packed` representation modifiers.
1865///   - The enum `E` has exactly two variants.
1866///   - One variant has exactly one field, of type `T`.
1867///   - All fields of the other variant are zero-sized with 1-byte alignment.
1868///
1869/// Furthermore, ABI compatibility satisfies the following general properties:
1870///
1871/// - Every type is ABI-compatible with itself.
1872/// - If `T1` and `T2` are ABI-compatible and `T2` and `T3` are ABI-compatible, then so are `T1` and
1873///   `T3` (i.e., ABI-compatibility is transitive).
1874/// - If `T1` and `T2` are ABI-compatible, then so are `T2` and `T1` (i.e., ABI-compatibility is
1875///   symmetric).
1876///
1877/// More signatures can be ABI-compatible on specific targets, but that should not be relied upon
1878/// since it is not portable and not a stable guarantee.
1879///
1880/// Noteworthy cases of types *not* being ABI-compatible in general are:
1881/// * `bool` vs `u8`, `i32` vs `u32`, `char` vs `i32`: on some targets, the calling conventions for
1882///   these types differ in terms of what they guarantee for the remaining bits in the register that
1883///   are not used by the value.
1884/// * `i32` vs `f32` are not compatible either, as has already been mentioned above.
1885/// * `struct Foo(u32)` and `u32` are not compatible (without `repr(transparent)`) since structs are
1886///   aggregate types and often passed in a different way than primitives like `i32`.
1887///
1888/// Note that these rules describe when two completely known types are ABI-compatible. When
1889/// considering ABI compatibility of a type declared in another crate (including the standard
1890/// library), consider that any type that has a private field or the `#[non_exhaustive]` attribute
1891/// may change its layout as a non-breaking update unless documented otherwise -- so for instance,
1892/// even if such a type is a 1-ZST or `repr(transparent)` right now, this might change with any
1893/// library version bump.
1894///
1895/// If the declared signature and the signature of the function pointer are ABI-compatible, then the
1896/// function call behaves as if every argument was [`transmute`d][mem::transmute] from the
1897/// type in the function pointer to the type at the function declaration, and the return value is
1898/// [`transmute`d][mem::transmute] from the type in the declaration to the type in the
1899/// pointer. All the usual caveats and concerns around transmutation apply; for instance, if the
1900/// function expects a `NonZero<i32>` and the function pointer uses the ABI-compatible type
1901/// `Option<NonZero<i32>>`, and the value used for the argument is `None`, then this call is Undefined
1902/// Behavior since transmuting `None::<NonZero<i32>>` to `NonZero<i32>` violates the non-zero
1903/// requirement.
1904///
1905/// ### Trait implementations
1906///
1907/// In this documentation the shorthand `fn(T₁, T₂, …, Tₙ)` is used to represent non-variadic
1908/// function pointers of varying length. Note that this is a convenience notation to avoid
1909/// repetitive documentation, not valid Rust syntax.
1910///
1911/// The following traits are implemented for function pointers with any number of arguments and
1912/// any ABI.
1913///
1914/// * [`PartialEq`]
1915/// * [`Eq`]
1916/// * [`PartialOrd`]
1917/// * [`Ord`]
1918/// * [`Hash`]
1919/// * [`Pointer`]
1920/// * [`Debug`]
1921/// * [`Clone`]
1922/// * [`Copy`]
1923/// * [`Send`]
1924/// * [`Sync`]
1925/// * [`Unpin`]
1926/// * [`UnwindSafe`]
1927/// * [`RefUnwindSafe`]
1928///
1929/// Note that while this type implements `PartialEq`, comparing function pointers is unreliable:
1930/// pointers to the same function can compare inequal (because functions are duplicated in multiple
1931/// codegen units), and pointers to *different* functions can compare equal (since identical
1932/// functions can be deduplicated within a codegen unit).
1933///
1934/// [`Hash`]: hash::Hash
1935/// [`Pointer`]: fmt::Pointer
1936/// [`UnwindSafe`]: panic::UnwindSafe
1937/// [`RefUnwindSafe`]: panic::RefUnwindSafe
1938/// [`Rust` representation]: <https://doc.rust-lang.org/reference/type-layout.html#the-rust-representation>
1939///
1940/// In addition, all *safe* function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`], because
1941/// these traits are specially known to the compiler.
1942#[stable(feature = "rust1", since = "1.0.0")]
1943#[cfg(not(feature = "ferrocene_certified"))]
1944mod prim_fn {}
1945
1946// Required to make auto trait impls render.
1947// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1948#[doc(hidden)]
1949impl<Ret, T> fn(T) -> Ret {}