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