any.rs.html -- source
Description: Source to the Rust file `src/libcore/any.rs`.
Keywords: rust, rustlang, rust-lang

      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
    327
    328
    329
    330
    331
    332
    333
    334
    335
    336
    337
    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461

    //! This module implements the `Any` trait, which enables dynamic typing
    //! of any `'static` type through runtime reflection.
    //!
    //! `Any` itself can be used to get a `TypeId`, and has more features when used
    //! as a trait object. As `&dyn Any` (a borrowed trait object), it has the `is`
    //! and `downcast_ref` methods, to test if the contained value is of a given type,
    //! and to get a reference to the inner value as a type. As `&mut dyn Any`, there
    //! is also the `downcast_mut` method, for getting a mutable reference to the
    //! inner value. `Box<dyn Any>` adds the `downcast` method, which attempts to
    //! convert to a `Box<T>`. See the [`Box`] documentation for the full details.
    //!
    //! Note that `&dyn Any` is limited to testing whether a value is of a specified
    //! concrete type, and cannot be used to test whether a type implements a trait.
    //!
    //! [`Box`]: ../../std/boxed/struct.Box.html
    //!
    //! # Examples
    //!
    //! Consider a situation where we want to log out a value passed to a function.
    //! We know the value we're working on implements Debug, but we don't know its
    //! concrete type. We want to give special treatment to certain types: in this
    //! case printing out the length of String values prior to their value.
    //! We don't know the concrete type of our value at compile time, so we need to
    //! use runtime reflection instead.
    //!
    //! ```rust
    //! use std::fmt::Debug;
    //! use std::any::Any;
    //!
    //! // Logger function for any type that implements Debug.
    //! fn log<T: Any + Debug>(value: &T) {
    //!     let value_any = value as &dyn Any;
    //!
    //!     // Try to convert our value to a `String`. If successful, we want to
    //!     // output the String`'s length as well as its value. If not, it's a
    //!     // different type: just print it out unadorned.
    //!     match value_any.downcast_ref::<String>() {
    //!         Some(as_string) => {
    //!             println!("String ({}): {}", as_string.len(), as_string);
    //!         }
    //!         None => {
    //!             println!("{:?}", value);
    //!         }
    //!     }
    //! }
    //!
    //! // This function wants to log its parameter out prior to doing work with it.
    //! fn do_work<T: Any + Debug>(value: &T) {
    //!     log(value);
    //!     // ...do some other work
    //! }
    //!
    //! fn main() {
    //!     let my_string = "Hello World".to_string();
    //!     do_work(&my_string);
    //!
    //!     let my_i8: i8 = 100;
    //!     do_work(&my_i8);
    //! }
    //! ```

    #![stable(feature = "rust1", since = "1.0.0")]

    use crate::fmt;
    use crate::intrinsics;

    ///////////////////////////////////////////////////////////////////////////////
    // Any trait
    ///////////////////////////////////////////////////////////////////////////////

    /// A type to emulate dynamic typing.
    ///
    /// Most types implement `Any`. However, any type which contains a non-`'static` reference does not.
    /// See the [module-level documentation][mod] for more details.
    ///
    /// [mod]: index.html
    #[stable(feature = "rust1", since = "1.0.0")]
    pub trait Any: 'static {
        /// Gets the `TypeId` of `self`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::{Any, TypeId};
        ///
        /// fn is_string(s: &dyn Any) -> bool {
        ///     TypeId::of::<String>() == s.type_id()
        /// }
        ///
        /// assert_eq!(is_string(&0), false);
        /// assert_eq!(is_string(&"cookie monster".to_string()), true);
        /// ```
        #[stable(feature = "get_type_id", since = "1.34.0")]
        fn type_id(&self) -> TypeId;
    }

    #[stable(feature = "rust1", since = "1.0.0")]
    impl<T: 'static + ?Sized > Any for T {
        fn type_id(&self) -> TypeId { TypeId::of::<T>() }
    }

    ///////////////////////////////////////////////////////////////////////////////
    // Extension methods for Any trait objects.
    ///////////////////////////////////////////////////////////////////////////////

    #[stable(feature = "rust1", since = "1.0.0")]
    impl fmt::Debug for dyn Any {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.pad("Any")
        }
    }

    // Ensure that the result of e.g., joining a thread can be printed and
    // hence used with `unwrap`. May eventually no longer be needed if
    // dispatch works with upcasting.
    #[stable(feature = "rust1", since = "1.0.0")]
    impl fmt::Debug for dyn Any + Send {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.pad("Any")
        }
    }

    #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
    impl fmt::Debug for dyn Any + Send + Sync {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.pad("Any")
        }
    }

    impl dyn Any {
        /// Returns `true` if the boxed type is the same as `T`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn is_string(s: &dyn Any) {
        ///     if s.is::<String>() {
        ///         println!("It's a string!");
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// is_string(&0);
        /// is_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn is<T: Any>(&self) -> bool {
            // Get `TypeId` of the type this function is instantiated with.
            let t = TypeId::of::<T>();

            // Get `TypeId` of the type in the trait object.
            let concrete = self.type_id();

            // Compare both `TypeId`s on equality.
            t == concrete
        }

        /// Returns some reference to the boxed value if it is of type `T`, or
        /// `None` if it isn't.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn print_if_string(s: &dyn Any) {
        ///     if let Some(string) = s.downcast_ref::<String>() {
        ///         println!("It's a string({}): '{}'", string.len(), string);
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// print_if_string(&0);
        /// print_if_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
            if self.is::<T>() {
                unsafe {
                    Some(&*(self as *const dyn Any as *const T))
                }
            } else {
                None
            }
        }

        /// Returns some mutable reference to the boxed value if it is of type `T`, or
        /// `None` if it isn't.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn modify_if_u32(s: &mut dyn Any) {
        ///     if let Some(num) = s.downcast_mut::<u32>() {
        ///         *num = 42;
        ///     }
        /// }
        ///
        /// let mut x = 10u32;
        /// let mut s = "starlord".to_string();
        ///
        /// modify_if_u32(&mut x);
        /// modify_if_u32(&mut s);
        ///
        /// assert_eq!(x, 42);
        /// assert_eq!(&s, "starlord");
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
            if self.is::<T>() {
                unsafe {
                    Some(&mut *(self as *mut dyn Any as *mut T))
                }
            } else {
                None
            }
        }
    }

    impl dyn Any+Send {
        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn is_string(s: &(dyn Any + Send)) {
        ///     if s.is::<String>() {
        ///         println!("It's a string!");
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// is_string(&0);
        /// is_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn is<T: Any>(&self) -> bool {
            Any::is::<T>(self)
        }

        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn print_if_string(s: &(dyn Any + Send)) {
        ///     if let Some(string) = s.downcast_ref::<String>() {
        ///         println!("It's a string({}): '{}'", string.len(), string);
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// print_if_string(&0);
        /// print_if_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
            Any::downcast_ref::<T>(self)
        }

        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn modify_if_u32(s: &mut (dyn Any + Send)) {
        ///     if let Some(num) = s.downcast_mut::<u32>() {
        ///         *num = 42;
        ///     }
        /// }
        ///
        /// let mut x = 10u32;
        /// let mut s = "starlord".to_string();
        ///
        /// modify_if_u32(&mut x);
        /// modify_if_u32(&mut s);
        ///
        /// assert_eq!(x, 42);
        /// assert_eq!(&s, "starlord");
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[inline]
        pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
            Any::downcast_mut::<T>(self)
        }
    }

    impl dyn Any+Send+Sync {
        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn is_string(s: &(dyn Any + Send + Sync)) {
        ///     if s.is::<String>() {
        ///         println!("It's a string!");
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// is_string(&0);
        /// is_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
        #[inline]
        pub fn is<T: Any>(&self) -> bool {
            Any::is::<T>(self)
        }

        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn print_if_string(s: &(dyn Any + Send + Sync)) {
        ///     if let Some(string) = s.downcast_ref::<String>() {
        ///         println!("It's a string({}): '{}'", string.len(), string);
        ///     } else {
        ///         println!("Not a string...");
        ///     }
        /// }
        ///
        /// print_if_string(&0);
        /// print_if_string(&"cookie monster".to_string());
        /// ```
        #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
        #[inline]
        pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
            Any::downcast_ref::<T>(self)
        }

        /// Forwards to the method defined on the type `Any`.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::Any;
        ///
        /// fn modify_if_u32(s: &mut (dyn Any + Send + Sync)) {
        ///     if let Some(num) = s.downcast_mut::<u32>() {
        ///         *num = 42;
        ///     }
        /// }
        ///
        /// let mut x = 10u32;
        /// let mut s = "starlord".to_string();
        ///
        /// modify_if_u32(&mut x);
        /// modify_if_u32(&mut s);
        ///
        /// assert_eq!(x, 42);
        /// assert_eq!(&s, "starlord");
        /// ```
        #[stable(feature = "any_send_sync_methods", since = "1.28.0")]
        #[inline]
        pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
            Any::downcast_mut::<T>(self)
        }
    }

    ///////////////////////////////////////////////////////////////////////////////
    // TypeID and its methods
    ///////////////////////////////////////////////////////////////////////////////

    /// A `TypeId` represents a globally unique identifier for a type.
    ///
    /// Each `TypeId` is an opaque object which does not allow inspection of what's
    /// inside but does allow basic operations such as cloning, comparison,
    /// printing, and showing.
    ///
    /// A `TypeId` is currently only available for types which ascribe to `'static`,
    /// but this limitation may be removed in the future.
    ///
    /// While `TypeId` implements `Hash`, `PartialOrd`, and `Ord`, it is worth
    /// noting that the hashes and ordering will vary between Rust releases. Beware
    /// of relying on them inside of your code!
    #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
    #[stable(feature = "rust1", since = "1.0.0")]
    pub struct TypeId {
        t: u64,
    }

    impl TypeId {
        /// Returns the `TypeId` of the type this generic function has been
        /// instantiated with.
        ///
        /// # Examples
        ///
        /// ```
        /// use std::any::{Any, TypeId};
        ///
        /// fn is_string<T: ?Sized + Any>(_s: &T) -> bool {
        ///     TypeId::of::<String>() == TypeId::of::<T>()
        /// }
        ///
        /// assert_eq!(is_string(&0), false);
        /// assert_eq!(is_string(&"cookie monster".to_string()), true);
        /// ```
        #[stable(feature = "rust1", since = "1.0.0")]
        #[rustc_const_unstable(feature="const_type_id")]
        pub const fn of<T: ?Sized + 'static>() -> TypeId {
            TypeId {
                t: unsafe { intrinsics::type_id::<T>() },
            }
        }
    }

    /// Returns the name of a type as a string slice.
    ///
    /// # Note
    ///
    /// This is intended for diagnostic use. The exact contents and format of the
    /// string are not specified, other than being a best-effort description of the
    /// type. For example, `type_name::<Option<String>>()` could return the
    /// `"Option<String>"` or `"std::option::Option<std::string::String>"`, but not
    /// `"foobar"`. In addition, the output may change between versions of the
    /// compiler.
    ///
    /// The type name should not be considered a unique identifier of a type;
    /// multiple types may share the same type name.
    ///
    /// The current implementation uses the same infrastructure as compiler
    /// diagnostics and debuginfo, but this is not guaranteed.
    ///
    /// # Example
    ///
    /// ```rust
    /// assert_eq!(
    ///     std::any::type_name::<Option<String>>(),
    ///     "core::option::Option<alloc::string::String>",
    /// );
    /// ```
    #[stable(feature = "type_name", since = "1.38.0")]
    #[rustc_const_unstable(feature = "const_type_name")]
    pub const fn type_name<T: ?Sized>() -> &'static str {
        intrinsics::type_name::<T>()
    }