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