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