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() * 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() * 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, size_of_val(&s[..]));
447/// assert_eq!(32, 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/// unsafe {
598///     let my_num: *mut i32 = libc::malloc(size_of::<i32>()) as *mut i32;
599///     if my_num.is_null() {
600///         panic!("failed to allocate memory");
601///     }
602///     libc::free(my_num as *mut core::ffi::c_void);
603/// }
604/// ```
605///
606/// Usually you wouldn't literally use `malloc` and `free` from Rust,
607/// but C APIs hand out a lot of pointers generally, so are a common source
608/// of raw pointers in Rust.
609///
610/// [`null`]: ptr::null
611/// [`null_mut`]: ptr::null_mut
612/// [`is_null`]: pointer::is_null
613/// [`offset`]: pointer::offset
614/// [`into_raw`]: ../std/boxed/struct.Box.html#method.into_raw
615/// [`write`]: ptr::write
616/// [valid]: ptr#safety
617#[stable(feature = "rust1", since = "1.0.0")]
618mod prim_pointer {}
619
620#[rustc_doc_primitive = "array"]
621#[doc(alias = "[]")]
622#[doc(alias = "[T;N]")] // unfortunately, rustdoc doesn't have fuzzy search for aliases
623#[doc(alias = "[T; N]")]
624/// A fixed-size array, denoted `[T; N]`, for the element type, `T`, and the
625/// non-negative compile-time constant size, `N`.
626///
627/// There are two syntactic forms for creating an array:
628///
629/// * A list with each element, i.e., `[x, y, z]`.
630/// * A repeat expression `[expr; N]` where `N` is how many times to repeat `expr` in the array. `expr` must either be:
631///
632///   * A value of a type implementing the [`Copy`] trait
633///   * A `const` value
634///
635/// Note that `[expr; 0]` is allowed, and produces an empty array.
636/// This will still evaluate `expr`, however, and immediately drop the resulting value, so
637/// be mindful of side effects.
638///
639/// Arrays of *any* size implement the following traits if the element type allows it:
640///
641/// - [`Copy`]
642/// - [`Clone`]
643/// - [`Debug`]
644/// - [`IntoIterator`] (implemented for `[T; N]`, `&[T; N]` and `&mut [T; N]`)
645/// - [`PartialEq`], [`PartialOrd`], [`Eq`], [`Ord`]
646/// - [`Hash`]
647/// - [`AsRef`], [`AsMut`]
648/// - [`Borrow`], [`BorrowMut`]
649///
650/// Arrays of sizes from 0 to 32 (inclusive) implement the [`Default`] trait
651/// if the element type allows it. As a stopgap, trait implementations are
652/// statically generated up to size 32.
653///
654/// Arrays of sizes from 1 to 12 (inclusive) implement [`From<Tuple>`], where `Tuple`
655/// is a homogeneous [prim@tuple] of appropriate length.
656///
657/// Arrays coerce to [slices (`[T]`)][slice], so a slice method may be called on
658/// an array. Indeed, this provides most of the API for working with arrays.
659///
660/// Slices have a dynamic size and do not coerce to arrays. Instead, use
661/// `slice.try_into().unwrap()` or `<ArrayType>::try_from(slice).unwrap()`.
662///
663/// Array's `try_from(slice)` implementations (and the corresponding `slice.try_into()`
664/// array implementations) succeed if the input slice length is the same as the result
665/// array length. They optimize especially well when the optimizer can easily determine
666/// the slice length, e.g. `<[u8; 4]>::try_from(&slice[4..8]).unwrap()`. Array implements
667/// [TryFrom](crate::convert::TryFrom) returning:
668///
669/// - `[T; N]` copies from the slice's elements
670/// - `&[T; N]` references the original slice's elements
671/// - `&mut [T; N]` references the original slice's elements
672///
673/// You can move elements out of an array with a [slice pattern]. If you want
674/// one element, see [`mem::replace`].
675///
676/// # Examples
677///
678/// ```
679/// let mut array: [i32; 3] = [0; 3];
680///
681/// array[1] = 1;
682/// array[2] = 2;
683///
684/// assert_eq!([1, 2], &array[1..]);
685///
686/// // This loop prints: 0 1 2
687/// for x in array {
688///     print!("{x} ");
689/// }
690/// ```
691///
692/// You can also iterate over reference to the array's elements:
693///
694/// ```
695/// let array: [i32; 3] = [0; 3];
696///
697/// for x in &array { }
698/// ```
699///
700/// You can use `<ArrayType>::try_from(slice)` or `slice.try_into()` to get an array from
701/// a slice:
702///
703/// ```
704/// let bytes: [u8; 3] = [1, 0, 2];
705/// assert_eq!(1, u16::from_le_bytes(<[u8; 2]>::try_from(&bytes[0..2]).unwrap()));
706/// assert_eq!(512, u16::from_le_bytes(bytes[1..3].try_into().unwrap()));
707/// ```
708///
709/// You can use a [slice pattern] to move elements out of an array:
710///
711/// ```
712/// fn move_away(_: String) { /* Do interesting things. */ }
713///
714/// let [john, roa] = ["John".to_string(), "Roa".to_string()];
715/// move_away(john);
716/// move_away(roa);
717/// ```
718///
719/// Arrays can be created from homogeneous tuples of appropriate length:
720///
721/// ```
722/// let tuple: (u32, u32, u32) = (1, 2, 3);
723/// let array: [u32; 3] = tuple.into();
724/// ```
725///
726/// # Editions
727///
728/// Prior to Rust 1.53, arrays did not implement [`IntoIterator`] by value, so the method call
729/// `array.into_iter()` auto-referenced into a [slice iterator](slice::iter). Right now, the old
730/// behavior is preserved in the 2015 and 2018 editions of Rust for compatibility, ignoring
731/// [`IntoIterator`] by value. In the future, the behavior on the 2015 and 2018 edition
732/// might be made consistent to the behavior of later editions.
733///
734/// ```rust,edition2018
735/// // Rust 2015 and 2018:
736///
737/// # #![allow(array_into_iter)] // override our `deny(warnings)`
738/// let array: [i32; 3] = [0; 3];
739///
740/// // This creates a slice iterator, producing references to each value.
741/// for item in array.into_iter().enumerate() {
742///     let (i, x): (usize, &i32) = item;
743///     println!("array[{i}] = {x}");
744/// }
745///
746/// // The `array_into_iter` lint suggests this change for future compatibility:
747/// for item in array.iter().enumerate() {
748///     let (i, x): (usize, &i32) = item;
749///     println!("array[{i}] = {x}");
750/// }
751///
752/// // You can explicitly iterate an array by value using `IntoIterator::into_iter`
753/// for item in IntoIterator::into_iter(array).enumerate() {
754///     let (i, x): (usize, i32) = item;
755///     println!("array[{i}] = {x}");
756/// }
757/// ```
758///
759/// Starting in the 2021 edition, `array.into_iter()` uses `IntoIterator` normally to iterate
760/// by value, and `iter()` should be used to iterate by reference like previous editions.
761///
762/// ```rust,edition2021
763/// // Rust 2021:
764///
765/// let array: [i32; 3] = [0; 3];
766///
767/// // This iterates by reference:
768/// for item in array.iter().enumerate() {
769///     let (i, x): (usize, &i32) = item;
770///     println!("array[{i}] = {x}");
771/// }
772///
773/// // This iterates by value:
774/// for item in array.into_iter().enumerate() {
775///     let (i, x): (usize, i32) = item;
776///     println!("array[{i}] = {x}");
777/// }
778/// ```
779///
780/// Future language versions might start treating the `array.into_iter()`
781/// syntax on editions 2015 and 2018 the same as on edition 2021. So code using
782/// those older editions should still be written with this change in mind, to
783/// prevent breakage in the future. The safest way to accomplish this is to
784/// avoid the `into_iter` syntax on those editions. If an edition update is not
785/// viable/desired, there are multiple alternatives:
786/// * use `iter`, equivalent to the old behavior, creating references
787/// * use [`IntoIterator::into_iter`], equivalent to the post-2021 behavior (Rust 1.53+)
788/// * replace `for ... in array.into_iter() {` with `for ... in array {`,
789///   equivalent to the post-2021 behavior (Rust 1.53+)
790///
791/// ```rust,edition2018
792/// // Rust 2015 and 2018:
793///
794/// let array: [i32; 3] = [0; 3];
795///
796/// // This iterates by reference:
797/// for item in array.iter() {
798///     let x: &i32 = item;
799///     println!("{x}");
800/// }
801///
802/// // This iterates by value:
803/// for item in IntoIterator::into_iter(array) {
804///     let x: i32 = item;
805///     println!("{x}");
806/// }
807///
808/// // This iterates by value:
809/// for item in array {
810///     let x: i32 = item;
811///     println!("{x}");
812/// }
813///
814/// // IntoIter can also start a chain.
815/// // This iterates by value:
816/// for item in IntoIterator::into_iter(array).enumerate() {
817///     let (i, x): (usize, i32) = item;
818///     println!("array[{i}] = {x}");
819/// }
820/// ```
821///
822/// [slice]: prim@slice
823/// [`Debug`]: fmt::Debug
824/// [`Hash`]: hash::Hash
825/// [`Borrow`]: borrow::Borrow
826/// [`BorrowMut`]: borrow::BorrowMut
827/// [slice pattern]: ../reference/patterns.html#slice-patterns
828/// [`From<Tuple>`]: convert::From
829#[stable(feature = "rust1", since = "1.0.0")]
830mod prim_array {}
831
832#[rustc_doc_primitive = "slice"]
833#[doc(alias = "[")]
834#[doc(alias = "]")]
835#[doc(alias = "[]")]
836/// A dynamically-sized view into a contiguous sequence, `[T]`.
837///
838/// Contiguous here means that elements are laid out so that every element is the same
839/// distance from its neighbors.
840///
841/// *[See also the `std::slice` module](crate::slice).*
842///
843/// Slices are a view into a block of memory represented as a pointer and a
844/// length.
845///
846/// ```
847/// // slicing a Vec
848/// let vec = vec![1, 2, 3];
849/// let int_slice = &vec[..];
850/// // coercing an array to a slice
851/// let str_slice: &[&str] = &["one", "two", "three"];
852/// ```
853///
854/// Slices are either mutable or shared. The shared slice type is `&[T]`,
855/// while the mutable slice type is `&mut [T]`, where `T` represents the element
856/// type. For example, you can mutate the block of memory that a mutable slice
857/// points to:
858///
859/// ```
860/// let mut x = [1, 2, 3];
861/// let x = &mut x[..]; // Take a full slice of `x`.
862/// x[1] = 7;
863/// assert_eq!(x, &[1, 7, 3]);
864/// ```
865///
866/// It is possible to slice empty subranges of slices by using empty ranges (including `slice.len()..slice.len()`):
867/// ```
868/// let x = [1, 2, 3];
869/// let empty = &x[0..0];   // subslice before the first element
870/// assert_eq!(empty, &[]);
871/// let empty = &x[..0];    // same as &x[0..0]
872/// assert_eq!(empty, &[]);
873/// let empty = &x[1..1];   // empty subslice in the middle
874/// assert_eq!(empty, &[]);
875/// let empty = &x[3..3];   // subslice after the last element
876/// assert_eq!(empty, &[]);
877/// let empty = &x[3..];    // same as &x[3..3]
878/// assert_eq!(empty, &[]);
879/// ```
880///
881/// It is not allowed to use subranges that start with lower bound bigger than `slice.len()`:
882/// ```should_panic
883/// let x = vec![1, 2, 3];
884/// let _ = &x[4..4];
885/// ```
886///
887/// As slices store the length of the sequence they refer to, they have twice
888/// the size of pointers to [`Sized`](marker/trait.Sized.html) types.
889/// Also see the reference on
890/// [dynamically sized types](../reference/dynamically-sized-types.html).
891///
892/// ```
893/// # use std::rc::Rc;
894/// let pointer_size = size_of::<&u8>();
895/// assert_eq!(2 * pointer_size, size_of::<&[u8]>());
896/// assert_eq!(2 * pointer_size, size_of::<*const [u8]>());
897/// assert_eq!(2 * pointer_size, size_of::<Box<[u8]>>());
898/// assert_eq!(2 * pointer_size, size_of::<Rc<[u8]>>());
899/// ```
900///
901/// ## Trait Implementations
902///
903/// Some traits are implemented for slices if the element type implements
904/// that trait. This includes [`Eq`], [`Hash`] and [`Ord`].
905///
906/// ## Iteration
907///
908/// The slices implement `IntoIterator`. The iterator yields references to the
909/// slice elements.
910///
911/// ```
912/// let numbers: &[i32] = &[0, 1, 2];
913/// for n in numbers {
914///     println!("{n} is a number!");
915/// }
916/// ```
917///
918/// The mutable slice yields mutable references to the elements:
919///
920/// ```
921/// let mut scores: &mut [i32] = &mut [7, 8, 9];
922/// for score in scores {
923///     *score += 1;
924/// }
925/// ```
926///
927/// This iterator yields mutable references to the slice's elements, so while
928/// the element type of the slice is `i32`, the element type of the iterator is
929/// `&mut i32`.
930///
931/// * [`.iter`] and [`.iter_mut`] are the explicit methods to return the default
932///   iterators.
933/// * Further methods that return iterators are [`.split`], [`.splitn`],
934///   [`.chunks`], [`.windows`] and more.
935///
936/// [`Hash`]: core::hash::Hash
937/// [`.iter`]: slice::iter
938/// [`.iter_mut`]: slice::iter_mut
939/// [`.split`]: slice::split
940/// [`.splitn`]: slice::splitn
941/// [`.chunks`]: slice::chunks
942/// [`.windows`]: slice::windows
943#[stable(feature = "rust1", since = "1.0.0")]
944mod prim_slice {}
945
946#[rustc_doc_primitive = "str"]
947/// String slices.
948///
949/// *[See also the `std::str` module](crate::str).*
950///
951/// The `str` type, also called a 'string slice', is the most primitive string
952/// type. It is usually seen in its borrowed form, `&str`. It is also the type
953/// of string literals, `&'static str`.
954///
955/// # Basic Usage
956///
957/// String literals are string slices:
958///
959/// ```
960/// let hello_world = "Hello, World!";
961/// ```
962///
963/// Here we have declared a string slice initialized with a string literal.
964/// String literals have a static lifetime, which means the string `hello_world`
965/// is guaranteed to be valid for the duration of the entire program.
966/// We can explicitly specify `hello_world`'s lifetime as well:
967///
968/// ```
969/// let hello_world: &'static str = "Hello, world!";
970/// ```
971///
972/// # Representation
973///
974/// A `&str` is made up of two components: a pointer to some bytes, and a
975/// length. You can look at these with the [`as_ptr`] and [`len`] methods:
976///
977/// ```
978/// use std::slice;
979/// use std::str;
980///
981/// let story = "Once upon a time...";
982///
983/// let ptr = story.as_ptr();
984/// let len = story.len();
985///
986/// // story has nineteen bytes
987/// assert_eq!(19, len);
988///
989/// // We can re-build a str out of ptr and len. This is all unsafe because
990/// // we are responsible for making sure the two components are valid:
991/// let s = unsafe {
992///     // First, we build a &[u8]...
993///     let slice = slice::from_raw_parts(ptr, len);
994///
995///     // ... and then convert that slice into a string slice
996///     str::from_utf8(slice)
997/// };
998///
999/// assert_eq!(s, Ok(story));
1000/// ```
1001///
1002/// [`as_ptr`]: str::as_ptr
1003/// [`len`]: str::len
1004///
1005/// Note: This example shows the internals of `&str`. `unsafe` should not be
1006/// used to get a string slice under normal circumstances. Use `as_str`
1007/// instead.
1008///
1009/// # Invariant
1010///
1011/// Rust libraries may assume that string slices are always valid UTF-8.
1012///
1013/// Constructing a non-UTF-8 string slice is not immediate undefined behavior, but any function
1014/// called on a string slice may assume that it is valid UTF-8, which means that a non-UTF-8 string
1015/// slice can lead to undefined behavior down the road.
1016#[stable(feature = "rust1", since = "1.0.0")]
1017mod prim_str {}
1018
1019#[rustc_doc_primitive = "tuple"]
1020#[doc(alias = "(")]
1021#[doc(alias = ")")]
1022#[doc(alias = "()")]
1023//
1024/// A finite heterogeneous sequence, `(T, U, ..)`.
1025///
1026/// Let's cover each of those in turn:
1027///
1028/// Tuples are *finite*. In other words, a tuple has a length. Here's a tuple
1029/// of length `3`:
1030///
1031/// ```
1032/// ("hello", 5, 'c');
1033/// ```
1034///
1035/// 'Length' is also sometimes called 'arity' here; each tuple of a different
1036/// length is a different, distinct type.
1037///
1038/// Tuples are *heterogeneous*. This means that each element of the tuple can
1039/// have a different type. In that tuple above, it has the type:
1040///
1041/// ```
1042/// # let _:
1043/// (&'static str, i32, char)
1044/// # = ("hello", 5, 'c');
1045/// ```
1046///
1047/// Tuples are a *sequence*. This means that they can be accessed by position;
1048/// this is called 'tuple indexing', and it looks like this:
1049///
1050/// ```rust
1051/// let tuple = ("hello", 5, 'c');
1052///
1053/// assert_eq!(tuple.0, "hello");
1054/// assert_eq!(tuple.1, 5);
1055/// assert_eq!(tuple.2, 'c');
1056/// ```
1057///
1058/// The sequential nature of the tuple applies to its implementations of various
1059/// traits. For example, in [`PartialOrd`] and [`Ord`], the elements are compared
1060/// sequentially until the first non-equal set is found.
1061///
1062/// For more about tuples, see [the book](../book/ch03-02-data-types.html#the-tuple-type).
1063///
1064// Hardcoded anchor in src/librustdoc/html/format.rs
1065// linked to as `#trait-implementations-1`
1066/// # Trait implementations
1067///
1068/// In this documentation the shorthand `(T₁, T₂, …, Tₙ)` is used to represent tuples of varying
1069/// length. When that is used, any trait bound expressed on `T` applies to each element of the
1070/// tuple independently. Note that this is a convenience notation to avoid repetitive
1071/// documentation, not valid Rust syntax.
1072///
1073/// Due to a temporary restriction in Rust’s type system, the following traits are only
1074/// implemented on tuples of arity 12 or less. In the future, this may change:
1075///
1076/// * [`PartialEq`]
1077/// * [`Eq`]
1078/// * [`PartialOrd`]
1079/// * [`Ord`]
1080/// * [`Debug`]
1081/// * [`Default`]
1082/// * [`Hash`]
1083/// * [`From<[T; N]>`][from]
1084///
1085/// [from]: convert::From
1086/// [`Debug`]: fmt::Debug
1087/// [`Hash`]: hash::Hash
1088///
1089/// The following traits are implemented for tuples of any length. These traits have
1090/// implementations that are automatically generated by the compiler, so are not limited by
1091/// missing language features.
1092///
1093/// * [`Clone`]
1094/// * [`Copy`]
1095/// * [`Send`]
1096/// * [`Sync`]
1097/// * [`Unpin`]
1098/// * [`UnwindSafe`]
1099/// * [`RefUnwindSafe`]
1100///
1101/// [`UnwindSafe`]: panic::UnwindSafe
1102/// [`RefUnwindSafe`]: panic::RefUnwindSafe
1103///
1104/// # Examples
1105///
1106/// Basic usage:
1107///
1108/// ```
1109/// let tuple = ("hello", 5, 'c');
1110///
1111/// assert_eq!(tuple.0, "hello");
1112/// ```
1113///
1114/// Tuples are often used as a return type when you want to return more than
1115/// one value:
1116///
1117/// ```
1118/// fn calculate_point() -> (i32, i32) {
1119///     // Don't do a calculation, that's not the point of the example
1120///     (4, 5)
1121/// }
1122///
1123/// let point = calculate_point();
1124///
1125/// assert_eq!(point.0, 4);
1126/// assert_eq!(point.1, 5);
1127///
1128/// // Combining this with patterns can be nicer.
1129///
1130/// let (x, y) = calculate_point();
1131///
1132/// assert_eq!(x, 4);
1133/// assert_eq!(y, 5);
1134/// ```
1135///
1136/// Homogeneous tuples can be created from arrays of appropriate length:
1137///
1138/// ```
1139/// let array: [u32; 3] = [1, 2, 3];
1140/// let tuple: (u32, u32, u32) = array.into();
1141/// ```
1142///
1143#[stable(feature = "rust1", since = "1.0.0")]
1144mod prim_tuple {}
1145
1146// Required to make auto trait impls render.
1147// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1148#[doc(hidden)]
1149impl<T> (T,) {}
1150
1151#[rustc_doc_primitive = "f16"]
1152#[doc(alias = "half")]
1153/// A 16-bit floating-point type (specifically, the "binary16" type defined in IEEE 754-2008).
1154///
1155/// This type is very similar to [`prim@f32`] but has decreased precision because it uses half as many
1156/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on half-precision
1157/// values][wikipedia] for more information.
1158///
1159/// Note that most common platforms will not support `f16` in hardware without enabling extra target
1160/// features, with the notable exception of Apple Silicon (also known as M1, M2, etc.) processors.
1161/// Hardware support on x86/x86-64 requires the avx512fp16 or avx10.1 features, while RISC-V requires
1162/// Zfh, and Arm/AArch64 requires FEAT_FP16.  Usually the fallback implementation will be to use `f32`
1163/// hardware if it exists, and convert between `f16` and `f32` when performing math.
1164///
1165/// *[See also the `std::f16::consts` module](crate::f16::consts).*
1166///
1167/// [wikipedia]: https://en.wikipedia.org/wiki/Half-precision_floating-point_format
1168#[unstable(feature = "f16", issue = "116909")]
1169mod prim_f16 {}
1170
1171#[rustc_doc_primitive = "f32"]
1172#[doc(alias = "single")]
1173/// A 32-bit floating-point type (specifically, the "binary32" type defined in IEEE 754-2008).
1174///
1175/// This type can represent a wide range of decimal numbers, like `3.5`, `27`,
1176/// `-113.75`, `0.0078125`, `34359738368`, `0`, `-1`. So unlike integer types
1177/// (such as `i32`), floating-point types can represent non-integer numbers,
1178/// too.
1179///
1180/// However, being able to represent this wide range of numbers comes at the
1181/// cost of precision: floats can only represent some of the real numbers and
1182/// calculation with floats round to a nearby representable number. For example,
1183/// `5.0` and `1.0` can be exactly represented as `f32`, but `1.0 / 5.0` results
1184/// in `0.20000000298023223876953125` since `0.2` cannot be exactly represented
1185/// as `f32`. Note, however, that printing floats with `println` and friends will
1186/// often discard insignificant digits: `println!("{}", 1.0f32 / 5.0f32)` will
1187/// print `0.2`.
1188///
1189/// Additionally, `f32` can represent some special values:
1190///
1191/// - −0.0: IEEE 754 floating-point numbers have a bit that indicates their sign, so −0.0 is a
1192///   possible value. For comparison −0.0 = +0.0, but floating-point operations can carry
1193///   the sign bit through arithmetic operations. This means −0.0 × +0.0 produces −0.0 and
1194///   a negative number rounded to a value smaller than a float can represent also produces −0.0.
1195/// - [∞](#associatedconstant.INFINITY) and
1196///   [−∞](#associatedconstant.NEG_INFINITY): these result from calculations
1197///   like `1.0 / 0.0`.
1198/// - [NaN (not a number)](#associatedconstant.NAN): this value results from
1199///   calculations like `(-1.0).sqrt()`. NaN has some potentially unexpected
1200///   behavior:
1201///   - It is not equal to any float, including itself! This is the reason `f32`
1202///     doesn't implement the `Eq` trait.
1203///   - It is also neither smaller nor greater than any float, making it
1204///     impossible to sort by the default comparison operation, which is the
1205///     reason `f32` doesn't implement the `Ord` trait.
1206///   - It is also considered *infectious* as almost all calculations where one
1207///     of the operands is NaN will also result in NaN. The explanations on this
1208///     page only explicitly document behavior on NaN operands if this default
1209///     is deviated from.
1210///   - Lastly, there are multiple bit patterns that are considered NaN.
1211///     Rust does not currently guarantee that the bit patterns of NaN are
1212///     preserved over arithmetic operations, and they are not guaranteed to be
1213///     portable or even fully deterministic! This means that there may be some
1214///     surprising results upon inspecting the bit patterns,
1215///     as the same calculations might produce NaNs with different bit patterns.
1216///     This also affects the sign of the NaN: checking `is_sign_positive` or `is_sign_negative` on
1217///     a NaN is the most common way to run into these surprising results.
1218///     (Checking `x >= 0.0` or `x <= 0.0` avoids those surprises, but also how negative/positive
1219///     zero are treated.)
1220///     See the section below for what exactly is guaranteed about the bit pattern of a NaN.
1221///
1222/// When a primitive operation (addition, subtraction, multiplication, or
1223/// division) is performed on this type, the result is rounded according to the
1224/// roundTiesToEven direction defined in IEEE 754-2008. That means:
1225///
1226/// - The result is the representable value closest to the true value, if there
1227///   is a unique closest representable value.
1228/// - If the true value is exactly half-way between two representable values,
1229///   the result is the one with an even least-significant binary digit.
1230/// - If the true value's magnitude is ≥ `f32::MAX` + 2<sup>(`f32::MAX_EXP` −
1231///   `f32::MANTISSA_DIGITS` − 1)</sup>, the result is ∞ or −∞ (preserving the
1232///   true value's sign).
1233/// - If the result of a sum exactly equals zero, the outcome is +0.0 unless
1234///   both arguments were negative, then it is -0.0. Subtraction `a - b` is
1235///   regarded as a sum `a + (-b)`.
1236///
1237/// For more information on floating-point numbers, see [Wikipedia][wikipedia].
1238///
1239/// *[See also the `std::f32::consts` module](crate::f32::consts).*
1240///
1241/// [wikipedia]: https://en.wikipedia.org/wiki/Single-precision_floating-point_format
1242///
1243/// # NaN bit patterns
1244///
1245/// This section defines the possible NaN bit patterns returned by floating-point operations.
1246///
1247/// The bit pattern of a floating-point NaN value is defined by:
1248/// - a sign bit.
1249/// - a quiet/signaling bit. Rust assumes that the quiet/signaling bit being set to `1` indicates a
1250///   quiet NaN (QNaN), and a value of `0` indicates a signaling NaN (SNaN). In the following we
1251///   will hence just call it the "quiet bit".
1252/// - a payload, which makes up the rest of the significand (i.e., the mantissa) except for the
1253///   quiet bit.
1254///
1255/// The rules for NaN values differ between *arithmetic* and *non-arithmetic* (or "bitwise")
1256/// operations. The non-arithmetic operations are unary `-`, `abs`, `copysign`, `signum`,
1257/// `{to,from}_bits`, `{to,from}_{be,le,ne}_bytes` and `is_sign_{positive,negative}`. These
1258/// operations are guaranteed to exactly preserve the bit pattern of their input except for possibly
1259/// changing the sign bit.
1260///
1261/// The following rules apply when a NaN value is returned from an arithmetic operation:
1262/// - The result has a non-deterministic sign.
1263/// - The quiet bit and payload are non-deterministically chosen from
1264///   the following set of options:
1265///
1266///   - **Preferred NaN**: The quiet bit is set and the payload is all-zero.
1267///   - **Quieting NaN propagation**: The quiet bit is set and the payload is copied from any input
1268///     operand that is a NaN. If the inputs and outputs do not have the same payload size (i.e., for
1269///     `as` casts), then
1270///     - If the output is smaller than the input, low-order bits of the payload get dropped.
1271///     - If the output is larger than the input, the payload gets filled up with 0s in the low-order
1272///       bits.
1273///   - **Unchanged NaN propagation**: The quiet bit and payload are copied from any input operand
1274///     that is a NaN. If the inputs and outputs do not have the same size (i.e., for `as` casts), the
1275///     same rules as for "quieting NaN propagation" apply, with one caveat: if the output is smaller
1276///     than the input, dropping the low-order bits may result in a payload of 0; a payload of 0 is not
1277///     possible with a signaling NaN (the all-0 significand encodes an infinity) so unchanged NaN
1278///     propagation cannot occur with some inputs.
1279///   - **Target-specific NaN**: The quiet bit is set and the payload is picked from a target-specific
1280///     set of "extra" possible NaN payloads. The set can depend on the input operand values.
1281///     See the table below for the concrete NaNs this set contains on various targets.
1282///
1283/// In particular, if all input NaNs are quiet (or if there are no input NaNs), then the output NaN
1284/// is definitely quiet. Signaling NaN outputs can only occur if they are provided as an input
1285/// value. Similarly, if all input NaNs are preferred (or if there are no input NaNs) and the target
1286/// does not have any "extra" NaN payloads, then the output NaN is guaranteed to be preferred.
1287///
1288/// The non-deterministic choice happens when the operation is executed; i.e., the result of a
1289/// NaN-producing floating-point operation is a stable bit pattern (looking at these bits multiple
1290/// times will yield consistent results), but running the same operation twice with the same inputs
1291/// can produce different results.
1292///
1293/// These guarantees are neither stronger nor weaker than those of IEEE 754: IEEE 754 guarantees
1294/// that an operation never returns a signaling NaN, whereas it is possible for operations like
1295/// `SNAN * 1.0` to return a signaling NaN in Rust. Conversely, IEEE 754 makes no statement at all
1296/// about which quiet NaN is returned, whereas Rust restricts the set of possible results to the
1297/// ones listed above.
1298///
1299/// Unless noted otherwise, the same rules also apply to NaNs returned by other library functions
1300/// (e.g. `min`, `minimum`, `max`, `maximum`); other aspects of their semantics and which IEEE 754
1301/// operation they correspond to are documented with the respective functions.
1302///
1303/// When an arithmetic floating-point operation is executed in `const` context, the same rules
1304/// apply: no guarantee is made about which of the NaN bit patterns described above will be
1305/// returned. The result does not have to match what happens when executing the same code at
1306/// runtime, and the result can vary depending on factors such as compiler version and flags.
1307///
1308/// ### Target-specific "extra" NaN values
1309// FIXME: Is there a better place to put this?
1310///
1311/// | `target_arch` | Extra payloads possible on this platform |
1312/// |---------------|---------|
1313/// | `x86`, `x86_64`, `arm`, `aarch64`, `riscv32`, `riscv64` | None |
1314/// | `sparc`, `sparc64` | The all-one payload |
1315/// | `wasm32`, `wasm64` | If all input NaNs are quiet with all-zero payload: None.<br> Otherwise: all possible payloads. |
1316///
1317/// For targets not in this table, all payloads are possible.
1318
1319#[stable(feature = "rust1", since = "1.0.0")]
1320mod prim_f32 {}
1321
1322#[rustc_doc_primitive = "f64"]
1323#[doc(alias = "double")]
1324/// A 64-bit floating-point type (specifically, the "binary64" type defined in IEEE 754-2008).
1325///
1326/// This type is very similar to [`prim@f32`], but has increased precision by using twice as many
1327/// bits. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on double-precision
1328/// values][wikipedia] for more information.
1329///
1330/// *[See also the `std::f64::consts` module](crate::f64::consts).*
1331///
1332/// [wikipedia]: https://en.wikipedia.org/wiki/Double-precision_floating-point_format
1333#[stable(feature = "rust1", since = "1.0.0")]
1334mod prim_f64 {}
1335
1336#[rustc_doc_primitive = "f128"]
1337#[doc(alias = "quad")]
1338/// A 128-bit floating-point type (specifically, the "binary128" type defined in IEEE 754-2008).
1339///
1340/// This type is very similar to [`prim@f32`] and [`prim@f64`], but has increased precision by using twice
1341/// as many bits as `f64`. Please see [the documentation for `f32`](prim@f32) or [Wikipedia on
1342/// quad-precision values][wikipedia] for more information.
1343///
1344/// Note that no platforms have hardware support for `f128` without enabling target specific features,
1345/// as for all instruction set architectures `f128` is considered an optional feature.  Only Power ISA
1346/// ("PowerPC") and RISC-V (via the Q extension) specify it, and only certain microarchitectures
1347/// actually implement it. For x86-64 and AArch64, ISA support is not even specified, so it will always
1348/// be a software implementation significantly slower than `f64`.
1349///
1350/// _Note: `f128` support is incomplete. Many platforms will not be able to link math functions. On
1351/// x86 in particular, these functions do link but their results are always incorrect._
1352///
1353/// *[See also the `std::f128::consts` module](crate::f128::consts).*
1354///
1355/// [wikipedia]: https://en.wikipedia.org/wiki/Quadruple-precision_floating-point_format
1356#[unstable(feature = "f128", issue = "116909")]
1357mod prim_f128 {}
1358
1359#[rustc_doc_primitive = "i8"]
1360//
1361/// The 8-bit signed integer type.
1362#[stable(feature = "rust1", since = "1.0.0")]
1363mod prim_i8 {}
1364
1365#[rustc_doc_primitive = "i16"]
1366//
1367/// The 16-bit signed integer type.
1368#[stable(feature = "rust1", since = "1.0.0")]
1369mod prim_i16 {}
1370
1371#[rustc_doc_primitive = "i32"]
1372//
1373/// The 32-bit signed integer type.
1374#[stable(feature = "rust1", since = "1.0.0")]
1375mod prim_i32 {}
1376
1377#[rustc_doc_primitive = "i64"]
1378//
1379/// The 64-bit signed integer type.
1380#[stable(feature = "rust1", since = "1.0.0")]
1381mod prim_i64 {}
1382
1383#[rustc_doc_primitive = "i128"]
1384//
1385/// The 128-bit signed integer type.
1386#[stable(feature = "i128", since = "1.26.0")]
1387mod prim_i128 {}
1388
1389#[rustc_doc_primitive = "u8"]
1390//
1391/// The 8-bit unsigned integer type.
1392#[stable(feature = "rust1", since = "1.0.0")]
1393mod prim_u8 {}
1394
1395#[rustc_doc_primitive = "u16"]
1396//
1397/// The 16-bit unsigned integer type.
1398#[stable(feature = "rust1", since = "1.0.0")]
1399mod prim_u16 {}
1400
1401#[rustc_doc_primitive = "u32"]
1402//
1403/// The 32-bit unsigned integer type.
1404#[stable(feature = "rust1", since = "1.0.0")]
1405mod prim_u32 {}
1406
1407#[rustc_doc_primitive = "u64"]
1408//
1409/// The 64-bit unsigned integer type.
1410#[stable(feature = "rust1", since = "1.0.0")]
1411mod prim_u64 {}
1412
1413#[rustc_doc_primitive = "u128"]
1414//
1415/// The 128-bit unsigned integer type.
1416#[stable(feature = "i128", since = "1.26.0")]
1417mod prim_u128 {}
1418
1419#[rustc_doc_primitive = "isize"]
1420//
1421/// The pointer-sized signed integer type.
1422///
1423/// The size of this primitive is how many bytes it takes to reference any
1424/// location in memory. For example, on a 32 bit target, this is 4 bytes
1425/// and on a 64 bit target, this is 8 bytes.
1426#[stable(feature = "rust1", since = "1.0.0")]
1427mod prim_isize {}
1428
1429#[rustc_doc_primitive = "usize"]
1430//
1431/// The pointer-sized unsigned integer type.
1432///
1433/// The size of this primitive is how many bytes it takes to reference any
1434/// location in memory. For example, on a 32 bit target, this is 4 bytes
1435/// and on a 64 bit target, this is 8 bytes.
1436#[stable(feature = "rust1", since = "1.0.0")]
1437mod prim_usize {}
1438
1439#[rustc_doc_primitive = "reference"]
1440#[doc(alias = "&")]
1441#[doc(alias = "&mut")]
1442//
1443/// References, `&T` and `&mut T`.
1444///
1445/// A reference represents a borrow of some owned value. You can get one by using the `&` or `&mut`
1446/// operators on a value, or by using a [`ref`](../std/keyword.ref.html) or
1447/// <code>[ref](../std/keyword.ref.html) [mut](../std/keyword.mut.html)</code> pattern.
1448///
1449/// For those familiar with pointers, a reference is just a pointer that is assumed to be
1450/// aligned, not null, and pointing to memory containing a valid value of `T` - for example,
1451/// <code>&[bool]</code> can only point to an allocation containing the integer values `1`
1452/// ([`true`](../std/keyword.true.html)) or `0` ([`false`](../std/keyword.false.html)), but
1453/// creating a <code>&[bool]</code> that points to an allocation containing
1454/// the value `3` causes undefined behavior.
1455/// In fact, <code>[Option]\<&T></code> has the same memory representation as a
1456/// nullable but aligned pointer, and can be passed across FFI boundaries as such.
1457///
1458/// In most cases, references can be used much like the original value. Field access, method
1459/// calling, and indexing work the same (save for mutability rules, of course). In addition, the
1460/// comparison operators transparently defer to the referent's implementation, allowing references
1461/// to be compared the same as owned values.
1462///
1463/// References have a lifetime attached to them, which represents the scope for which the borrow is
1464/// valid. A lifetime is said to "outlive" another one if its representative scope is as long or
1465/// longer than the other. The `'static` lifetime is the longest lifetime, which represents the
1466/// total life of the program. For example, string literals have a `'static` lifetime because the
1467/// text data is embedded into the binary of the program, rather than in an allocation that needs
1468/// to be dynamically managed.
1469///
1470/// `&mut T` references can be freely coerced into `&T` references with the same referent type, and
1471/// references with longer lifetimes can be freely coerced into references with shorter ones.
1472///
1473/// Reference equality by address, instead of comparing the values pointed to, is accomplished via
1474/// implicit reference-pointer coercion and raw pointer equality via [`ptr::eq`], while
1475/// [`PartialEq`] compares values.
1476///
1477/// ```
1478/// use std::ptr;
1479///
1480/// let five = 5;
1481/// let other_five = 5;
1482/// let five_ref = &five;
1483/// let same_five_ref = &five;
1484/// let other_five_ref = &other_five;
1485///
1486/// assert!(five_ref == same_five_ref);
1487/// assert!(five_ref == other_five_ref);
1488///
1489/// assert!(ptr::eq(five_ref, same_five_ref));
1490/// assert!(!ptr::eq(five_ref, other_five_ref));
1491/// ```
1492///
1493/// For more information on how to use references, see [the book's section on "References and
1494/// Borrowing"][book-refs].
1495///
1496/// [book-refs]: ../book/ch04-02-references-and-borrowing.html
1497///
1498/// # Trait implementations
1499///
1500/// The following traits are implemented for all `&T`, regardless of the type of its referent:
1501///
1502/// * [`Copy`]
1503/// * [`Clone`] \(Note that this will not defer to `T`'s `Clone` implementation if it exists!)
1504/// * [`Deref`]
1505/// * [`Borrow`]
1506/// * [`fmt::Pointer`]
1507///
1508/// [`Deref`]: ops::Deref
1509/// [`Borrow`]: borrow::Borrow
1510///
1511/// `&mut T` references get all of the above except `Copy` and `Clone` (to prevent creating
1512/// multiple simultaneous mutable borrows), plus the following, regardless of the type of its
1513/// referent:
1514///
1515/// * [`DerefMut`]
1516/// * [`BorrowMut`]
1517///
1518/// [`DerefMut`]: ops::DerefMut
1519/// [`BorrowMut`]: borrow::BorrowMut
1520/// [bool]: prim@bool
1521///
1522/// The following traits are implemented on `&T` references if the underlying `T` also implements
1523/// that trait:
1524///
1525/// * All the traits in [`std::fmt`] except [`fmt::Pointer`] (which is implemented regardless of the type of its referent) and [`fmt::Write`]
1526/// * [`PartialOrd`]
1527/// * [`Ord`]
1528/// * [`PartialEq`]
1529/// * [`Eq`]
1530/// * [`AsRef`]
1531/// * [`Fn`] \(in addition, `&T` references get [`FnMut`] and [`FnOnce`] if `T: Fn`)
1532/// * [`Hash`]
1533/// * [`ToSocketAddrs`]
1534/// * [`Sync`]
1535///
1536/// [`std::fmt`]: fmt
1537/// [`Hash`]: hash::Hash
1538/// [`ToSocketAddrs`]: ../std/net/trait.ToSocketAddrs.html
1539///
1540/// `&mut T` references get all of the above except `ToSocketAddrs`, plus the following, if `T`
1541/// implements that trait:
1542///
1543/// * [`AsMut`]
1544/// * [`FnMut`] \(in addition, `&mut T` references get [`FnOnce`] if `T: FnMut`)
1545/// * [`fmt::Write`]
1546/// * [`Iterator`]
1547/// * [`DoubleEndedIterator`]
1548/// * [`ExactSizeIterator`]
1549/// * [`FusedIterator`]
1550/// * [`TrustedLen`]
1551/// * [`Send`]
1552/// * [`io::Write`]
1553/// * [`Read`]
1554/// * [`Seek`]
1555/// * [`BufRead`]
1556///
1557/// [`FusedIterator`]: iter::FusedIterator
1558/// [`TrustedLen`]: iter::TrustedLen
1559/// [`Seek`]: ../std/io/trait.Seek.html
1560/// [`BufRead`]: ../std/io/trait.BufRead.html
1561/// [`Read`]: ../std/io/trait.Read.html
1562/// [`io::Write`]: ../std/io/trait.Write.html
1563///
1564/// In addition, `&T` references implement [`Send`] if and only if `T` implements [`Sync`].
1565///
1566/// Note that due to method call deref coercion, simply calling a trait method will act like they
1567/// work on references as well as they do on owned values! The implementations described here are
1568/// meant for generic contexts, where the final type `T` is a type parameter or otherwise not
1569/// locally known.
1570///
1571/// # Safety
1572///
1573/// For all types, `T: ?Sized`, and for all `t: &T` or `t: &mut T`, when such values cross an API
1574/// boundary, the following invariants must generally be upheld:
1575///
1576/// * `t` is non-null
1577/// * `t` is aligned to `align_of_val(t)`
1578/// * if `size_of_val(t) > 0`, then `t` is dereferenceable for `size_of_val(t)` many bytes
1579///
1580/// If `t` points at address `a`, being "dereferenceable" for N bytes means that the memory range
1581/// `[a, a + N)` is all contained within a single [allocated object].
1582///
1583/// For instance, this means that unsafe code in a safe function may assume these invariants are
1584/// ensured of arguments passed by the caller, and it may assume that these invariants are ensured
1585/// of return values from any safe functions it calls.
1586///
1587/// For the other direction, things are more complicated: when unsafe code passes arguments
1588/// to safe functions or returns values from safe functions, they generally must *at least*
1589/// not violate these invariants. The full requirements are stronger, as the reference generally
1590/// must point to data that is safe to use at type `T`.
1591///
1592/// It is not decided yet whether unsafe code may violate these invariants temporarily on internal
1593/// data. As a consequence, unsafe code which violates these invariants temporarily on internal data
1594/// may be unsound or become unsound in future versions of Rust depending on how this question is
1595/// decided.
1596///
1597/// [allocated object]: ptr#allocated-object
1598#[stable(feature = "rust1", since = "1.0.0")]
1599mod prim_ref {}
1600
1601#[rustc_doc_primitive = "fn"]
1602//
1603/// Function pointers, like `fn(usize) -> bool`.
1604///
1605/// *See also the traits [`Fn`], [`FnMut`], and [`FnOnce`].*
1606///
1607/// Function pointers are pointers that point to *code*, not data. They can be called
1608/// just like functions. Like references, function pointers are, among other things, assumed to
1609/// not be null, so if you want to pass a function pointer over FFI and be able to accommodate null
1610/// pointers, make your type [`Option<fn()>`](core::option#options-and-pointers-nullable-pointers)
1611/// with your required signature.
1612///
1613/// Note that FFI requires additional care to ensure that the ABI for both sides of the call match.
1614/// The exact requirements are not currently documented.
1615///
1616/// ### Safety
1617///
1618/// Plain function pointers are obtained by casting either plain functions, or closures that don't
1619/// capture an environment:
1620///
1621/// ```
1622/// fn add_one(x: usize) -> usize {
1623///     x + 1
1624/// }
1625///
1626/// let ptr: fn(usize) -> usize = add_one;
1627/// assert_eq!(ptr(5), 6);
1628///
1629/// let clos: fn(usize) -> usize = |x| x + 5;
1630/// assert_eq!(clos(5), 10);
1631/// ```
1632///
1633/// In addition to varying based on their signature, function pointers come in two flavors: safe
1634/// and unsafe. Plain `fn()` function pointers can only point to safe functions,
1635/// while `unsafe fn()` function pointers can point to safe or unsafe functions.
1636///
1637/// ```
1638/// fn add_one(x: usize) -> usize {
1639///     x + 1
1640/// }
1641///
1642/// unsafe fn add_one_unsafely(x: usize) -> usize {
1643///     x + 1
1644/// }
1645///
1646/// let safe_ptr: fn(usize) -> usize = add_one;
1647///
1648/// //ERROR: mismatched types: expected normal fn, found unsafe fn
1649/// //let bad_ptr: fn(usize) -> usize = add_one_unsafely;
1650///
1651/// let unsafe_ptr: unsafe fn(usize) -> usize = add_one_unsafely;
1652/// let really_safe_ptr: unsafe fn(usize) -> usize = add_one;
1653/// ```
1654///
1655/// ### ABI
1656///
1657/// On top of that, function pointers can vary based on what ABI they use. This
1658/// is achieved by adding the `extern` keyword before the type, followed by the
1659/// ABI in question. The default ABI is "Rust", i.e., `fn()` is the exact same
1660/// type as `extern "Rust" fn()`. A pointer to a function with C ABI would have
1661/// type `extern "C" fn()`.
1662///
1663/// `extern "ABI" { ... }` blocks declare functions with ABI "ABI". The default
1664/// here is "C", i.e., functions declared in an `extern {...}` block have "C"
1665/// ABI.
1666///
1667/// For more information and a list of supported ABIs, see [the nomicon's
1668/// section on foreign calling conventions][nomicon-abi].
1669///
1670/// [nomicon-abi]: ../nomicon/ffi.html#foreign-calling-conventions
1671///
1672/// ### Variadic functions
1673///
1674/// Extern function declarations with the "C" or "cdecl" ABIs can also be *variadic*, allowing them
1675/// to be called with a variable number of arguments. Normal Rust functions, even those with an
1676/// `extern "ABI"`, cannot be variadic. For more information, see [the nomicon's section on
1677/// variadic functions][nomicon-variadic].
1678///
1679/// [nomicon-variadic]: ../nomicon/ffi.html#variadic-functions
1680///
1681/// ### Creating function pointers
1682///
1683/// When `bar` is the name of a function, then the expression `bar` is *not* a
1684/// function pointer. Rather, it denotes a value of an unnameable type that
1685/// uniquely identifies the function `bar`. The value is zero-sized because the
1686/// type already identifies the function. This has the advantage that "calling"
1687/// the value (it implements the `Fn*` traits) does not require dynamic
1688/// dispatch.
1689///
1690/// This zero-sized type *coerces* to a regular function pointer. For example:
1691///
1692/// ```rust
1693/// fn bar(x: i32) {}
1694///
1695/// let not_bar_ptr = bar; // `not_bar_ptr` is zero-sized, uniquely identifying `bar`
1696/// assert_eq!(size_of_val(&not_bar_ptr), 0);
1697///
1698/// let bar_ptr: fn(i32) = not_bar_ptr; // force coercion to function pointer
1699/// assert_eq!(size_of_val(&bar_ptr), size_of::<usize>());
1700///
1701/// let footgun = &bar; // this is a shared reference to the zero-sized type identifying `bar`
1702/// ```
1703///
1704/// The last line shows that `&bar` is not a function pointer either. Rather, it
1705/// is a reference to the function-specific ZST. `&bar` is basically never what you
1706/// want when `bar` is a function.
1707///
1708/// ### Casting to and from integers
1709///
1710/// You can cast function pointers directly to integers:
1711///
1712/// ```rust
1713/// let fnptr: fn(i32) -> i32 = |x| x+2;
1714/// let fnptr_addr = fnptr as usize;
1715/// ```
1716///
1717/// However, a direct cast back is not possible. You need to use `transmute`:
1718///
1719/// ```rust
1720/// # #[cfg(not(miri))] { // FIXME: use strict provenance APIs once they are stable, then remove this `cfg`
1721/// # let fnptr: fn(i32) -> i32 = |x| x+2;
1722/// # let fnptr_addr = fnptr as usize;
1723/// let fnptr = fnptr_addr as *const ();
1724/// let fnptr: fn(i32) -> i32 = unsafe { std::mem::transmute(fnptr) };
1725/// assert_eq!(fnptr(40), 42);
1726/// # }
1727/// ```
1728///
1729/// Crucially, we `as`-cast to a raw pointer before `transmute`ing to a function pointer.
1730/// This avoids an integer-to-pointer `transmute`, which can be problematic.
1731/// Transmuting between raw pointers and function pointers (i.e., two pointer types) is fine.
1732///
1733/// Note that all of this is not portable to platforms where function pointers and data pointers
1734/// have different sizes.
1735///
1736/// ### ABI compatibility
1737///
1738/// Generally, when a function is declared with one signature and called via a function pointer with
1739/// a different signature, the two signatures must be *ABI-compatible* or else calling the function
1740/// via that function pointer is Undefined Behavior. ABI compatibility is a lot stricter than merely
1741/// having the same memory layout; for example, even if `i32` and `f32` have the same size and
1742/// alignment, they might be passed in different registers and hence not be ABI-compatible.
1743///
1744/// ABI compatibility as a concern only arises in code that alters the type of function pointers,
1745/// and code that imports functions via `extern` blocks. Altering the type of function pointers is
1746/// wildly unsafe (as in, a lot more unsafe than even [`transmute_copy`][mem::transmute_copy]), and
1747/// should only occur in the most exceptional circumstances. Most Rust code just imports functions
1748/// via `use`. So, most likely you do not have to worry about ABI compatibility.
1749///
1750/// But assuming such circumstances, what are the rules? For this section, we are only considering
1751/// the ABI of direct Rust-to-Rust calls (with both definition and callsite visible to the
1752/// Rust compiler), not linking in general -- once functions are imported via `extern` blocks, there
1753/// are more things to consider that we do not go into here. Note that this also applies to
1754/// passing/calling functions across language boundaries via function pointers.
1755///
1756/// **Nothing in this section should be taken as a guarantee for non-Rust-to-Rust calls, even with
1757/// types from `core::ffi` or `libc`**.
1758///
1759/// For two signatures to be considered *ABI-compatible*, they must use a compatible ABI string,
1760/// must take the same number of arguments, and the individual argument types and the return types
1761/// must be ABI-compatible. The ABI string is declared via `extern "ABI" fn(...) -> ...`; note that
1762/// `fn name(...) -> ...` implicitly uses the `"Rust"` ABI string and `extern fn name(...) -> ...`
1763/// implicitly uses the `"C"` ABI string.
1764///
1765/// The ABI strings are guaranteed to be compatible if they are the same, or if the caller ABI
1766/// string is `$X-unwind` and the callee ABI string is `$X`, where `$X` is one of the following:
1767/// "C", "aapcs", "fastcall", "stdcall", "system", "sysv64", "thiscall", "vectorcall", "win64".
1768///
1769/// The following types are guaranteed to be ABI-compatible:
1770///
1771/// - `*const T`, `*mut T`, `&T`, `&mut T`, `Box<T>` (specifically, only `Box<T, Global>`), and
1772///   `NonNull<T>` are all ABI-compatible with each other for all `T`. They are also ABI-compatible
1773///   with each other for _different_ `T` if they have the same metadata type (`<T as
1774///   Pointee>::Metadata`).
1775/// - `usize` is ABI-compatible with the `uN` integer type of the same size, and likewise `isize` is
1776///   ABI-compatible with the `iN` integer type of the same size.
1777/// - `char` is ABI-compatible with `u32`.
1778/// - Any two `fn` (function pointer) types are ABI-compatible with each other if they have the same
1779///   ABI string or the ABI string only differs in a trailing `-unwind`, independent of the rest of
1780///   their signature. (This means you can pass `fn()` to a function expecting `fn(i32)`, and the
1781///   call will be valid ABI-wise. The callee receives the result of transmuting the function pointer
1782///   from `fn()` to `fn(i32)`; that transmutation is itself a well-defined operation, it's just
1783///   almost certainly UB to later call that function pointer.)
1784/// - Any two types with size 0 and alignment 1 are ABI-compatible.
1785/// - A `repr(transparent)` type `T` is ABI-compatible with its unique non-trivial field, i.e., the
1786///   unique field that doesn't have size 0 and alignment 1 (if there is such a field).
1787/// - `i32` is ABI-compatible with `NonZero<i32>`, and similar for all other integer types.
1788/// - If `T` is guaranteed to be subject to the [null pointer
1789///   optimization](option/index.html#representation), and `E` is an enum satisfying the following
1790///   requirements, then `T` and `E` are ABI-compatible. Such an enum `E` is called "option-like".
1791///   - The enum `E` has exactly two variants.
1792///   - One variant has exactly one field, of type `T`.
1793///   - All fields of the other variant are zero-sized with 1-byte alignment.
1794///
1795/// Furthermore, ABI compatibility satisfies the following general properties:
1796///
1797/// - Every type is ABI-compatible with itself.
1798/// - If `T1` and `T2` are ABI-compatible and `T2` and `T3` are ABI-compatible, then so are `T1` and
1799///   `T3` (i.e., ABI-compatibility is transitive).
1800/// - If `T1` and `T2` are ABI-compatible, then so are `T2` and `T1` (i.e., ABI-compatibility is
1801///   symmetric).
1802///
1803/// More signatures can be ABI-compatible on specific targets, but that should not be relied upon
1804/// since it is not portable and not a stable guarantee.
1805///
1806/// Noteworthy cases of types *not* being ABI-compatible in general are:
1807/// * `bool` vs `u8`, `i32` vs `u32`, `char` vs `i32`: on some targets, the calling conventions for
1808///   these types differ in terms of what they guarantee for the remaining bits in the register that
1809///   are not used by the value.
1810/// * `i32` vs `f32` are not compatible either, as has already been mentioned above.
1811/// * `struct Foo(u32)` and `u32` are not compatible (without `repr(transparent)`) since structs are
1812///   aggregate types and often passed in a different way than primitives like `i32`.
1813///
1814/// Note that these rules describe when two completely known types are ABI-compatible. When
1815/// considering ABI compatibility of a type declared in another crate (including the standard
1816/// library), consider that any type that has a private field or the `#[non_exhaustive]` attribute
1817/// may change its layout as a non-breaking update unless documented otherwise -- so for instance,
1818/// even if such a type is a 1-ZST or `repr(transparent)` right now, this might change with any
1819/// library version bump.
1820///
1821/// If the declared signature and the signature of the function pointer are ABI-compatible, then the
1822/// function call behaves as if every argument was [`transmute`d][mem::transmute] from the
1823/// type in the function pointer to the type at the function declaration, and the return value is
1824/// [`transmute`d][mem::transmute] from the type in the declaration to the type in the
1825/// pointer. All the usual caveats and concerns around transmutation apply; for instance, if the
1826/// function expects a `NonZero<i32>` and the function pointer uses the ABI-compatible type
1827/// `Option<NonZero<i32>>`, and the value used for the argument is `None`, then this call is Undefined
1828/// Behavior since transmuting `None::<NonZero<i32>>` to `NonZero<i32>` violates the non-zero
1829/// requirement.
1830///
1831/// ### Trait implementations
1832///
1833/// In this documentation the shorthand `fn(T₁, T₂, …, Tₙ)` is used to represent non-variadic
1834/// function pointers of varying length. Note that this is a convenience notation to avoid
1835/// repetitive documentation, not valid Rust syntax.
1836///
1837/// The following traits are implemented for function pointers with any number of arguments and
1838/// any ABI.
1839///
1840/// * [`PartialEq`]
1841/// * [`Eq`]
1842/// * [`PartialOrd`]
1843/// * [`Ord`]
1844/// * [`Hash`]
1845/// * [`Pointer`]
1846/// * [`Debug`]
1847/// * [`Clone`]
1848/// * [`Copy`]
1849/// * [`Send`]
1850/// * [`Sync`]
1851/// * [`Unpin`]
1852/// * [`UnwindSafe`]
1853/// * [`RefUnwindSafe`]
1854///
1855/// Note that while this type implements `PartialEq`, comparing function pointers is unreliable:
1856/// pointers to the same function can compare inequal (because functions are duplicated in multiple
1857/// codegen units), and pointers to *different* functions can compare equal (since identical
1858/// functions can be deduplicated within a codegen unit).
1859///
1860/// [`Hash`]: hash::Hash
1861/// [`Pointer`]: fmt::Pointer
1862/// [`UnwindSafe`]: panic::UnwindSafe
1863/// [`RefUnwindSafe`]: panic::RefUnwindSafe
1864///
1865/// In addition, all *safe* function pointers implement [`Fn`], [`FnMut`], and [`FnOnce`], because
1866/// these traits are specially known to the compiler.
1867#[stable(feature = "rust1", since = "1.0.0")]
1868mod prim_fn {}
1869
1870// Required to make auto trait impls render.
1871// See src/librustdoc/passes/collect_trait_impls.rs:collect_trait_impls
1872#[doc(hidden)]
1873impl<Ret, T> fn(T) -> Ret {}