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 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
#![no_std] #![allow(warnings)] //! Typic helps you transmute fearlessly. It worries about the subtleties of //! ***[soundness]*** and ***[safety]*** so you don't have to! //! //! Just import it and replace your `#[repr(...)]` attributes with `#[typic::repr(...)]`: //! ``` //! // Import it! //! use typic::{self, TransmuteInto}; //! //! // Update your attributes! //! #[typic::repr(C)] //! pub struct Foo(pub u8, pub u16); //! //! // Transmute fearlessly! //! let _ : Foo = 64u32.transmute_into(); // Alchemy achieved! //! ``` //! ```compile_fail //! # use typic::{self, TransmuteInto}; //! # #[typic::repr(C)] //! # struct Foo(pub u8, pub u16); //! let _ : u32 = Foo(16, 12).transmute_into(); // Compiler Error! //! ``` //! //! [soundness]: crate::sound#when-is-a-transmutation-sound //! [safety]: crate::safe //! //! ## Three Types of Transmutation //! //! ### Unsound Transmutation //! [`transmute`]: core::mem::transmute //! [`transmute_copy`]: core::mem::transmute_copy //! //! The [`transmute`] and [`transmute_copy`] intrinsics //! allow for the ***unsafe*** and ***unsound*** transmutation between any `T` //! and `U`. //! //! These intrinsics are deeply unsafe. The Rust compiler will accept uses of //! these intrinsics even when `T` and `U` do not have well-defined layouts. //! ***Always use a [safe transmutation](#safe-transmutation) method instead, //! if possible.*** If you are unable to use a safe transmutation method, //! ***you may be relying on undefined compiler behavior***. //! //! ### Sound Transmutation //! [`sound_transmute`]: crate::sound_transmute //! //! The [`sound_transmute`] function allows for the ***unsafe*** transmutation //! between `T` and `U`, when merely transmuting from `T` to `U` will not cause //! undefined behavior. For the key rules that govern when `T` is soundly //! convertible to `U`, see ***[When is a transmutation sound?][soundness]***. //! //! This operation is `unsafe`, as it will bypass any user-defined validity //! restrictions that `U` places on its fields and enforces with its //! constructors and methods. //! //! ***Always use a [safe transmutation](#safe-transmutation) method instead, if //! possible.*** If you are unable to use a safe transmutation method, you may //! be violating library invariants. //! //! ### Safe Transmutation //! [safe transmutation]: #safe-transmutation //! [`TransmuteInto<U>`]: crate::TransmuteInto //! //! The [`TransmuteInto<U>`] trait is implemented for a type `T` if: //! 1. [`T` is ***soundly*** transmutable into `U`][soundness], and //! 2. [`T` is ***safely*** transmutable into `U`][safety]. //! //! If you are unable to use [`TransmuteInto<U>`], you may be attempting a //! transmutation that is relying unspecified behavior. #[doc(hidden)] pub mod docs { pub mod prelude { use crate::typic; pub use crate::{transmute_sound, TransmuteInto, Transparent}; pub use core::mem; pub use core::num::NonZeroU8; #[typic::repr(C)] #[derive(Default)] pub struct Padded(pub u8, pub u16, pub u8); #[typic::repr(C)] #[derive(Default)] pub struct Packed(pub u16, pub u16, pub u16); #[typic::repr(C)] #[derive(Default)] pub struct Constrained { wizz: i8, bang: u8, } impl Constrained { /// the sum of `wizz` and `bang` must be greater than or equal to zero. pub fn new(wizz: i8, bang: u8) -> Self { assert!((wizz as i16) / (bang as i16) >= 0); Constrained { wizz, bang } } pub fn something_dangerous(&self) { unsafe { // do something that's only safe if `wizz + bang >= 0` } } } #[typic::repr(C)] #[derive(Default)] pub struct Unconstrained { pub wizz: u8, pub bang: i8, } } } #[doc(hidden)] #[deprecated(note = "TODO")] pub enum TODO {} pub(crate) mod private { pub(crate) mod bytelevel; pub mod highlevel; pub(crate) mod layout; pub(crate) mod num; pub(crate) mod target; pub(crate) mod transmute; } #[doc(hidden)] pub use private::highlevel as internal; #[doc(inline)] pub use private::highlevel::Transparent; #[doc(inline)] pub use private::transmute::{transmute_safe, transmute_sound, TransmuteFrom, TransmuteInto}; /// Use `#[typic::repr(...)]` instead of `#[repr(...)]` on your type definitions. #[doc(inline)] pub use typic_derive::repr; mod typic { pub use super::*; } /// Guidance and tools for ***safe*** transmutation. /// /// A [sound transmutation] is safe only if it also cannot violate library /// invariants on types. Unless a type implements [`Transparent`], it is /// assumed to have library-defined invariants on its fields. /// /// [sound transmutation]: crate#sound-transmutation /// [soundness]: crate::sound#when-is-a-transmutation-sound /// [`Transparent`]: crate::Transparent /// [`TransmuteInto`]: crate::TransmuteInto /// [`transmute_sound`]: crate::transmute_sound /// /// ## Why is safety different than soundness? /// Consider the type `Constrained`, which enforces a validity constraint on its /// fields, and the type `Unconstrained` (which has no internal validity /// constraints): /// /// ``` /// # use typic::docs::prelude::*; /// #[typic::repr(C)] /// pub struct Constrained { /// wizz: i8, /// bang: u8, /// } /// /// impl Constrained { /// /// the sum of `wizz` and `bang` must be greater than or equal to zero. /// pub fn new(wizz: i8, bang: u8) -> Self { /// assert!((wizz as i16) / (bang as i16) >= 0); /// Constrained { wizz, bang } /// } /// /// pub fn something_dangerous(&self) { /// unsafe { /// // do something that's only safe if `wizz + bang >= 0` /// } /// } /// } /// /// #[typic::repr(C)] /// pub struct Unconstrained { /// pub wizz: u8, /// pub bang: i8, /// } /// ``` /// /// It is [sound][soundness] to transmute an instance of `Unconstrained` into /// `Constrained`: /// ``` /// use typic::docs::prelude::*; /// let _ : Constrained = unsafe { transmute_sound(Unconstrained::default()) }; /// ``` /// ...but it isn't safe! The [`transmute_sound`] function creates an instance /// of `Bar` _without_ calling its `new` constructor, thereby bypassing the /// safety check which ensures `something_dangerous` does not violate Rust's /// memory model. The compiler will reject our program if we try to safely /// transmute `Unconstrained` to `Constrained`: /// ```compile_fail /// # use typic::docs::prelude::*; /// let unconstrained = Unconstrained::default(); /// let _ : Constrained = unconstrained.transmute_into(); /// // ^^^^^^^^^^^^^^ /// // the trait `Transparent` is not /// // implemented for `Constrained` /// ``` /// /// ## Indicating that a transmutation is safe /// /// The [`Transparent`] trait is used to indicate that a compound type does not /// place any additional validity restrictions on its fields. /// /// This trait can be implemented ***manually***: /// ``` /// # use typic::docs::prelude::*; /// #[typic::repr(C)] /// pub struct Unconstrained { /// wizz: u8, /// bang: i8, /// } /// /// unsafe impl Transparent for Unconstrained {} /// /// let _ : Unconstrained = u16::default().transmute_into(); /// ``` /// /// Or, ***automatically***, by marking the fields `pub`: /// ``` /// # use typic::docs::prelude::*; /// #[typic::repr(C)] /// pub struct Unconstrained { /// pub wizz: u8, /// pub bang: i8, /// } /// /// let _ : Unconstrained = u16::default().transmute_into(); /// ``` /// /// If the fields are marked `pub`, the type cannot rely on any internal /// validity requirements, as users of the type are free to manipulate its /// fields via the `.` operator. /// /// ## Safely transmuting references /// When safely transmuting owned values, only the destination must be /// [`Transparent`]: /// ``` /// # use typic::docs::prelude::*; /// let _ : Unconstrained = Constrained::default().transmute_into(); /// ``` /// When safely transmuting references, both the source and destination types /// must be [`Transparent`]: /// ```compile_fail /// # use typic::docs::prelude::*; /// let mut x = Constrained::default(); /// /// { /// let y : &mut Unconstrained = (&mut x).transmute_into(); /// // ^^^^^^^^^^^^^^ /// // the trait `Transparent` is not /// // implemented for `Constrained` /// let z : u8 = -100i8.transmute_into(); /// y.wizz = z; /// } /// /// x.something_dangerous(); /// Ack! `x.wizz + x.bang` is -100! /// ``` pub mod safe { #[doc(inline)] pub use crate::{transmute_safe, TransmuteFrom, TransmuteInto}; } /// Guidance and tools for ***sound*** transmutation. /// /// A transmutation is ***sound*** if the mere act of transmutation is /// guaranteed to not violate Rust's memory model. /// /// [`sound_transmute`]: crate::sound_transmute /// [`TransmuteInto<U>`]: crate::TransmuteInto /// /// ## When is a transmutation sound? /// [`NonZeroU8`]: core::num::NonZeroU8 /// /// A transmutation is only sound if it occurs between types with [well-defined /// representations](#well-defined-representation), and does not violate Rust's /// memory model. See [*Transmutations Between Owned Values*][transmute-owned], /// and [*Transmutations Between References*][transmute-references]. These rules /// are automatically enforced by [`sound_transmute`] and [`TransmuteInto<U>`]. /// /// ### Well-Defined Representation /// [`u8`]: core::u8 /// [`f32`]: core::f32 /// /// Transmutation is ***always unsound*** if it occurs between types with /// unspecified representations. Most of Rust's primitive types have specified /// representations. That is, the layout characteristics of [`u8`], [`f32`] and /// others are guaranteed to be stable across compiler versions. /// /// In contrast, most `struct` and `enum` types defined without an explicit /// `#[repr(C)]` or `#[repr(transparent)]` attribute do ***not*** have /// well-specified layout characteristics. /// /// To ensure that types you've define are soundly transmutable, you usually /// must mark them with the `#[repr(C)]` attribute. /// /// ### Transmuting Owned Values /// [transmute-owned]: #transmuting-owned-values /// /// Transmutations involving owned values must adhere to two rules to be sound. /// They must: /// * [preserve or broaden the bit validity][owned-validity], and /// * [preserve or shrink the size][owned-size]. /// /// #### Preserve or Broaden Bit Validity /// [owned-validity]: #preserve-or-broaden-bit-validity /// /// For each _i<sup>th</sup>_ of the destination type, all possible /// instantiations of the _i<sup>th</sup>_ byte of the source type must be a /// bit-valid instance of the _i<sup>th</sup>_ byte of the destination type. /// /// For example, we are permitted us to transmute a [`NonZeroU8`] into a [`u8`]: /// ```rust /// # use typic::docs::prelude::*; /// let _ : u8 = NonZeroU8::new(1).unwrap().transmute_into(); /// ``` /// ...because all possible instances of [`NonZeroU8`] are also valid instances /// of [`u8`]. However, transmuting a [`u8`] into a [`NonZeroU8`] is forbidden: /// ```compile_fail /// # use typic::docs::prelude::*; /// let _ : NonZeroU8 = u8::default().transmute_into(); // Compile Error! /// ``` /// ...because not all instances of [`u8`] are valid instances of [`NonZeroU8`]. /// /// Another example: While laying out certain types, rust may insert padding /// bytes between the layouts of fields. In the below example `Padded` has two /// padding bytes, while `Packed` has none: /// ```rust /// # use typic::docs::prelude::*; /// #[typic::repr(C)] /// #[derive(Default)] /// struct Padded(pub u8, pub u16, pub u8); /// /// #[typic::repr(C)] /// #[derive(Default)] /// struct Packed(pub u16, pub u16, pub u16); /// /// assert_eq!(mem::size_of::<Packed>(), mem::size_of::<Padded>()); /// ``` /// /// We may safely transmute from `Packed` to `Padded`: /// ```rust /// # use typic::docs::prelude::*; /// let _ : Padded = Packed::default().transmute_into(); /// ``` /// ...but not from `Padded` to `Packed`: /// ```compile_fail /// # use typic::docs::prelude::*; /// let _ : Packed = Padded::default().transmute_into(); // Compile Error! /// ``` /// ...because doing so would expose two uninitialized padding bytes in `Padded` /// as if they were initialized bytes in `Packed`. /// /// #### Preserve or Shrink Size /// [owned-size]: #preserve-or-shrink-size /// /// It's completely safe to transmute into a type with fewer bytes than the /// destination type; e.g.: /// ```rust /// # use typic::docs::prelude::*; /// let _ : u8 = u64::default().transmute_into(); /// ``` /// This transmute truncates away the final three bytes of the `u64` value. /// /// A value may ***not*** be transmuted into a type of greater size: /// ```compile_fail /// # use typic::docs::prelude::*; /// let _ : u64 = u8::default().transmute_into(); // Compile Error! /// ``` /// /// ### Transmuting References /// [transmute-references]: #transmuting-references /// /// The [restrictions above that to transmuting owned values][transmute-owned], /// also apply to transmuting references. However, references carry a few /// additional restrictions. A [sound transmutation](#sound-transmutation) must: /// - [preserve or relax alignment][reference-alignment], /// - [preserve or shrink lifetimes][reference-lifetimes], /// - [preserve or shrink mutability][reference-mutability], and /// - [preserve validity][reference-validity]. /// /// #### Preserve or Relax Alignment /// [reference-alignment]: #preserve-or-relax-alignment /// /// You may transmute a reference into reference of more relaxed alignment: /// ```rust /// # use typic::docs::prelude::*; /// let _: &[u8; 0] = (&[0u16; 0]).transmute_into(); /// ``` /// /// However, you may **not** transmute a reference into a reference of stricter /// alignment: /// ```compile_fail /// # use typic::docs::prelude::*; /// let _: &[u16; 0] = (&[0u8; 0]).transmute_into(); // Compile Error! /// ``` /// /// #### Preserve or Shrink Lifetimes /// [reference-lifetimes]: #preserve-or-shrink-lifetimes /// /// You may transmute a reference into reference of lesser lifetime: /// ```rust /// # use typic::docs::prelude::*; /// fn shrink<'a>() -> &'a u8 { /// static long : &'static u8 = &16; /// long /// } /// ``` /// /// However, you may **not** transmute a reference into a reference of greater /// lifetime: /// ```compile_fail /// # use typic::docs::prelude::*; /// fn extend<'a>(short: &'a u8) -> &'static u8 { /// static long : &'static u8 = &16; /// short.transmute_into() /// } /// ``` /// /// #### Preserve or Shrink Mutability /// [reference-mutability]: #preserve-or-shrink-mutability /// /// You may preserve or decrease the mutability of a reference through /// transmutation: /// ```rust /// # use typic::docs::prelude::*; /// let _: &u8 = (&42u8).transmute_into(); /// let _: &u8 = (&mut 42u8).transmute_into(); /// ``` /// /// However, you may **not** transmute an immutable reference into a mutable /// reference: /// ```compile_fail /// # use typic::docs::prelude::*; /// let _: &mut u8 = (&42u8).transmute_into(); // Compile Error! /// ``` /// /// #### Preserve Validity /// [reference-validity]: #preserve-validity /// /// Unlike transmutations of owned values, the transmutation of a reference may /// also not expand the bit-validity of the referenced type. For instance: /// /// ```compile_fail /// # use typic::docs::prelude::*; /// let mut x = NonZeroU8::new(42).unwrap(); /// { /// let y : &mut u8 = (&mut x).transmute_into(); // Compile Error! /// *y = 0; /// } /// /// let z : NonZeroU8 = x; /// ``` /// If this example did not produce a compile error, the value of `z` would not /// be a bit-valid instance of its type. pub mod sound { pub use crate::transmute_sound; } /// Details about the layout of types. /// /// [`SizeOf`]: crate::layout::SizeOf /// [`zerocopy`]: https://crates.io/crates/zerocopy /// [`AsBytes`]: https://docs.rs/zerocopy/0.2.*/zerocopy/trait.AsBytes.html /// [`FromBytes`]: https://docs.rs/zerocopy/0.2.*/zerocopy/trait.FromBytes.html /// [`Unaligned`]: https://docs.rs/zerocopy/0.2.*/zerocopy/trait.Unaligned.html /// /// Useful for building your own abstractions over Typic. For instance, we can /// use [`SizeOf`] to implement [`zerocopy`]'s [`FromBytes`], [`AsBytes`] and /// [`Unaligned`] marker traits: /// /// ``` /// use typic::{layout::{Layout, SizeOf}, TransmuteInto, TransmuteFrom}; /// use generic_array::{ArrayLength as Length, GenericArray as Array}; /// use typenum::U1; /// /// /// Indicates `Self` can be produced from an /// /// appropriately-sized array of arbitrarily /// /// initialized bytes. /// pub trait FromBytes {} /// /// impl<T> FromBytes for T /// where /// T: Layout, /// SizeOf<T>: Length<u8>, /// T: TransmuteFrom<Array<u8, SizeOf<T>>> /// {} /// /// /// Indicates `Self` can be converted into an /// /// appropriately-sized array of arbitrarily /// /// initialized bytes. /// pub trait AsBytes {} /// /// impl<T> AsBytes for T /// where /// T: Layout, /// SizeOf<T>: Length<u8>, /// T: TransmuteInto<Array<u8, SizeOf<T>>> /// {} /// /// /// Indicates `Self` has no alignment requirement. /// pub trait Unaligned {} /// /// impl<T> Unaligned for T /// where /// T: Layout<Align=U1>, /// {} /// ``` pub mod layout { use crate::private::{layout, num}; /// Type-level information about type representation. pub trait Layout { /// The size of `Self`. /// /// ``` /// use typenum::*; /// use static_assertions::*; /// use typic::layout::Layout; /// /// assert_type_eq_all!(U4, <[u16; 2] as Layout>::Size); /// ``` type Size: num::Unsigned; /// The minimum alignment of `Self`. /// /// ``` /// use typenum::*; /// use static_assertions::*; /// use typic::layout::Layout; /// /// assert_type_eq_all!(U2, <[u16; 2] as Layout>::Align); /// ``` type Align: num::Unsigned; } impl<T> Layout for T where T: layout::Layout, { type Size = <T as layout::Layout>::Size; type Align = <T as layout::Layout>::Align; } /// Get the size of `T` (if `T: Layout`). /// /// ``` /// use typenum::*; /// use static_assertions::*; /// use typic::layout::SizeOf; /// /// assert_type_eq_all!(U4, SizeOf<[u16; 2]>); /// ``` pub type SizeOf<T> = <T as Layout>::Size; /// Get the minimum alignment of `T` (if `T: Layout`). /// /// ``` /// use typenum::*; /// use static_assertions::*; /// use typic::layout::AlignOf; /// /// assert_type_eq_all!(U2, AlignOf<[u16; 2]>); /// ``` pub type AlignOf<T> = <T as Layout>::Align; }