From f442797c17f8f1f6ff217d48e664018359bdd6bc Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Fri, 6 Dec 2019 13:56:25 +0100 Subject: Make `core::convert` a directory-module with `mod.rs` --- src/libcore/convert.rs | 660 --------------------------------------------- src/libcore/convert/mod.rs | 660 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 660 insertions(+), 660 deletions(-) delete mode 100644 src/libcore/convert.rs create mode 100644 src/libcore/convert/mod.rs (limited to 'src/libcore') diff --git a/src/libcore/convert.rs b/src/libcore/convert.rs deleted file mode 100644 index 08802b3a97a..00000000000 --- a/src/libcore/convert.rs +++ /dev/null @@ -1,660 +0,0 @@ -//! Traits for conversions between types. -//! -//! The traits in this module provide a way to convert from one type to another type. -//! Each trait serves a different purpose: -//! -//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions -//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions -//! - Implement the [`From`] trait for consuming value-to-value conversions -//! - Implement the [`Into`] trait for consuming value-to-value conversions to types -//! outside the current crate -//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], -//! but should be implemented when the conversion can fail. -//! -//! The traits in this module are often used as trait bounds for generic functions such that to -//! arguments of multiple types are supported. See the documentation of each trait for examples. -//! -//! As a library author, you should always prefer implementing [`From`][`From`] or -//! [`TryFrom`][`TryFrom`] rather than [`Into`][`Into`] or [`TryInto`][`TryInto`], -//! as [`From`] and [`TryFrom`] provide greater flexibility and offer -//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a -//! blanket implementation in the standard library. Only implement [`Into`] or [`TryInto`] -//! when a conversion to a type outside the current crate is required. -//! -//! # Generic Implementations -//! -//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference -//! - [`From`]` for T` implies [`Into`]` for U` -//! - [`TryFrom`]` for T` implies [`TryInto`]` for U` -//! - [`From`] and [`Into`] are reflexive, which means that all types can -//! `into` themselves and `from` themselves -//! -//! See each trait for usage examples. -//! -//! [`Into`]: trait.Into.html -//! [`From`]: trait.From.html -//! [`TryFrom`]: trait.TryFrom.html -//! [`TryInto`]: trait.TryInto.html -//! [`AsRef`]: trait.AsRef.html -//! [`AsMut`]: trait.AsMut.html - -#![stable(feature = "rust1", since = "1.0.0")] - -/// The identity function. -/// -/// Two things are important to note about this function: -/// -/// - It is not always equivalent to a closure like `|x| x`, since the -/// closure may coerce `x` into a different type. -/// -/// - It moves the input `x` passed to the function. -/// -/// While it might seem strange to have a function that just returns back the -/// input, there are some interesting uses. -/// -/// # Examples -/// -/// Using `identity` to do nothing in a sequence of other, interesting, -/// functions: -/// -/// ```rust -/// use std::convert::identity; -/// -/// fn manipulation(x: u32) -> u32 { -/// // Let's pretend that adding one is an interesting function. -/// x + 1 -/// } -/// -/// let _arr = &[identity, manipulation]; -/// ``` -/// -/// Using `identity` as a "do nothing" base case in a conditional: -/// -/// ```rust -/// use std::convert::identity; -/// -/// # let condition = true; -/// # -/// # fn manipulation(x: u32) -> u32 { x + 1 } -/// # -/// let do_stuff = if condition { manipulation } else { identity }; -/// -/// // Do more interesting stuff... -/// -/// let _results = do_stuff(42); -/// ``` -/// -/// Using `identity` to keep the `Some` variants of an iterator of `Option`: -/// -/// ```rust -/// use std::convert::identity; -/// -/// let iter = vec![Some(1), None, Some(3)].into_iter(); -/// let filtered = iter.filter_map(identity).collect::>(); -/// assert_eq!(vec![1, 3], filtered); -/// ``` -#[stable(feature = "convert_id", since = "1.33.0")] -#[inline] -pub const fn identity(x: T) -> T { - x -} - -/// Used to do a cheap reference-to-reference conversion. -/// -/// This trait is similar to [`AsMut`] which is used for converting between mutable references. -/// If you need to do a costly conversion it is better to implement [`From`] with type -/// `&T` or write a custom function. -/// -/// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in few aspects: -/// -/// - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either -/// a reference or a value. -/// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for borrowed value are -/// equivalent to those of the owned value. For this reason, if you want to -/// borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`]. -/// -/// **Note: This trait must not fail**. If the conversion can fail, use a -/// dedicated method which returns an [`Option`] or a [`Result`]. -/// -/// # Generic Implementations -/// -/// - `AsRef` auto-dereferences if the inner type is a reference or a mutable -/// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type -/// `&mut Foo` or `&&mut Foo`) -/// -/// # Examples -/// -/// By using trait bounds we can accept arguments of different types as long as they can be -/// converted to the specified type `T`. -/// -/// For example: By creating a generic function that takes an `AsRef` we express that we -/// want to accept all references that can be converted to [`&str`] as an argument. -/// Since both [`String`] and [`&str`] implement `AsRef` we can accept both as input argument. -/// -/// [`Option`]: ../../std/option/enum.Option.html -/// [`Result`]: ../../std/result/enum.Result.html -/// [`Borrow`]: ../../std/borrow/trait.Borrow.html -/// [`Hash`]: ../../std/hash/trait.Hash.html -/// [`Eq`]: ../../std/cmp/trait.Eq.html -/// [`Ord`]: ../../std/cmp/trait.Ord.html -/// [`&str`]: ../../std/primitive.str.html -/// [`String`]: ../../std/string/struct.String.html -/// -/// ``` -/// fn is_hello>(s: T) { -/// assert_eq!("hello", s.as_ref()); -/// } -/// -/// let s = "hello"; -/// is_hello(s); -/// -/// let s = "hello".to_string(); -/// is_hello(s); -/// ``` -#[stable(feature = "rust1", since = "1.0.0")] -pub trait AsRef { - /// Performs the conversion. - #[stable(feature = "rust1", since = "1.0.0")] - fn as_ref(&self) -> &T; -} - -/// Used to do a cheap mutable-to-mutable reference conversion. -/// -/// This trait is similar to [`AsRef`] but used for converting between mutable -/// references. If you need to do a costly conversion it is better to -/// implement [`From`] with type `&mut T` or write a custom function. -/// -/// **Note: This trait must not fail**. If the conversion can fail, use a -/// dedicated method which returns an [`Option`] or a [`Result`]. -/// -/// [`Option`]: ../../std/option/enum.Option.html -/// [`Result`]: ../../std/result/enum.Result.html -/// -/// # Generic Implementations -/// -/// - `AsMut` auto-dereferences if the inner type is a mutable reference -/// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` -/// or `&mut &mut Foo`) -/// -/// # Examples -/// -/// Using `AsMut` as trait bound for a generic function we can accept all mutable references -/// that can be converted to type `&mut T`. Because [`Box`] implements `AsMut` we can -/// write a function `add_one` that takes all arguments that can be converted to `&mut u64`. -/// Because [`Box`] implements `AsMut`, `add_one` accepts arguments of type -/// `&mut Box` as well: -/// -/// ``` -/// fn add_one>(num: &mut T) { -/// *num.as_mut() += 1; -/// } -/// -/// let mut boxed_num = Box::new(0); -/// add_one(&mut boxed_num); -/// assert_eq!(*boxed_num, 1); -/// ``` -/// -/// [`Box`]: ../../std/boxed/struct.Box.html -#[stable(feature = "rust1", since = "1.0.0")] -pub trait AsMut { - /// Performs the conversion. - #[stable(feature = "rust1", since = "1.0.0")] - fn as_mut(&mut self) -> &mut T; -} - -/// A value-to-value conversion that consumes the input value. The -/// opposite of [`From`]. -/// -/// One should avoid implementing [`Into`] and implement [`From`] instead. -/// Implementing [`From`] automatically provides one with an implementation of [`Into`] -/// thanks to the blanket implementation in the standard library. -/// -/// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function -/// to ensure that types that only implement [`Into`] can be used as well. -/// -/// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. -/// -/// # Generic Implementations -/// -/// - [`From`]` for U` implies `Into for T` -/// - [`Into`] is reflexive, which means that `Into for T` is implemented -/// -/// # Implementing [`Into`] for conversions to external types in old versions of Rust -/// -/// Prior to Rust 1.40, if the destination type was not part of the current crate -/// then you couldn't implement [`From`] directly. -/// For example, take this code: -/// -/// ``` -/// struct Wrapper(Vec); -/// impl From> for Vec { -/// fn from(w: Wrapper) -> Vec { -/// w.0 -/// } -/// } -/// ``` -/// This will fail to compile in older versions of the language because Rust's orphaning rules -/// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly: -/// -/// ``` -/// struct Wrapper(Vec); -/// impl Into> for Wrapper { -/// fn into(self) -> Vec { -/// self.0 -/// } -/// } -/// ``` -/// -/// It is important to understand that [`Into`] does not provide a [`From`] implementation -/// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`] -/// and then fall back to [`Into`] if [`From`] can't be implemented. -/// -/// # Examples -/// -/// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`: -/// -/// In order to express that we want a generic function to take all arguments that can be -/// converted to a specified type `T`, we can use a trait bound of [`Into`]``. -/// For example: The function `is_hello` takes all arguments that can be converted into a -/// [`Vec`]`<`[`u8`]`>`. -/// -/// ``` -/// fn is_hello>>(s: T) { -/// let bytes = b"hello".to_vec(); -/// assert_eq!(bytes, s.into()); -/// } -/// -/// let s = "hello".to_string(); -/// is_hello(s); -/// ``` -/// -/// [`TryInto`]: trait.TryInto.html -/// [`Option`]: ../../std/option/enum.Option.html -/// [`Result`]: ../../std/result/enum.Result.html -/// [`String`]: ../../std/string/struct.String.html -/// [`From`]: trait.From.html -/// [`Into`]: trait.Into.html -/// [`Vec`]: ../../std/vec/struct.Vec.html -#[stable(feature = "rust1", since = "1.0.0")] -pub trait Into: Sized { - /// Performs the conversion. - #[stable(feature = "rust1", since = "1.0.0")] - fn into(self) -> T; -} - -/// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of -/// [`Into`]. -/// -/// One should always prefer implementing `From` over [`Into`] -/// because implementing `From` automatically provides one with a implementation of [`Into`] -/// thanks to the blanket implementation in the standard library. -/// -/// Only implement [`Into`] if a conversion to a type outside the current crate is required. -/// `From` cannot do these type of conversions because of Rust's orphaning rules. -/// See [`Into`] for more details. -/// -/// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function. -/// This way, types that directly implement [`Into`] can be used as arguments as well. -/// -/// The `From` is also very useful when performing error handling. When constructing a function -/// that is capable of failing, the return type will generally be of the form `Result`. -/// The `From` trait simplifies error handling by allowing a function to return a single error type -/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more -/// details. -/// -/// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. -/// -/// # Generic Implementations -/// -/// - `From for U` implies [`Into`]` for T` -/// - `From` is reflexive, which means that `From for T` is implemented -/// -/// # Examples -/// -/// [`String`] implements `From<&str>`: -/// -/// An explicit conversion from a `&str` to a String is done as follows: -/// -/// ``` -/// let string = "hello".to_string(); -/// let other_string = String::from("hello"); -/// -/// assert_eq!(string, other_string); -/// ``` -/// -/// While performing error handling it is often useful to implement `From` for your own error type. -/// By converting underlying error types to our own custom error type that encapsulates the -/// underlying error type, we can return a single error type without losing information on the -/// underlying cause. The '?' operator automatically converts the underlying error type to our -/// custom error type by calling `Into::into` which is automatically provided when -/// implementing `From`. The compiler then infers which implementation of `Into` should be used. -/// -/// ``` -/// use std::fs; -/// use std::io; -/// use std::num; -/// -/// enum CliError { -/// IoError(io::Error), -/// ParseError(num::ParseIntError), -/// } -/// -/// impl From for CliError { -/// fn from(error: io::Error) -> Self { -/// CliError::IoError(error) -/// } -/// } -/// -/// impl From for CliError { -/// fn from(error: num::ParseIntError) -> Self { -/// CliError::ParseError(error) -/// } -/// } -/// -/// fn open_and_parse_file(file_name: &str) -> Result { -/// let mut contents = fs::read_to_string(&file_name)?; -/// let num: i32 = contents.trim().parse()?; -/// Ok(num) -/// } -/// ``` -/// -/// [`TryFrom`]: trait.TryFrom.html -/// [`Option`]: ../../std/option/enum.Option.html -/// [`Result`]: ../../std/result/enum.Result.html -/// [`String`]: ../../std/string/struct.String.html -/// [`Into`]: trait.Into.html -/// [`from`]: trait.From.html#tymethod.from -/// [book]: ../../book/ch09-00-error-handling.html -#[stable(feature = "rust1", since = "1.0.0")] -#[rustc_on_unimplemented(on( - all(_Self = "&str", T = "std::string::String"), - note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix", -))] -pub trait From: Sized { - /// Performs the conversion. - #[stable(feature = "rust1", since = "1.0.0")] - fn from(_: T) -> Self; -} - -/// An attempted conversion that consumes `self`, which may or may not be -/// expensive. -/// -/// Library authors should usually not directly implement this trait, -/// but should prefer implementing the [`TryFrom`] trait, which offers -/// greater flexibility and provides an equivalent `TryInto` -/// implementation for free, thanks to a blanket implementation in the -/// standard library. For more information on this, see the -/// documentation for [`Into`]. -/// -/// # Implementing `TryInto` -/// -/// This suffers the same restrictions and reasoning as implementing -/// [`Into`], see there for details. -/// -/// [`TryFrom`]: trait.TryFrom.html -/// [`Into`]: trait.Into.html -#[stable(feature = "try_from", since = "1.34.0")] -pub trait TryInto: Sized { - /// The type returned in the event of a conversion error. - #[stable(feature = "try_from", since = "1.34.0")] - type Error; - - /// Performs the conversion. - #[stable(feature = "try_from", since = "1.34.0")] - fn try_into(self) -> Result; -} - -/// Simple and safe type conversions that may fail in a controlled -/// way under some circumstances. It is the reciprocal of [`TryInto`]. -/// -/// This is useful when you are doing a type conversion that may -/// trivially succeed but may also need special handling. -/// For example, there is no way to convert an [`i64`] into an [`i32`] -/// using the [`From`] trait, because an [`i64`] may contain a value -/// that an [`i32`] cannot represent and so the conversion would lose data. -/// This might be handled by truncating the [`i64`] to an [`i32`] (essentially -/// giving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning -/// [`i32::MAX`], or by some other method. The [`From`] trait is intended -/// for perfect conversions, so the `TryFrom` trait informs the -/// programmer when a type conversion could go bad and lets them -/// decide how to handle it. -/// -/// # Generic Implementations -/// -/// - `TryFrom for U` implies [`TryInto`]` for T` -/// - [`try_from`] is reflexive, which means that `TryFrom for T` -/// is implemented and cannot fail -- the associated `Error` type for -/// calling `T::try_from()` on a value of type `T` is [`!`]. -/// -/// `TryFrom` can be implemented as follows: -/// -/// ``` -/// use std::convert::TryFrom; -/// -/// struct GreaterThanZero(i32); -/// -/// impl TryFrom for GreaterThanZero { -/// type Error = &'static str; -/// -/// fn try_from(value: i32) -> Result { -/// if value <= 0 { -/// Err("GreaterThanZero only accepts value superior than zero!") -/// } else { -/// Ok(GreaterThanZero(value)) -/// } -/// } -/// } -/// ``` -/// -/// # Examples -/// -/// As described, [`i32`] implements `TryFrom<`[`i64`]`>`: -/// -/// ``` -/// use std::convert::TryFrom; -/// -/// let big_number = 1_000_000_000_000i64; -/// // Silently truncates `big_number`, requires detecting -/// // and handling the truncation after the fact. -/// let smaller_number = big_number as i32; -/// assert_eq!(smaller_number, -727379968); -/// -/// // Returns an error because `big_number` is too big to -/// // fit in an `i32`. -/// let try_smaller_number = i32::try_from(big_number); -/// assert!(try_smaller_number.is_err()); -/// -/// // Returns `Ok(3)`. -/// let try_successful_smaller_number = i32::try_from(3); -/// assert!(try_successful_smaller_number.is_ok()); -/// ``` -/// -/// [`try_from`]: trait.TryFrom.html#tymethod.try_from -/// [`TryInto`]: trait.TryInto.html -/// [`i32::MAX`]: ../../std/i32/constant.MAX.html -/// [`!`]: ../../std/primitive.never.html -#[stable(feature = "try_from", since = "1.34.0")] -pub trait TryFrom: Sized { - /// The type returned in the event of a conversion error. - #[stable(feature = "try_from", since = "1.34.0")] - type Error; - - /// Performs the conversion. - #[stable(feature = "try_from", since = "1.34.0")] - fn try_from(value: T) -> Result; -} - -//////////////////////////////////////////////////////////////////////////////// -// GENERIC IMPLS -//////////////////////////////////////////////////////////////////////////////// - -// As lifts over & -#[stable(feature = "rust1", since = "1.0.0")] -impl AsRef for &T -where - T: AsRef, -{ - fn as_ref(&self) -> &U { - >::as_ref(*self) - } -} - -// As lifts over &mut -#[stable(feature = "rust1", since = "1.0.0")] -impl AsRef for &mut T -where - T: AsRef, -{ - fn as_ref(&self) -> &U { - >::as_ref(*self) - } -} - -// FIXME (#45742): replace the above impls for &/&mut with the following more general one: -// // As lifts over Deref -// impl>, U: ?Sized> AsRef for D { -// fn as_ref(&self) -> &U { -// self.deref().as_ref() -// } -// } - -// AsMut lifts over &mut -#[stable(feature = "rust1", since = "1.0.0")] -impl AsMut for &mut T -where - T: AsMut, -{ - fn as_mut(&mut self) -> &mut U { - (*self).as_mut() - } -} - -// FIXME (#45742): replace the above impl for &mut with the following more general one: -// // AsMut lifts over DerefMut -// impl>, U: ?Sized> AsMut for D { -// fn as_mut(&mut self) -> &mut U { -// self.deref_mut().as_mut() -// } -// } - -// From implies Into -#[stable(feature = "rust1", since = "1.0.0")] -impl Into for T -where - U: From, -{ - fn into(self) -> U { - U::from(self) - } -} - -// From (and thus Into) is reflexive -#[stable(feature = "rust1", since = "1.0.0")] -impl From for T { - fn from(t: T) -> T { - t - } -} - -/// **Stability note:** This impl does not yet exist, but we are -/// "reserving space" to add it in the future. See -/// [rust-lang/rust#64715][#64715] for details. -/// -/// [#64715]: https://github.com/rust-lang/rust/issues/64715 -#[stable(feature = "convert_infallible", since = "1.34.0")] -#[rustc_reservation_impl = "permitting this impl would forbid us from adding \ - `impl From for T` later; see rust-lang/rust#64715 for details"] -impl From for T { - fn from(t: !) -> T { - t - } -} - -// TryFrom implies TryInto -#[stable(feature = "try_from", since = "1.34.0")] -impl TryInto for T -where - U: TryFrom, -{ - type Error = U::Error; - - fn try_into(self) -> Result { - U::try_from(self) - } -} - -// Infallible conversions are semantically equivalent to fallible conversions -// with an uninhabited error type. -#[stable(feature = "try_from", since = "1.34.0")] -impl TryFrom for T -where - U: Into, -{ - type Error = Infallible; - - fn try_from(value: U) -> Result { - Ok(U::into(value)) - } -} - -//////////////////////////////////////////////////////////////////////////////// -// CONCRETE IMPLS -//////////////////////////////////////////////////////////////////////////////// - -#[stable(feature = "rust1", since = "1.0.0")] -impl AsRef<[T]> for [T] { - fn as_ref(&self) -> &[T] { - self - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl AsMut<[T]> for [T] { - fn as_mut(&mut self) -> &mut [T] { - self - } -} - -#[stable(feature = "rust1", since = "1.0.0")] -impl AsRef for str { - #[inline] - fn as_ref(&self) -> &str { - self - } -} - -//////////////////////////////////////////////////////////////////////////////// -// THE NO-ERROR ERROR TYPE -//////////////////////////////////////////////////////////////////////////////// - -/// A type alias for [the `!` “never” type][never]. -/// -/// `Infallible` represents types of errors that can never happen since `!` has no valid values. -/// This can be useful for generic APIs that use [`Result`] and parameterize the error type, -/// to indicate that the result is always [`Ok`]. -/// -/// For example, the [`TryFrom`] trait (conversion that returns a [`Result`]) -/// has a blanket implementation for all types where a reverse [`Into`] implementation exists. -/// -/// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error) -/// impl TryFrom for T where U: Into { -/// type Error = Infallible; -/// -/// fn try_from(value: U) -> Result { -/// Ok(U::into(value)) // Never returns `Err` -/// } -/// } -/// ``` -/// -/// # Eventual deprecation -/// -/// Previously, `Infallible` was defined as `enum Infallible {}`. -/// Now that it is merely a type alias to `!`, we will eventually deprecate `Infallible`. -/// -/// [`Ok`]: ../result/enum.Result.html#variant.Ok -/// [`Result`]: ../result/enum.Result.html -/// [`TryFrom`]: trait.TryFrom.html -/// [`Into`]: trait.Into.html -/// [never]: ../../std/primitive.never.html -#[stable(feature = "convert_infallible", since = "1.34.0")] -pub type Infallible = !; diff --git a/src/libcore/convert/mod.rs b/src/libcore/convert/mod.rs new file mode 100644 index 00000000000..08802b3a97a --- /dev/null +++ b/src/libcore/convert/mod.rs @@ -0,0 +1,660 @@ +//! Traits for conversions between types. +//! +//! The traits in this module provide a way to convert from one type to another type. +//! Each trait serves a different purpose: +//! +//! - Implement the [`AsRef`] trait for cheap reference-to-reference conversions +//! - Implement the [`AsMut`] trait for cheap mutable-to-mutable conversions +//! - Implement the [`From`] trait for consuming value-to-value conversions +//! - Implement the [`Into`] trait for consuming value-to-value conversions to types +//! outside the current crate +//! - The [`TryFrom`] and [`TryInto`] traits behave like [`From`] and [`Into`], +//! but should be implemented when the conversion can fail. +//! +//! The traits in this module are often used as trait bounds for generic functions such that to +//! arguments of multiple types are supported. See the documentation of each trait for examples. +//! +//! As a library author, you should always prefer implementing [`From`][`From`] or +//! [`TryFrom`][`TryFrom`] rather than [`Into`][`Into`] or [`TryInto`][`TryInto`], +//! as [`From`] and [`TryFrom`] provide greater flexibility and offer +//! equivalent [`Into`] or [`TryInto`] implementations for free, thanks to a +//! blanket implementation in the standard library. Only implement [`Into`] or [`TryInto`] +//! when a conversion to a type outside the current crate is required. +//! +//! # Generic Implementations +//! +//! - [`AsRef`] and [`AsMut`] auto-dereference if the inner type is a reference +//! - [`From`]` for T` implies [`Into`]` for U` +//! - [`TryFrom`]` for T` implies [`TryInto`]` for U` +//! - [`From`] and [`Into`] are reflexive, which means that all types can +//! `into` themselves and `from` themselves +//! +//! See each trait for usage examples. +//! +//! [`Into`]: trait.Into.html +//! [`From`]: trait.From.html +//! [`TryFrom`]: trait.TryFrom.html +//! [`TryInto`]: trait.TryInto.html +//! [`AsRef`]: trait.AsRef.html +//! [`AsMut`]: trait.AsMut.html + +#![stable(feature = "rust1", since = "1.0.0")] + +/// The identity function. +/// +/// Two things are important to note about this function: +/// +/// - It is not always equivalent to a closure like `|x| x`, since the +/// closure may coerce `x` into a different type. +/// +/// - It moves the input `x` passed to the function. +/// +/// While it might seem strange to have a function that just returns back the +/// input, there are some interesting uses. +/// +/// # Examples +/// +/// Using `identity` to do nothing in a sequence of other, interesting, +/// functions: +/// +/// ```rust +/// use std::convert::identity; +/// +/// fn manipulation(x: u32) -> u32 { +/// // Let's pretend that adding one is an interesting function. +/// x + 1 +/// } +/// +/// let _arr = &[identity, manipulation]; +/// ``` +/// +/// Using `identity` as a "do nothing" base case in a conditional: +/// +/// ```rust +/// use std::convert::identity; +/// +/// # let condition = true; +/// # +/// # fn manipulation(x: u32) -> u32 { x + 1 } +/// # +/// let do_stuff = if condition { manipulation } else { identity }; +/// +/// // Do more interesting stuff... +/// +/// let _results = do_stuff(42); +/// ``` +/// +/// Using `identity` to keep the `Some` variants of an iterator of `Option`: +/// +/// ```rust +/// use std::convert::identity; +/// +/// let iter = vec![Some(1), None, Some(3)].into_iter(); +/// let filtered = iter.filter_map(identity).collect::>(); +/// assert_eq!(vec![1, 3], filtered); +/// ``` +#[stable(feature = "convert_id", since = "1.33.0")] +#[inline] +pub const fn identity(x: T) -> T { + x +} + +/// Used to do a cheap reference-to-reference conversion. +/// +/// This trait is similar to [`AsMut`] which is used for converting between mutable references. +/// If you need to do a costly conversion it is better to implement [`From`] with type +/// `&T` or write a custom function. +/// +/// `AsRef` has the same signature as [`Borrow`], but [`Borrow`] is different in few aspects: +/// +/// - Unlike `AsRef`, [`Borrow`] has a blanket impl for any `T`, and can be used to accept either +/// a reference or a value. +/// - [`Borrow`] also requires that [`Hash`], [`Eq`] and [`Ord`] for borrowed value are +/// equivalent to those of the owned value. For this reason, if you want to +/// borrow only a single field of a struct you can implement `AsRef`, but not [`Borrow`]. +/// +/// **Note: This trait must not fail**. If the conversion can fail, use a +/// dedicated method which returns an [`Option`] or a [`Result`]. +/// +/// # Generic Implementations +/// +/// - `AsRef` auto-dereferences if the inner type is a reference or a mutable +/// reference (e.g.: `foo.as_ref()` will work the same if `foo` has type +/// `&mut Foo` or `&&mut Foo`) +/// +/// # Examples +/// +/// By using trait bounds we can accept arguments of different types as long as they can be +/// converted to the specified type `T`. +/// +/// For example: By creating a generic function that takes an `AsRef` we express that we +/// want to accept all references that can be converted to [`&str`] as an argument. +/// Since both [`String`] and [`&str`] implement `AsRef` we can accept both as input argument. +/// +/// [`Option`]: ../../std/option/enum.Option.html +/// [`Result`]: ../../std/result/enum.Result.html +/// [`Borrow`]: ../../std/borrow/trait.Borrow.html +/// [`Hash`]: ../../std/hash/trait.Hash.html +/// [`Eq`]: ../../std/cmp/trait.Eq.html +/// [`Ord`]: ../../std/cmp/trait.Ord.html +/// [`&str`]: ../../std/primitive.str.html +/// [`String`]: ../../std/string/struct.String.html +/// +/// ``` +/// fn is_hello>(s: T) { +/// assert_eq!("hello", s.as_ref()); +/// } +/// +/// let s = "hello"; +/// is_hello(s); +/// +/// let s = "hello".to_string(); +/// is_hello(s); +/// ``` +#[stable(feature = "rust1", since = "1.0.0")] +pub trait AsRef { + /// Performs the conversion. + #[stable(feature = "rust1", since = "1.0.0")] + fn as_ref(&self) -> &T; +} + +/// Used to do a cheap mutable-to-mutable reference conversion. +/// +/// This trait is similar to [`AsRef`] but used for converting between mutable +/// references. If you need to do a costly conversion it is better to +/// implement [`From`] with type `&mut T` or write a custom function. +/// +/// **Note: This trait must not fail**. If the conversion can fail, use a +/// dedicated method which returns an [`Option`] or a [`Result`]. +/// +/// [`Option`]: ../../std/option/enum.Option.html +/// [`Result`]: ../../std/result/enum.Result.html +/// +/// # Generic Implementations +/// +/// - `AsMut` auto-dereferences if the inner type is a mutable reference +/// (e.g.: `foo.as_mut()` will work the same if `foo` has type `&mut Foo` +/// or `&mut &mut Foo`) +/// +/// # Examples +/// +/// Using `AsMut` as trait bound for a generic function we can accept all mutable references +/// that can be converted to type `&mut T`. Because [`Box`] implements `AsMut` we can +/// write a function `add_one` that takes all arguments that can be converted to `&mut u64`. +/// Because [`Box`] implements `AsMut`, `add_one` accepts arguments of type +/// `&mut Box` as well: +/// +/// ``` +/// fn add_one>(num: &mut T) { +/// *num.as_mut() += 1; +/// } +/// +/// let mut boxed_num = Box::new(0); +/// add_one(&mut boxed_num); +/// assert_eq!(*boxed_num, 1); +/// ``` +/// +/// [`Box`]: ../../std/boxed/struct.Box.html +#[stable(feature = "rust1", since = "1.0.0")] +pub trait AsMut { + /// Performs the conversion. + #[stable(feature = "rust1", since = "1.0.0")] + fn as_mut(&mut self) -> &mut T; +} + +/// A value-to-value conversion that consumes the input value. The +/// opposite of [`From`]. +/// +/// One should avoid implementing [`Into`] and implement [`From`] instead. +/// Implementing [`From`] automatically provides one with an implementation of [`Into`] +/// thanks to the blanket implementation in the standard library. +/// +/// Prefer using [`Into`] over [`From`] when specifying trait bounds on a generic function +/// to ensure that types that only implement [`Into`] can be used as well. +/// +/// **Note: This trait must not fail**. If the conversion can fail, use [`TryInto`]. +/// +/// # Generic Implementations +/// +/// - [`From`]` for U` implies `Into for T` +/// - [`Into`] is reflexive, which means that `Into for T` is implemented +/// +/// # Implementing [`Into`] for conversions to external types in old versions of Rust +/// +/// Prior to Rust 1.40, if the destination type was not part of the current crate +/// then you couldn't implement [`From`] directly. +/// For example, take this code: +/// +/// ``` +/// struct Wrapper(Vec); +/// impl From> for Vec { +/// fn from(w: Wrapper) -> Vec { +/// w.0 +/// } +/// } +/// ``` +/// This will fail to compile in older versions of the language because Rust's orphaning rules +/// used to be a little bit more strict. To bypass this, you could implement [`Into`] directly: +/// +/// ``` +/// struct Wrapper(Vec); +/// impl Into> for Wrapper { +/// fn into(self) -> Vec { +/// self.0 +/// } +/// } +/// ``` +/// +/// It is important to understand that [`Into`] does not provide a [`From`] implementation +/// (as [`From`] does with [`Into`]). Therefore, you should always try to implement [`From`] +/// and then fall back to [`Into`] if [`From`] can't be implemented. +/// +/// # Examples +/// +/// [`String`] implements [`Into`]`<`[`Vec`]`<`[`u8`]`>>`: +/// +/// In order to express that we want a generic function to take all arguments that can be +/// converted to a specified type `T`, we can use a trait bound of [`Into`]``. +/// For example: The function `is_hello` takes all arguments that can be converted into a +/// [`Vec`]`<`[`u8`]`>`. +/// +/// ``` +/// fn is_hello>>(s: T) { +/// let bytes = b"hello".to_vec(); +/// assert_eq!(bytes, s.into()); +/// } +/// +/// let s = "hello".to_string(); +/// is_hello(s); +/// ``` +/// +/// [`TryInto`]: trait.TryInto.html +/// [`Option`]: ../../std/option/enum.Option.html +/// [`Result`]: ../../std/result/enum.Result.html +/// [`String`]: ../../std/string/struct.String.html +/// [`From`]: trait.From.html +/// [`Into`]: trait.Into.html +/// [`Vec`]: ../../std/vec/struct.Vec.html +#[stable(feature = "rust1", since = "1.0.0")] +pub trait Into: Sized { + /// Performs the conversion. + #[stable(feature = "rust1", since = "1.0.0")] + fn into(self) -> T; +} + +/// Used to do value-to-value conversions while consuming the input value. It is the reciprocal of +/// [`Into`]. +/// +/// One should always prefer implementing `From` over [`Into`] +/// because implementing `From` automatically provides one with a implementation of [`Into`] +/// thanks to the blanket implementation in the standard library. +/// +/// Only implement [`Into`] if a conversion to a type outside the current crate is required. +/// `From` cannot do these type of conversions because of Rust's orphaning rules. +/// See [`Into`] for more details. +/// +/// Prefer using [`Into`] over using `From` when specifying trait bounds on a generic function. +/// This way, types that directly implement [`Into`] can be used as arguments as well. +/// +/// The `From` is also very useful when performing error handling. When constructing a function +/// that is capable of failing, the return type will generally be of the form `Result`. +/// The `From` trait simplifies error handling by allowing a function to return a single error type +/// that encapsulate multiple error types. See the "Examples" section and [the book][book] for more +/// details. +/// +/// **Note: This trait must not fail**. If the conversion can fail, use [`TryFrom`]. +/// +/// # Generic Implementations +/// +/// - `From for U` implies [`Into`]` for T` +/// - `From` is reflexive, which means that `From for T` is implemented +/// +/// # Examples +/// +/// [`String`] implements `From<&str>`: +/// +/// An explicit conversion from a `&str` to a String is done as follows: +/// +/// ``` +/// let string = "hello".to_string(); +/// let other_string = String::from("hello"); +/// +/// assert_eq!(string, other_string); +/// ``` +/// +/// While performing error handling it is often useful to implement `From` for your own error type. +/// By converting underlying error types to our own custom error type that encapsulates the +/// underlying error type, we can return a single error type without losing information on the +/// underlying cause. The '?' operator automatically converts the underlying error type to our +/// custom error type by calling `Into::into` which is automatically provided when +/// implementing `From`. The compiler then infers which implementation of `Into` should be used. +/// +/// ``` +/// use std::fs; +/// use std::io; +/// use std::num; +/// +/// enum CliError { +/// IoError(io::Error), +/// ParseError(num::ParseIntError), +/// } +/// +/// impl From for CliError { +/// fn from(error: io::Error) -> Self { +/// CliError::IoError(error) +/// } +/// } +/// +/// impl From for CliError { +/// fn from(error: num::ParseIntError) -> Self { +/// CliError::ParseError(error) +/// } +/// } +/// +/// fn open_and_parse_file(file_name: &str) -> Result { +/// let mut contents = fs::read_to_string(&file_name)?; +/// let num: i32 = contents.trim().parse()?; +/// Ok(num) +/// } +/// ``` +/// +/// [`TryFrom`]: trait.TryFrom.html +/// [`Option`]: ../../std/option/enum.Option.html +/// [`Result`]: ../../std/result/enum.Result.html +/// [`String`]: ../../std/string/struct.String.html +/// [`Into`]: trait.Into.html +/// [`from`]: trait.From.html#tymethod.from +/// [book]: ../../book/ch09-00-error-handling.html +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_on_unimplemented(on( + all(_Self = "&str", T = "std::string::String"), + note = "to coerce a `{T}` into a `{Self}`, use `&*` as a prefix", +))] +pub trait From: Sized { + /// Performs the conversion. + #[stable(feature = "rust1", since = "1.0.0")] + fn from(_: T) -> Self; +} + +/// An attempted conversion that consumes `self`, which may or may not be +/// expensive. +/// +/// Library authors should usually not directly implement this trait, +/// but should prefer implementing the [`TryFrom`] trait, which offers +/// greater flexibility and provides an equivalent `TryInto` +/// implementation for free, thanks to a blanket implementation in the +/// standard library. For more information on this, see the +/// documentation for [`Into`]. +/// +/// # Implementing `TryInto` +/// +/// This suffers the same restrictions and reasoning as implementing +/// [`Into`], see there for details. +/// +/// [`TryFrom`]: trait.TryFrom.html +/// [`Into`]: trait.Into.html +#[stable(feature = "try_from", since = "1.34.0")] +pub trait TryInto: Sized { + /// The type returned in the event of a conversion error. + #[stable(feature = "try_from", since = "1.34.0")] + type Error; + + /// Performs the conversion. + #[stable(feature = "try_from", since = "1.34.0")] + fn try_into(self) -> Result; +} + +/// Simple and safe type conversions that may fail in a controlled +/// way under some circumstances. It is the reciprocal of [`TryInto`]. +/// +/// This is useful when you are doing a type conversion that may +/// trivially succeed but may also need special handling. +/// For example, there is no way to convert an [`i64`] into an [`i32`] +/// using the [`From`] trait, because an [`i64`] may contain a value +/// that an [`i32`] cannot represent and so the conversion would lose data. +/// This might be handled by truncating the [`i64`] to an [`i32`] (essentially +/// giving the [`i64`]'s value modulo [`i32::MAX`]) or by simply returning +/// [`i32::MAX`], or by some other method. The [`From`] trait is intended +/// for perfect conversions, so the `TryFrom` trait informs the +/// programmer when a type conversion could go bad and lets them +/// decide how to handle it. +/// +/// # Generic Implementations +/// +/// - `TryFrom for U` implies [`TryInto`]` for T` +/// - [`try_from`] is reflexive, which means that `TryFrom for T` +/// is implemented and cannot fail -- the associated `Error` type for +/// calling `T::try_from()` on a value of type `T` is [`!`]. +/// +/// `TryFrom` can be implemented as follows: +/// +/// ``` +/// use std::convert::TryFrom; +/// +/// struct GreaterThanZero(i32); +/// +/// impl TryFrom for GreaterThanZero { +/// type Error = &'static str; +/// +/// fn try_from(value: i32) -> Result { +/// if value <= 0 { +/// Err("GreaterThanZero only accepts value superior than zero!") +/// } else { +/// Ok(GreaterThanZero(value)) +/// } +/// } +/// } +/// ``` +/// +/// # Examples +/// +/// As described, [`i32`] implements `TryFrom<`[`i64`]`>`: +/// +/// ``` +/// use std::convert::TryFrom; +/// +/// let big_number = 1_000_000_000_000i64; +/// // Silently truncates `big_number`, requires detecting +/// // and handling the truncation after the fact. +/// let smaller_number = big_number as i32; +/// assert_eq!(smaller_number, -727379968); +/// +/// // Returns an error because `big_number` is too big to +/// // fit in an `i32`. +/// let try_smaller_number = i32::try_from(big_number); +/// assert!(try_smaller_number.is_err()); +/// +/// // Returns `Ok(3)`. +/// let try_successful_smaller_number = i32::try_from(3); +/// assert!(try_successful_smaller_number.is_ok()); +/// ``` +/// +/// [`try_from`]: trait.TryFrom.html#tymethod.try_from +/// [`TryInto`]: trait.TryInto.html +/// [`i32::MAX`]: ../../std/i32/constant.MAX.html +/// [`!`]: ../../std/primitive.never.html +#[stable(feature = "try_from", since = "1.34.0")] +pub trait TryFrom: Sized { + /// The type returned in the event of a conversion error. + #[stable(feature = "try_from", since = "1.34.0")] + type Error; + + /// Performs the conversion. + #[stable(feature = "try_from", since = "1.34.0")] + fn try_from(value: T) -> Result; +} + +//////////////////////////////////////////////////////////////////////////////// +// GENERIC IMPLS +//////////////////////////////////////////////////////////////////////////////// + +// As lifts over & +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for &T +where + T: AsRef, +{ + fn as_ref(&self) -> &U { + >::as_ref(*self) + } +} + +// As lifts over &mut +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for &mut T +where + T: AsRef, +{ + fn as_ref(&self) -> &U { + >::as_ref(*self) + } +} + +// FIXME (#45742): replace the above impls for &/&mut with the following more general one: +// // As lifts over Deref +// impl>, U: ?Sized> AsRef for D { +// fn as_ref(&self) -> &U { +// self.deref().as_ref() +// } +// } + +// AsMut lifts over &mut +#[stable(feature = "rust1", since = "1.0.0")] +impl AsMut for &mut T +where + T: AsMut, +{ + fn as_mut(&mut self) -> &mut U { + (*self).as_mut() + } +} + +// FIXME (#45742): replace the above impl for &mut with the following more general one: +// // AsMut lifts over DerefMut +// impl>, U: ?Sized> AsMut for D { +// fn as_mut(&mut self) -> &mut U { +// self.deref_mut().as_mut() +// } +// } + +// From implies Into +#[stable(feature = "rust1", since = "1.0.0")] +impl Into for T +where + U: From, +{ + fn into(self) -> U { + U::from(self) + } +} + +// From (and thus Into) is reflexive +#[stable(feature = "rust1", since = "1.0.0")] +impl From for T { + fn from(t: T) -> T { + t + } +} + +/// **Stability note:** This impl does not yet exist, but we are +/// "reserving space" to add it in the future. See +/// [rust-lang/rust#64715][#64715] for details. +/// +/// [#64715]: https://github.com/rust-lang/rust/issues/64715 +#[stable(feature = "convert_infallible", since = "1.34.0")] +#[rustc_reservation_impl = "permitting this impl would forbid us from adding \ + `impl From for T` later; see rust-lang/rust#64715 for details"] +impl From for T { + fn from(t: !) -> T { + t + } +} + +// TryFrom implies TryInto +#[stable(feature = "try_from", since = "1.34.0")] +impl TryInto for T +where + U: TryFrom, +{ + type Error = U::Error; + + fn try_into(self) -> Result { + U::try_from(self) + } +} + +// Infallible conversions are semantically equivalent to fallible conversions +// with an uninhabited error type. +#[stable(feature = "try_from", since = "1.34.0")] +impl TryFrom for T +where + U: Into, +{ + type Error = Infallible; + + fn try_from(value: U) -> Result { + Ok(U::into(value)) + } +} + +//////////////////////////////////////////////////////////////////////////////// +// CONCRETE IMPLS +//////////////////////////////////////////////////////////////////////////////// + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef<[T]> for [T] { + fn as_ref(&self) -> &[T] { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsMut<[T]> for [T] { + fn as_mut(&mut self) -> &mut [T] { + self + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl AsRef for str { + #[inline] + fn as_ref(&self) -> &str { + self + } +} + +//////////////////////////////////////////////////////////////////////////////// +// THE NO-ERROR ERROR TYPE +//////////////////////////////////////////////////////////////////////////////// + +/// A type alias for [the `!` “never” type][never]. +/// +/// `Infallible` represents types of errors that can never happen since `!` has no valid values. +/// This can be useful for generic APIs that use [`Result`] and parameterize the error type, +/// to indicate that the result is always [`Ok`]. +/// +/// For example, the [`TryFrom`] trait (conversion that returns a [`Result`]) +/// has a blanket implementation for all types where a reverse [`Into`] implementation exists. +/// +/// ```ignore (illustrates std code, duplicating the impl in a doctest would be an error) +/// impl TryFrom for T where U: Into { +/// type Error = Infallible; +/// +/// fn try_from(value: U) -> Result { +/// Ok(U::into(value)) // Never returns `Err` +/// } +/// } +/// ``` +/// +/// # Eventual deprecation +/// +/// Previously, `Infallible` was defined as `enum Infallible {}`. +/// Now that it is merely a type alias to `!`, we will eventually deprecate `Infallible`. +/// +/// [`Ok`]: ../result/enum.Result.html#variant.Ok +/// [`Result`]: ../result/enum.Result.html +/// [`TryFrom`]: trait.TryFrom.html +/// [`Into`]: trait.Into.html +/// [never]: ../../std/primitive.never.html +#[stable(feature = "convert_infallible", since = "1.34.0")] +pub type Infallible = !; -- cgit 1.4.1-3-g733a5 From cba479f75c7513f91f727741882a99442f393c12 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Thu, 28 Nov 2019 15:24:26 +0100 Subject: Add `{f32,f64}::approx_unchecked_to` unsafe methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As discussed in https://github.com/rust-lang/rust/issues/10184 Currently, casting a floating point number to an integer with `as` is Undefined Behavior if the value is out of range. `-Z saturating-float-casts` fixes this soundness hole by making `as` “saturate” to the maximum or minimum value of the integer type (or zero for `NaN`), but has measurable negative performance impact in some benchmarks. There is some consensus in that thread for enabling saturation by default anyway, but provide an `unsafe fn` alternative for users who know through some other mean that their values are in range. --- src/libcore/convert/mod.rs | 5 +++++ src/libcore/convert/num.rs | 38 ++++++++++++++++++++++++++++++++++ src/libcore/intrinsics.rs | 5 +++++ src/libcore/num/f32.rs | 32 +++++++++++++++++++++++++++- src/libcore/num/f64.rs | 32 +++++++++++++++++++++++++++- src/librustc_codegen_llvm/intrinsic.rs | 29 +++++++++++++++++++++++++- src/librustc_typeck/check/intrinsic.rs | 1 + 7 files changed, 139 insertions(+), 3 deletions(-) create mode 100644 src/libcore/convert/num.rs (limited to 'src/libcore') diff --git a/src/libcore/convert/mod.rs b/src/libcore/convert/mod.rs index 08802b3a97a..16d5375059f 100644 --- a/src/libcore/convert/mod.rs +++ b/src/libcore/convert/mod.rs @@ -40,6 +40,11 @@ #![stable(feature = "rust1", since = "1.0.0")] +mod num; + +#[unstable(feature = "convert_float_to_int", issue = "67057")] +pub use num::FloatToInt; + /// The identity function. /// /// Two things are important to note about this function: diff --git a/src/libcore/convert/num.rs b/src/libcore/convert/num.rs new file mode 100644 index 00000000000..076a1107479 --- /dev/null +++ b/src/libcore/convert/num.rs @@ -0,0 +1,38 @@ +mod private { + /// This trait being unreachable from outside the crate + /// prevents other implementations of the `FloatToInt` trait, + /// which allows potentially adding more trait methods after the trait is `#[stable]`. + #[unstable(feature = "convert_float_to_int", issue = "67057")] + pub trait Sealed {} +} + +/// Supporting trait for inherent methods of `f32` and `f64` such as `round_unchecked_to`. +/// Typically doesn’t need to be used directly. +#[unstable(feature = "convert_float_to_int", issue = "67057")] +pub trait FloatToInt: private::Sealed + Sized { + #[cfg(not(bootstrap))] + #[unstable(feature = "float_approx_unchecked_to", issue = "67058")] + #[doc(hidden)] + unsafe fn approx_unchecked(self) -> Int; +} + +macro_rules! impl_float_to_int { + ( $Float: ident => $( $Int: ident )+ ) => { + #[unstable(feature = "convert_float_to_int", issue = "67057")] + impl private::Sealed for $Float {} + $( + #[unstable(feature = "convert_float_to_int", issue = "67057")] + impl FloatToInt<$Int> for $Float { + #[cfg(not(bootstrap))] + #[doc(hidden)] + #[inline] + unsafe fn approx_unchecked(self) -> $Int { + crate::intrinsics::float_to_int_approx_unchecked(self) + } + } + )+ + } +} + +impl_float_to_int!(f32 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); +impl_float_to_int!(f64 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); diff --git a/src/libcore/intrinsics.rs b/src/libcore/intrinsics.rs index 19928f30f2e..18aae59573d 100644 --- a/src/libcore/intrinsics.rs +++ b/src/libcore/intrinsics.rs @@ -1144,6 +1144,11 @@ extern "rust-intrinsic" { /// May assume inputs are finite. pub fn frem_fast(a: T, b: T) -> T; + /// Convert with LLVM’s fptoui/fptosi, which may return undef for values out of range + /// https://github.com/rust-lang/rust/issues/10184 + #[cfg(not(bootstrap))] + pub fn float_to_int_approx_unchecked(value: Float) -> Int; + /// Returns the number of bits set in an integer type `T` pub fn ctpop(x: T) -> T; diff --git a/src/libcore/num/f32.rs b/src/libcore/num/f32.rs index 913c0f96d11..ac06f95e244 100644 --- a/src/libcore/num/f32.rs +++ b/src/libcore/num/f32.rs @@ -7,9 +7,10 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[cfg(not(bootstrap))] +use crate::convert::FloatToInt; #[cfg(not(test))] use crate::intrinsics; - use crate::mem; use crate::num::FpCategory; @@ -400,6 +401,35 @@ impl f32 { intrinsics::minnumf32(self, other) } + /// Rounds toward zero and converts to any primitive integer type, + /// assuming that the value is finite and fits in that type. + /// + /// ``` + /// #![feature(float_approx_unchecked_to)] + /// + /// let value = 4.6_f32; + /// let rounded = unsafe { value.approx_unchecked_to::() }; + /// assert_eq!(rounded, 4); + /// + /// let value = -128.9_f32; + /// let rounded = unsafe { value.approx_unchecked_to::() }; + /// assert_eq!(rounded, std::i8::MIN); + /// ``` + /// + /// # Safety + /// + /// The value must: + /// + /// * Not be `NaN` + /// * Not be infinite + /// * Be representable in the return type `Int`, after truncating off its fractional part + #[cfg(not(bootstrap))] + #[unstable(feature = "float_approx_unchecked_to", issue = "67058")] + #[inline] + pub unsafe fn approx_unchecked_to(self) -> Int where Self: FloatToInt { + FloatToInt::::approx_unchecked(self) + } + /// Raw transmutation to `u32`. /// /// This is currently identical to `transmute::(self)` on all platforms. diff --git a/src/libcore/num/f64.rs b/src/libcore/num/f64.rs index 6ca830b1f38..794f77fcfc1 100644 --- a/src/libcore/num/f64.rs +++ b/src/libcore/num/f64.rs @@ -7,9 +7,10 @@ #![stable(feature = "rust1", since = "1.0.0")] +#[cfg(not(bootstrap))] +use crate::convert::FloatToInt; #[cfg(not(test))] use crate::intrinsics; - use crate::mem; use crate::num::FpCategory; @@ -413,6 +414,35 @@ impl f64 { intrinsics::minnumf64(self, other) } + /// Rounds toward zero and converts to any primitive integer type, + /// assuming that the value is finite and fits in that type. + /// + /// ``` + /// #![feature(float_approx_unchecked_to)] + /// + /// let value = 4.6_f32; + /// let rounded = unsafe { value.approx_unchecked_to::() }; + /// assert_eq!(rounded, 4); + /// + /// let value = -128.9_f32; + /// let rounded = unsafe { value.approx_unchecked_to::() }; + /// assert_eq!(rounded, std::i8::MIN); + /// ``` + /// + /// # Safety + /// + /// The value must: + /// + /// * Not be `NaN` + /// * Not be infinite + /// * Be representable in the return type `Int`, after truncating off its fractional part + #[cfg(not(bootstrap))] + #[unstable(feature = "float_approx_unchecked_to", issue = "67058")] + #[inline] + pub unsafe fn approx_unchecked_to(self) -> Int where Self: FloatToInt { + FloatToInt::::approx_unchecked(self) + } + /// Raw transmutation to `u64`. /// /// This is currently identical to `transmute::(self)` on all platforms. diff --git a/src/librustc_codegen_llvm/intrinsic.rs b/src/librustc_codegen_llvm/intrinsic.rs index 9df75a800f1..1767ad118e7 100644 --- a/src/librustc_codegen_llvm/intrinsic.rs +++ b/src/librustc_codegen_llvm/intrinsic.rs @@ -516,9 +516,36 @@ impl IntrinsicCallMethods<'tcx> for Builder<'a, 'll, 'tcx> { return; } } - }, + "float_to_int_approx_unchecked" => { + if float_type_width(arg_tys[0]).is_none() { + span_invalid_monomorphization_error( + tcx.sess, span, + &format!("invalid monomorphization of `float_to_int_approx_unchecked` \ + intrinsic: expected basic float type, \ + found `{}`", arg_tys[0])); + return; + } + match int_type_width_signed(ret_ty, self.cx) { + Some((width, signed)) => { + if signed { + self.fptosi(args[0].immediate(), self.cx.type_ix(width)) + } else { + self.fptoui(args[0].immediate(), self.cx.type_ix(width)) + } + } + None => { + span_invalid_monomorphization_error( + tcx.sess, span, + &format!("invalid monomorphization of `float_to_int_approx_unchecked` \ + intrinsic: expected basic integer type, \ + found `{}`", ret_ty)); + return; + } + } + } + "discriminant_value" => { args[0].deref(self.cx()).codegen_get_discr(self, ret_ty) } diff --git a/src/librustc_typeck/check/intrinsic.rs b/src/librustc_typeck/check/intrinsic.rs index 9f034e65b6e..b967c6e36e3 100644 --- a/src/librustc_typeck/check/intrinsic.rs +++ b/src/librustc_typeck/check/intrinsic.rs @@ -336,6 +336,7 @@ pub fn check_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem) { (1, vec![param(0), param(0)], param(0)), "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => (1, vec![param(0), param(0)], param(0)), + "float_to_int_approx_unchecked" => (2, vec![ param(0) ], param(1)), "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()), "likely" => (0, vec![tcx.types.bool], tcx.types.bool), -- cgit 1.4.1-3-g733a5 From a213ff82998ef91fa793883c2f2ebbc574967500 Mon Sep 17 00:00:00 2001 From: Simon Sapin Date: Mon, 2 Dec 2019 09:44:48 +0100 Subject: Move numeric `From` and `TryFrom` impls to `libcore/convert/num.rs` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This makes `libcore/num/mod.rs` slightly smaller. It’s still 4911 lines and not easy to navigate. This doesn’t change any public API. --- src/libcore/convert/num.rs | 331 +++++++++++++++++++++++++++++++++++++++++++++ src/libcore/num/mod.rs | 331 +-------------------------------------------- 2 files changed, 332 insertions(+), 330 deletions(-) (limited to 'src/libcore') diff --git a/src/libcore/convert/num.rs b/src/libcore/convert/num.rs index 076a1107479..0877dacb38d 100644 --- a/src/libcore/convert/num.rs +++ b/src/libcore/convert/num.rs @@ -1,3 +1,6 @@ +use super::{From, TryFrom}; +use crate::num::TryFromIntError; + mod private { /// This trait being unreachable from outside the crate /// prevents other implementations of the `FloatToInt` trait, @@ -36,3 +39,331 @@ macro_rules! impl_float_to_int { impl_float_to_int!(f32 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); impl_float_to_int!(f64 => u8 u16 u32 u64 u128 usize i8 i16 i32 i64 i128 isize); + +// Conversion traits for primitive integer and float types +// Conversions T -> T are covered by a blanket impl and therefore excluded +// Some conversions from and to usize/isize are not implemented due to portability concerns +macro_rules! impl_from { + ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => { + #[$attr] + #[doc = $doc] + impl From<$Small> for $Large { + #[inline] + fn from(small: $Small) -> $Large { + small as $Large + } + } + }; + ($Small: ty, $Large: ty, #[$attr:meta]) => { + impl_from!($Small, + $Large, + #[$attr], + concat!("Converts `", + stringify!($Small), + "` to `", + stringify!($Large), + "` losslessly.")); + } +} + +macro_rules! impl_from_bool { + ($target: ty, #[$attr:meta]) => { + impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `", + stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true` +values. + +# Examples + +``` +assert_eq!(", stringify!($target), "::from(true), 1); +assert_eq!(", stringify!($target), "::from(false), 0); +```")); + }; +} + +// Bool -> Any +impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] } +impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] } + +// Unsigned -> Unsigned +impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] } + +// Signed -> Signed +impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] } + +// Unsigned -> Signed +impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } +impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] } +impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] } + +// The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX +// which imply that pointer-sized integers must be at least 16 bits: +// https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4 +impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } +impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } +impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } + +// RISC-V defines the possibility of a 128-bit address space (RV128). + +// CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize. +// https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf +// http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf + + +// Note: integers can only be represented with full precision in a float if +// they fit in the significand, which is 24 bits in f32 and 53 bits in f64. +// Lossy float conversions are not implemented at this time. + +// Signed -> Float +impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } + +// Unsigned -> Float +impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } +impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } + +// Float -> Float +impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } + +// no possible bounds violation +macro_rules! try_from_unbounded { + ($source:ty, $($target:ty),*) => {$( + #[stable(feature = "try_from", since = "1.34.0")] + impl TryFrom<$source> for $target { + type Error = TryFromIntError; + + /// Try to create the target number type from a source + /// number type. This returns an error if the source value + /// is outside of the range of the target type. + #[inline] + fn try_from(value: $source) -> Result { + Ok(value as $target) + } + } + )*} +} + +// only negative bounds +macro_rules! try_from_lower_bounded { + ($source:ty, $($target:ty),*) => {$( + #[stable(feature = "try_from", since = "1.34.0")] + impl TryFrom<$source> for $target { + type Error = TryFromIntError; + + /// Try to create the target number type from a source + /// number type. This returns an error if the source value + /// is outside of the range of the target type. + #[inline] + fn try_from(u: $source) -> Result<$target, TryFromIntError> { + if u >= 0 { + Ok(u as $target) + } else { + Err(TryFromIntError(())) + } + } + } + )*} +} + +// unsigned to signed (only positive bound) +macro_rules! try_from_upper_bounded { + ($source:ty, $($target:ty),*) => {$( + #[stable(feature = "try_from", since = "1.34.0")] + impl TryFrom<$source> for $target { + type Error = TryFromIntError; + + /// Try to create the target number type from a source + /// number type. This returns an error if the source value + /// is outside of the range of the target type. + #[inline] + fn try_from(u: $source) -> Result<$target, TryFromIntError> { + if u > (<$target>::max_value() as $source) { + Err(TryFromIntError(())) + } else { + Ok(u as $target) + } + } + } + )*} +} + +// all other cases +macro_rules! try_from_both_bounded { + ($source:ty, $($target:ty),*) => {$( + #[stable(feature = "try_from", since = "1.34.0")] + impl TryFrom<$source> for $target { + type Error = TryFromIntError; + + /// Try to create the target number type from a source + /// number type. This returns an error if the source value + /// is outside of the range of the target type. + #[inline] + fn try_from(u: $source) -> Result<$target, TryFromIntError> { + let min = <$target>::min_value() as $source; + let max = <$target>::max_value() as $source; + if u < min || u > max { + Err(TryFromIntError(())) + } else { + Ok(u as $target) + } + } + } + )*} +} + +macro_rules! rev { + ($mac:ident, $source:ty, $($target:ty),*) => {$( + $mac!($target, $source); + )*} +} + +// intra-sign conversions +try_from_upper_bounded!(u16, u8); +try_from_upper_bounded!(u32, u16, u8); +try_from_upper_bounded!(u64, u32, u16, u8); +try_from_upper_bounded!(u128, u64, u32, u16, u8); + +try_from_both_bounded!(i16, i8); +try_from_both_bounded!(i32, i16, i8); +try_from_both_bounded!(i64, i32, i16, i8); +try_from_both_bounded!(i128, i64, i32, i16, i8); + +// unsigned-to-signed +try_from_upper_bounded!(u8, i8); +try_from_upper_bounded!(u16, i8, i16); +try_from_upper_bounded!(u32, i8, i16, i32); +try_from_upper_bounded!(u64, i8, i16, i32, i64); +try_from_upper_bounded!(u128, i8, i16, i32, i64, i128); + +// signed-to-unsigned +try_from_lower_bounded!(i8, u8, u16, u32, u64, u128); +try_from_lower_bounded!(i16, u16, u32, u64, u128); +try_from_lower_bounded!(i32, u32, u64, u128); +try_from_lower_bounded!(i64, u64, u128); +try_from_lower_bounded!(i128, u128); +try_from_both_bounded!(i16, u8); +try_from_both_bounded!(i32, u16, u8); +try_from_both_bounded!(i64, u32, u16, u8); +try_from_both_bounded!(i128, u64, u32, u16, u8); + +// usize/isize +try_from_upper_bounded!(usize, isize); +try_from_lower_bounded!(isize, usize); + +#[cfg(target_pointer_width = "16")] +mod ptr_try_from_impls { + use super::TryFromIntError; + use crate::convert::TryFrom; + + try_from_upper_bounded!(usize, u8); + try_from_unbounded!(usize, u16, u32, u64, u128); + try_from_upper_bounded!(usize, i8, i16); + try_from_unbounded!(usize, i32, i64, i128); + + try_from_both_bounded!(isize, u8); + try_from_lower_bounded!(isize, u16, u32, u64, u128); + try_from_both_bounded!(isize, i8); + try_from_unbounded!(isize, i16, i32, i64, i128); + + rev!(try_from_upper_bounded, usize, u32, u64, u128); + rev!(try_from_lower_bounded, usize, i8, i16); + rev!(try_from_both_bounded, usize, i32, i64, i128); + + rev!(try_from_upper_bounded, isize, u16, u32, u64, u128); + rev!(try_from_both_bounded, isize, i32, i64, i128); +} + +#[cfg(target_pointer_width = "32")] +mod ptr_try_from_impls { + use super::TryFromIntError; + use crate::convert::TryFrom; + + try_from_upper_bounded!(usize, u8, u16); + try_from_unbounded!(usize, u32, u64, u128); + try_from_upper_bounded!(usize, i8, i16, i32); + try_from_unbounded!(usize, i64, i128); + + try_from_both_bounded!(isize, u8, u16); + try_from_lower_bounded!(isize, u32, u64, u128); + try_from_both_bounded!(isize, i8, i16); + try_from_unbounded!(isize, i32, i64, i128); + + rev!(try_from_unbounded, usize, u32); + rev!(try_from_upper_bounded, usize, u64, u128); + rev!(try_from_lower_bounded, usize, i8, i16, i32); + rev!(try_from_both_bounded, usize, i64, i128); + + rev!(try_from_unbounded, isize, u16); + rev!(try_from_upper_bounded, isize, u32, u64, u128); + rev!(try_from_unbounded, isize, i32); + rev!(try_from_both_bounded, isize, i64, i128); +} + +#[cfg(target_pointer_width = "64")] +mod ptr_try_from_impls { + use super::TryFromIntError; + use crate::convert::TryFrom; + + try_from_upper_bounded!(usize, u8, u16, u32); + try_from_unbounded!(usize, u64, u128); + try_from_upper_bounded!(usize, i8, i16, i32, i64); + try_from_unbounded!(usize, i128); + + try_from_both_bounded!(isize, u8, u16, u32); + try_from_lower_bounded!(isize, u64, u128); + try_from_both_bounded!(isize, i8, i16, i32); + try_from_unbounded!(isize, i64, i128); + + rev!(try_from_unbounded, usize, u32, u64); + rev!(try_from_upper_bounded, usize, u128); + rev!(try_from_lower_bounded, usize, i8, i16, i32, i64); + rev!(try_from_both_bounded, usize, i128); + + rev!(try_from_unbounded, isize, u16, u32); + rev!(try_from_upper_bounded, isize, u64, u128); + rev!(try_from_unbounded, isize, i32, i64); + rev!(try_from_both_bounded, isize, i128); +} diff --git a/src/libcore/num/mod.rs b/src/libcore/num/mod.rs index 4313248f263..585f144cf8a 100644 --- a/src/libcore/num/mod.rs +++ b/src/libcore/num/mod.rs @@ -4,7 +4,6 @@ #![stable(feature = "rust1", since = "1.0.0")] -use crate::convert::TryFrom; use crate::fmt; use crate::intrinsics; use crate::mem; @@ -4701,7 +4700,7 @@ from_str_radix_int_impl! { isize i8 i16 i32 i64 i128 usize u8 u16 u32 u64 u128 } /// The error type returned when a checked integral type conversion fails. #[stable(feature = "try_from", since = "1.34.0")] #[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub struct TryFromIntError(()); +pub struct TryFromIntError(pub(crate) ()); impl TryFromIntError { #[unstable(feature = "int_error_internals", @@ -4728,206 +4727,6 @@ impl From for TryFromIntError { } } -// no possible bounds violation -macro_rules! try_from_unbounded { - ($source:ty, $($target:ty),*) => {$( - #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { - type Error = TryFromIntError; - - /// Try to create the target number type from a source - /// number type. This returns an error if the source value - /// is outside of the range of the target type. - #[inline] - fn try_from(value: $source) -> Result { - Ok(value as $target) - } - } - )*} -} - -// only negative bounds -macro_rules! try_from_lower_bounded { - ($source:ty, $($target:ty),*) => {$( - #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { - type Error = TryFromIntError; - - /// Try to create the target number type from a source - /// number type. This returns an error if the source value - /// is outside of the range of the target type. - #[inline] - fn try_from(u: $source) -> Result<$target, TryFromIntError> { - if u >= 0 { - Ok(u as $target) - } else { - Err(TryFromIntError(())) - } - } - } - )*} -} - -// unsigned to signed (only positive bound) -macro_rules! try_from_upper_bounded { - ($source:ty, $($target:ty),*) => {$( - #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { - type Error = TryFromIntError; - - /// Try to create the target number type from a source - /// number type. This returns an error if the source value - /// is outside of the range of the target type. - #[inline] - fn try_from(u: $source) -> Result<$target, TryFromIntError> { - if u > (<$target>::max_value() as $source) { - Err(TryFromIntError(())) - } else { - Ok(u as $target) - } - } - } - )*} -} - -// all other cases -macro_rules! try_from_both_bounded { - ($source:ty, $($target:ty),*) => {$( - #[stable(feature = "try_from", since = "1.34.0")] - impl TryFrom<$source> for $target { - type Error = TryFromIntError; - - /// Try to create the target number type from a source - /// number type. This returns an error if the source value - /// is outside of the range of the target type. - #[inline] - fn try_from(u: $source) -> Result<$target, TryFromIntError> { - let min = <$target>::min_value() as $source; - let max = <$target>::max_value() as $source; - if u < min || u > max { - Err(TryFromIntError(())) - } else { - Ok(u as $target) - } - } - } - )*} -} - -macro_rules! rev { - ($mac:ident, $source:ty, $($target:ty),*) => {$( - $mac!($target, $source); - )*} -} - -// intra-sign conversions -try_from_upper_bounded!(u16, u8); -try_from_upper_bounded!(u32, u16, u8); -try_from_upper_bounded!(u64, u32, u16, u8); -try_from_upper_bounded!(u128, u64, u32, u16, u8); - -try_from_both_bounded!(i16, i8); -try_from_both_bounded!(i32, i16, i8); -try_from_both_bounded!(i64, i32, i16, i8); -try_from_both_bounded!(i128, i64, i32, i16, i8); - -// unsigned-to-signed -try_from_upper_bounded!(u8, i8); -try_from_upper_bounded!(u16, i8, i16); -try_from_upper_bounded!(u32, i8, i16, i32); -try_from_upper_bounded!(u64, i8, i16, i32, i64); -try_from_upper_bounded!(u128, i8, i16, i32, i64, i128); - -// signed-to-unsigned -try_from_lower_bounded!(i8, u8, u16, u32, u64, u128); -try_from_lower_bounded!(i16, u16, u32, u64, u128); -try_from_lower_bounded!(i32, u32, u64, u128); -try_from_lower_bounded!(i64, u64, u128); -try_from_lower_bounded!(i128, u128); -try_from_both_bounded!(i16, u8); -try_from_both_bounded!(i32, u16, u8); -try_from_both_bounded!(i64, u32, u16, u8); -try_from_both_bounded!(i128, u64, u32, u16, u8); - -// usize/isize -try_from_upper_bounded!(usize, isize); -try_from_lower_bounded!(isize, usize); - -#[cfg(target_pointer_width = "16")] -mod ptr_try_from_impls { - use super::TryFromIntError; - use crate::convert::TryFrom; - - try_from_upper_bounded!(usize, u8); - try_from_unbounded!(usize, u16, u32, u64, u128); - try_from_upper_bounded!(usize, i8, i16); - try_from_unbounded!(usize, i32, i64, i128); - - try_from_both_bounded!(isize, u8); - try_from_lower_bounded!(isize, u16, u32, u64, u128); - try_from_both_bounded!(isize, i8); - try_from_unbounded!(isize, i16, i32, i64, i128); - - rev!(try_from_upper_bounded, usize, u32, u64, u128); - rev!(try_from_lower_bounded, usize, i8, i16); - rev!(try_from_both_bounded, usize, i32, i64, i128); - - rev!(try_from_upper_bounded, isize, u16, u32, u64, u128); - rev!(try_from_both_bounded, isize, i32, i64, i128); -} - -#[cfg(target_pointer_width = "32")] -mod ptr_try_from_impls { - use super::TryFromIntError; - use crate::convert::TryFrom; - - try_from_upper_bounded!(usize, u8, u16); - try_from_unbounded!(usize, u32, u64, u128); - try_from_upper_bounded!(usize, i8, i16, i32); - try_from_unbounded!(usize, i64, i128); - - try_from_both_bounded!(isize, u8, u16); - try_from_lower_bounded!(isize, u32, u64, u128); - try_from_both_bounded!(isize, i8, i16); - try_from_unbounded!(isize, i32, i64, i128); - - rev!(try_from_unbounded, usize, u32); - rev!(try_from_upper_bounded, usize, u64, u128); - rev!(try_from_lower_bounded, usize, i8, i16, i32); - rev!(try_from_both_bounded, usize, i64, i128); - - rev!(try_from_unbounded, isize, u16); - rev!(try_from_upper_bounded, isize, u32, u64, u128); - rev!(try_from_unbounded, isize, i32); - rev!(try_from_both_bounded, isize, i64, i128); -} - -#[cfg(target_pointer_width = "64")] -mod ptr_try_from_impls { - use super::TryFromIntError; - use crate::convert::TryFrom; - - try_from_upper_bounded!(usize, u8, u16, u32); - try_from_unbounded!(usize, u64, u128); - try_from_upper_bounded!(usize, i8, i16, i32, i64); - try_from_unbounded!(usize, i128); - - try_from_both_bounded!(isize, u8, u16, u32); - try_from_lower_bounded!(isize, u64, u128); - try_from_both_bounded!(isize, i8, i16, i32); - try_from_unbounded!(isize, i64, i128); - - rev!(try_from_unbounded, usize, u32, u64); - rev!(try_from_upper_bounded, usize, u128); - rev!(try_from_lower_bounded, usize, i8, i16, i32, i64); - rev!(try_from_both_bounded, usize, i128); - - rev!(try_from_unbounded, isize, u16, u32); - rev!(try_from_upper_bounded, isize, u64, u128); - rev!(try_from_unbounded, isize, i32, i64); - rev!(try_from_both_bounded, isize, i128); -} - #[doc(hidden)] trait FromStrRadixHelper: PartialOrd + Copy { fn min_value() -> Self; @@ -5110,131 +4909,3 @@ impl fmt::Display for ParseIntError { #[stable(feature = "rust1", since = "1.0.0")] pub use crate::num::dec2flt::ParseFloatError; - -// Conversion traits for primitive integer and float types -// Conversions T -> T are covered by a blanket impl and therefore excluded -// Some conversions from and to usize/isize are not implemented due to portability concerns -macro_rules! impl_from { - ($Small: ty, $Large: ty, #[$attr:meta], $doc: expr) => { - #[$attr] - #[doc = $doc] - impl From<$Small> for $Large { - #[inline] - fn from(small: $Small) -> $Large { - small as $Large - } - } - }; - ($Small: ty, $Large: ty, #[$attr:meta]) => { - impl_from!($Small, - $Large, - #[$attr], - concat!("Converts `", - stringify!($Small), - "` to `", - stringify!($Large), - "` losslessly.")); - } -} - -macro_rules! impl_from_bool { - ($target: ty, #[$attr:meta]) => { - impl_from!(bool, $target, #[$attr], concat!("Converts a `bool` to a `", - stringify!($target), "`. The resulting value is `0` for `false` and `1` for `true` -values. - -# Examples - -``` -assert_eq!(", stringify!($target), "::from(true), 1); -assert_eq!(", stringify!($target), "::from(false), 0); -```")); - }; -} - -// Bool -> Any -impl_from_bool! { u8, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { u16, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { u32, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { u64, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { u128, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { usize, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { i8, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { i16, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { i32, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { i64, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { i128, #[stable(feature = "from_bool", since = "1.28.0")] } -impl_from_bool! { isize, #[stable(feature = "from_bool", since = "1.28.0")] } - -// Unsigned -> Unsigned -impl_from! { u8, u16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, u128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u8, usize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u16, u32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u16, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u16, u128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u32, u64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u32, u128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u64, u128, #[stable(feature = "i128", since = "1.26.0")] } - -// Signed -> Signed -impl_from! { i8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i8, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { i8, isize, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i16, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { i32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { i32, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { i64, i128, #[stable(feature = "i128", since = "1.26.0")] } - -// Unsigned -> Signed -impl_from! { u8, i16, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u8, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u16, i32, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u16, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u16, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u32, i64, #[stable(feature = "lossless_int_conv", since = "1.5.0")] } -impl_from! { u32, i128, #[stable(feature = "i128", since = "1.26.0")] } -impl_from! { u64, i128, #[stable(feature = "i128", since = "1.26.0")] } - -// The C99 standard defines bounds on INTPTR_MIN, INTPTR_MAX, and UINTPTR_MAX -// which imply that pointer-sized integers must be at least 16 bits: -// https://port70.net/~nsz/c/c99/n1256.html#7.18.2.4 -impl_from! { u16, usize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } -impl_from! { u8, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } -impl_from! { i16, isize, #[stable(feature = "lossless_iusize_conv", since = "1.26.0")] } - -// RISC-V defines the possibility of a 128-bit address space (RV128). - -// CHERI proposes 256-bit “capabilities”. Unclear if this would be relevant to usize/isize. -// https://www.cl.cam.ac.uk/research/security/ctsrd/pdfs/20171017a-cheri-poster.pdf -// http://www.csl.sri.com/users/neumann/2012resolve-cheri.pdf - - -// Note: integers can only be represented with full precision in a float if -// they fit in the significand, which is 24 bits in f32 and 53 bits in f64. -// Lossy float conversions are not implemented at this time. - -// Signed -> Float -impl_from! { i8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { i8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { i16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { i16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { i32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } - -// Unsigned -> Float -impl_from! { u8, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { u8, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { u16, f32, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { u16, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -impl_from! { u32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } - -// Float -> Float -impl_from! { f32, f64, #[stable(feature = "lossless_float_conv", since = "1.6.0")] } -- cgit 1.4.1-3-g733a5