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