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 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042
#![feature(untagged_unions,const_fn,const_fn_union)] // for the impl of transmute free functions #![feature(const_generics)] // for stability declarations on `[T; N]` #![feature(decl_macro)] // for stub implementations of derives #![feature(never_type)] // for stability declarations on `!` #![feature(marker_trait_attr)] // for cast extension #![cfg_attr(doc, feature(staged_api))] // for `unstable` attribute #![feature(optin_builtin_traits)] // for `mem` gadgets demo #![feature(vec_into_raw_parts)] // for vec casting demo #![feature(impl_trait_in_bindings)] #![allow(unused_unsafe, incomplete_features)] #![deny(missing_docs)] //! Rustdoc for the API surface proposed by the [safer transmute RFC](https://github.com/rust-lang/project-safe-transmute/pull/5). //! //! New modules and new items within existing modules are marked with **🌟**. Items associated with RFC extensions are marked unstable. //! //! <style>h2#macros, h2#macros + table, a[href="#macros"] { display: none!important; }</style> /// Additions to libcore. pub mod core { /// Traits for conversions between types. pub mod convert { #[doc(no_inline)] pub use core::convert::*; use transmute::*; /// **🌟** **Bit-preserving conversions.** /// /// Transmutation is the act of reinterpreting the bytes corresponding to a value of one type as if they corresponded to a different type. A transmutation of a `Src` to a `Dst` type is similar to defining a union with two variants: /// ```rust /// #![feature(untagged_unions)] /// union Transmute<Src, Dst> { /// src: ManuallyDrop<Src>, /// dst: ManuallyDrop<Dst>, /// } /// ``` /// And instantiating that union with its `src` variant, then reading `dst` back out. The [TransmuteFrom] and [TransmuteInto] traits are implemented *automatically* for all `Src` and `Dst` types where it is *sound*, *safe*, and *stable* to do this conversion: /// - A transmutation is ***sound*** if the mere act of transmuting a value from one type to another is not compiler undefined behavior. /// - A sound transmutation is ***safe*** if *using* the transmuted value cannot violate memory safety. /// - A safe transmutation is ***stable*** if the authors of the source type and destination types [have indicated that the layouts of those types is part of their libraries' stability guarantees][stability]. /// /// For more information on these concepts [**see here**](https://github.com/jswrenn/project-safe-transmute/blob/rfc/rfcs/0000-safe-transmute.md#concepts-in-depth). /// /// ## Example /// Given: /// ```rust /// use core::convert::transmute::{ /// TransmuteInto, /// stability::{PromiseTransmutableInto, PromiseTransmutableFrom}, /// }; /// /// #[derive(PromiseTransmutableInto, PromiseTransmutableFrom)] /// #[repr(C)] /// pub struct Foo(pub u8, pub u16); /// // ^ there's a padding byte here, between these fields /// ``` /// This transmutation accepted: /// ```rust /// let _ : Foo = 64u32.transmute_into(); // Alchemy Achieved! /// // ^^^^^^^^^^^^^^ provided by the `TransmuteInto` trait /// ``` /// But this transmutation is rejected: /// ```compile_fail /// let _ : u32 = Foo(16, 12).transmute_into(); /// // error[E0277]: the trait bound `u32: TransmuteFrom<Foo, _>` is not satisfied /// // --> src/demo.rs:15:27 /// // | /// // 15 | let _ : u32 = Foo(16, 12).transmute_into(); /// // | ^^^^^^^^^^^^^^ the trait `TransmuteFrom<foo::Foo, _>` is not implemented for `u32` /// // | /// // = note: required because of the requirements on the impl of `TransmuteInto<u32, _>` for `foo::Foo` /// ``` pub mod transmute { use {options::*, stability::*}; /// Reinterprets the bits of a value of one type as another type, safely. /// /// Use `()` as `Neglect` to omit *no* static checks. #[inline(always)] pub const fn safe_transmute<Src, Dst, Neglect>(src: Src) -> Dst where Src: TransmuteInto<Dst, Neglect>, Neglect: SafeTransmuteOptions { unsafe { unsafe_transmute::<Src, Dst, Neglect>(src) } } /// Reinterprets the bits of a value of one type as another type, potentially unsafely. /// /// The onus is on you to ensure that calling this method is safe. #[inline(always)] pub const unsafe fn unsafe_transmute<Src, Dst, Neglect>(src: Src) -> Dst where Src: TransmuteInto<Dst, Neglect>, Neglect: TransmuteOptions { use core::mem::ManuallyDrop; #[repr(C)] union Transmute<Src, Dst> { src: ManuallyDrop<Src>, dst: ManuallyDrop<Dst>, } unsafe { ManuallyDrop::into_inner(Transmute { src: ManuallyDrop::new(src) }.dst) } } /// Reinterpret the bits of `Self` as a type `Dst`. /// /// The reciprocal of [TransmuteFrom]. /// /// ***This trait is implemented automatically by the compiler for combinations of types where a transmutation is valid.*** pub unsafe trait TransmuteInto<Dst: ?Sized, Neglect = ()> where Neglect: TransmuteOptions, { /// Reinterpret the bits of a value of one type as another type, safely. fn transmute_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: SafeTransmuteOptions; /// Reinterpret the bits of a value of one type as another type, potentially unsafely. /// /// The onus is on you to ensure that calling this method is safe. unsafe fn unsafe_transmute_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: TransmuteOptions; } unsafe impl<Src, Dst, Neglect> TransmuteInto<Dst, Neglect> for Src where Src: ?Sized, Dst: ?Sized + TransmuteFrom<Src, Neglect>, Neglect: TransmuteOptions, { #[inline(always)] fn transmute_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: SafeTransmuteOptions, { Dst::transmute_from(self) } #[inline(always)] unsafe fn unsafe_transmute_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: TransmuteOptions, { unsafe { Dst::unsafe_transmute_from(self) } } } /// Reinterpret the bits of `Src` as a type `Self`. /// /// The reciprocal of [TransmuteFrom]. /// /// ***This trait is implemented automatically by the compiler for combinations of types where a transmutation is valid.*** pub unsafe trait TransmuteFrom<Src: ?Sized, Neglect = ()> where Neglect: TransmuteOptions, { /// Reinterpret the bits of a value of one type as another type, safely. #[inline(always)] fn transmute_from(src: Src) -> Self where Src: Sized, Self: Sized, Neglect: SafeTransmuteOptions, { unsafe { Self::unsafe_transmute_from(src) } } /// Reinterpret the bits of a value of one type as another type, potentially unsafely. /// /// The onus is on you to ensure that calling this function is safe. #[inline(always)] unsafe fn unsafe_transmute_from(src: Src) -> Self where Src: Sized, Self: Sized, Neglect: TransmuteOptions, { unsafe_transmute::<Src, Self, Neglect>(src) } } #[doc(hidden)] unsafe impl<T> TransmuteFrom<T, NeglectStability> for T {} /// A type `Dst` is [stably][stability] transmutable from `Src` if: /// - `Dst` implements [PromiseTransmutableFrom][trait@PromiseTransmutableFrom], /// - `Src` implements [PromiseTransmutableInto][trait@PromiseTransmutableInto], and /// - The [PromiseTransmutableFrom::Archetype] of `Dst` is safely transmutable from the [PromiseTransmutableInto::Archetype] of `Src`. unsafe impl<Src, Dst> TransmuteFrom<Src> for Dst where Src: PromiseTransmutableInto, Dst: PromiseTransmutableFrom, <Dst as PromiseTransmutableFrom>::Archetype: TransmuteFrom< <Src as PromiseTransmutableInto>::Archetype, NeglectStability > {} /// Traits for declaring the SemVer stability of a type's layout. /// /// Since the soundness and safety of a transmutation is affected by the layouts of the source and destination types, changes to those types' layouts may cause code which previously compiled to produce errors. In other words, transmutation causes a type's layout to become part of that type's API for the purposes of SemVer stability. /// /// To promise that all transmutations which are currently safe for your type will remain so in the future, simply annotate your type with: /// ```rust /// #[derive(PromiseTransmutableFrom, PromiseTransmutableInto)] /// #[repr(C)] /// pub struct Foo(pub Bar, pub Baz); /// ``` /// /// For more information on stability, [**see here**](https://github.com/jswrenn/project-safe-transmute/blob/rfc/rfcs/0000-safe-transmute.md#-when-is-a-transmutation-stable). pub mod stability { use super::{TransmuteFrom, TransmuteInto, options::NeglectStability}; /// Promise that a type may be stably transmuted *into* other types. /// /// To promise that all safe transmutations from your type into other `PromiseTransmutableFrom` types will remain safe in the future, simply annotate your type with `#[derive(PromiseTransmutableFrom)]`; e.g.: /// ```rust /// #[derive(PromiseTransmutableFrom)] /// #[repr(C)] /// pub struct Foo(pub Bar, pub Baz); /// ``` pub trait PromiseTransmutableInto where Self::Archetype: PromiseTransmutableInto { /// A type which exemplifies the greatest extent to which `Self` might change in non-breaking crate releases, insofar that those changes might affect converting `Self` into another type via transmutation. type Archetype: TransmuteFrom<Self, NeglectStability>; } /// Promise that a type may be stably transmuted *from* other types. /// /// To promise that all transmutations of any `PromiseTransmutableInto` type into your type that are currently safe will remain so in the future, simply annotate your type with `#[derive(PromiseTransmutableFrom)]`. /// /// For instance, this: /// ```rust /// #[derive(PromiseTransmutableFrom)] /// #[repr(C)] /// pub struct Foo(pub Bar, pub Baz); /// ``` /* #[lang = "promise_transmutable_from"] */ pub trait PromiseTransmutableFrom where Self::Archetype: PromiseTransmutableFrom { /// A type which exemplifies the greatest extent to which `Self` might change in non-breaking crate releases, insofar that those changes might affect instantiating `Self` via transmutation. type Archetype: TransmuteInto<Self, NeglectStability>; } #[doc(hidden)] mod macros { use super::*; /// Derive macro generating an impl of the trait [PromiseTransmutableFrom][trait@PromiseTransmutableFrom]. /// /// To promise that all safe transmutations from your type into other `PromiseTransmutableFrom` types will remain safe in the future, simply annotate your type with `#[derive(PromiseTransmutableFrom)]`. /// /// For instance, this: /// ```rust /// #[derive(PromiseTransmutableFrom)] /// #[repr(C)] /// pub struct Foo(pub Bar, pub Baz); /// ``` /// will expand to this: /// ```rust /// /// Generated `PromiseTransmutableInto` for `Foo` /// const _: () = { /// use core::convert::transmute::stability::PromiseTransmutableInto; /// /// #[repr(C)] /// pub struct TransmutableIntoArchetype( /// pub <Bar as PromiseTransmutableInto>::Archetype, /// pub <Baz as PromiseTransmutableInto>::Archetype, /// ); /// /// impl PromiseTransmutableInto for TransmutableIntoArchetype { type Archetype = Self }; /// /// impl PromiseTransmutableInto for Foo { /// type Archetype = TransmutableIntoArchetype; /// } /// }; /// ``` pub macro PromiseTransmutableInto($item:item) { /* compiler built-in */ } /// Derive macro generating an impl of the trait [PromiseTransmutableFrom][trait@PromiseTransmutableFrom]. /// /// To promise that all transmutations of any `PromiseTransmutableInto` type into your type that are currently safe will remain so in the future, simply annotate your type with `#[derive(PromiseTransmutableFrom)]`. /// /// For instance, this: /// ```rust /// #[derive(PromiseTransmutableFrom)] /// #[repr(C)] /// pub struct Foo(pub Bar, pub Baz); /// ``` /// will expand to this: /// ```rust /// /// Generated `PromiseTransmutableFrom` for `Foo` /// const _: () = { /// use core::convert::transmute::stability::PromiseTransmutableFrom; /// /// #[repr(C)] /// pub struct TransmutableFromArchetype( /// pub <Bar as PromiseTransmutableFrom>::Archetype, /// pub <Baz as PromiseTransmutableFrom>::Archetype, /// ); /// /// impl PromiseTransmutableFrom for TransmutableFromArchetype { type Archetype = Self }; /// /// impl PromiseTransmutableFrom for Foo { /// type Archetype = TransmutableFromArchetype; /// } /// }; /// ``` pub macro PromiseTransmutableFrom($item:item) { /* compiler built-in */ } /// Derive macro generating impls of *both* [PromiseTransmutableFrom][trait@PromiseTransmutableFrom] and [PromiseTransmutableInto][trait@PromiseTransmutableInto]. /// /// This is just a shorthand for deriving both [PromiseTransmutableFrom!] and [PromiseTransmutableInto!]. /// /// For more information on this extension, [**see here**](https://github.com/jswrenn/project-safe-transmute/blob/rfc/rfcs/0000-safe-transmute.md#extension-promisetransmutable-shorthand). #[cfg_attr(doc, unstable(feature = "stability_shorthand", issue = "none"))] pub macro PromiseTransmutable($item:item) { /* compiler built-in */ } } #[doc(inline)] pub use macros::{ PromiseTransmutableInto, PromiseTransmutableFrom, PromiseTransmutable, }; impl PromiseTransmutableInto for ! {type Archetype = Self;} impl PromiseTransmutableFrom for ! {type Archetype = Self;} impl PromiseTransmutableInto for () {type Archetype = Self;} impl PromiseTransmutableFrom for () {type Archetype = Self;} impl PromiseTransmutableInto for f32 {type Archetype = Self;} impl PromiseTransmutableFrom for f32 {type Archetype = Self;} impl PromiseTransmutableInto for f64 {type Archetype = Self;} impl PromiseTransmutableFrom for f64 {type Archetype = Self;} impl PromiseTransmutableInto for i8 {type Archetype = Self;} impl PromiseTransmutableFrom for i8 {type Archetype = Self;} impl PromiseTransmutableInto for i16 {type Archetype = Self;} impl PromiseTransmutableFrom for i16 {type Archetype = Self;} impl PromiseTransmutableInto for i32 {type Archetype = Self;} impl PromiseTransmutableFrom for i32 {type Archetype = Self;} impl PromiseTransmutableInto for i64 {type Archetype = Self;} impl PromiseTransmutableFrom for i64 {type Archetype = Self;} impl PromiseTransmutableInto for i128 {type Archetype = Self;} impl PromiseTransmutableFrom for i128 {type Archetype = Self;} impl PromiseTransmutableInto for isize {type Archetype = Self;} impl PromiseTransmutableFrom for isize {type Archetype = Self;} impl PromiseTransmutableInto for u8 {type Archetype = Self;} impl PromiseTransmutableFrom for u8 {type Archetype = Self;} impl PromiseTransmutableInto for u16 {type Archetype = Self;} impl PromiseTransmutableFrom for u16 {type Archetype = Self;} impl PromiseTransmutableInto for u32 {type Archetype = Self;} impl PromiseTransmutableFrom for u32 {type Archetype = Self;} impl PromiseTransmutableInto for u64 {type Archetype = Self;} impl PromiseTransmutableFrom for u64 {type Archetype = Self;} impl PromiseTransmutableInto for u128 {type Archetype = Self;} impl PromiseTransmutableFrom for u128 {type Archetype = Self;} impl PromiseTransmutableInto for usize {type Archetype = Self;} impl PromiseTransmutableFrom for usize {type Archetype = Self;} use core::marker::PhantomData; impl<T: ?Sized> PromiseTransmutableInto for PhantomData<T> { type Archetype = Self; } impl<T: ?Sized> PromiseTransmutableFrom for PhantomData<T> { type Archetype = Self; } impl<T, const N: usize> PromiseTransmutableInto for [T; N] where T: PromiseTransmutableInto, [T::Archetype; N] : TransmuteFrom<Self, NeglectStability> + PromiseTransmutableInto, { type Archetype = [T::Archetype; N]; } impl<T, const N: usize> PromiseTransmutableFrom for [T; N] where T: PromiseTransmutableFrom, [T::Archetype; N] : TransmuteInto<Self, NeglectStability> + PromiseTransmutableFrom, { type Archetype = [T::Archetype; N]; } impl<T: ?Sized> PromiseTransmutableInto for *const T where T: PromiseTransmutableInto, *const T::Archetype : TransmuteFrom<Self, NeglectStability> + PromiseTransmutableInto, { type Archetype = *const T::Archetype; } impl<T: ?Sized> PromiseTransmutableFrom for *const T where T: PromiseTransmutableFrom, *const T::Archetype : TransmuteInto<Self, NeglectStability> + PromiseTransmutableFrom, { type Archetype = *const T::Archetype; } impl<T: ?Sized> PromiseTransmutableInto for *mut T where T: PromiseTransmutableInto, *mut T::Archetype : TransmuteFrom<Self, NeglectStability> + PromiseTransmutableInto, { type Archetype = *mut T::Archetype; } impl<T: ?Sized> PromiseTransmutableFrom for *mut T where T: PromiseTransmutableFrom, *mut T::Archetype : TransmuteInto<Self, NeglectStability> + PromiseTransmutableFrom, { type Archetype = *mut T::Archetype; } impl<'a, T: ?Sized> PromiseTransmutableInto for &'a T where T: PromiseTransmutableInto, &'a T::Archetype : TransmuteFrom<&'a T, NeglectStability> + PromiseTransmutableInto, { type Archetype = &'a T::Archetype; } impl<'a, T: ?Sized> PromiseTransmutableFrom for &'a T where T: PromiseTransmutableFrom, &'a T::Archetype : TransmuteInto<&'a T, NeglectStability> + PromiseTransmutableFrom, { type Archetype = &'a T::Archetype; } impl<'a, T: ?Sized> PromiseTransmutableInto for &'a mut T where T: PromiseTransmutableInto, &'a mut T::Archetype : TransmuteFrom<&'a mut T, NeglectStability> + PromiseTransmutableInto, { type Archetype = &'a mut T::Archetype; } impl<'a, T: ?Sized> PromiseTransmutableFrom for &'a mut T where T: PromiseTransmutableFrom, &'a mut T::Archetype : TransmuteInto<&'a mut T, NeglectStability> + PromiseTransmutableFrom, { type Archetype = &'a mut T::Archetype; } } /// Static checks that may be neglected when determining if two types are transmutable. /// /// The default value of the `Neglect` parameter of [TransmuteFrom] and [TransmuteInto], `()`, statically forbids transmutes that are unsafe, unsound, or unstable. However, you may explicitly opt-out of some static checks: /// /// | Transmute Option | Compromises | Usable With | /// |---------------------|-------------|---------------------------------------------------------| /// | [NeglectStability] | Stability | `transmute_{from,into}`, `unsafe_transmute_{from,into}` | /// | [NeglectAlignment] | Safety | `unsafe_transmute_{from,into}` | /// | [NeglectValidity] | Soundness | `unsafe_transmute_{from,into}` | /// /// The selection of multiple options is encoded by grouping them as a tuple; e.g., `(NeglectAlignment, NeglectValidity)` is a selection of both the [NeglectAlignment] and [NeglectValidity] options. pub mod options { use super::*; /// Options that may be used with safe transmutations. pub trait SafeTransmuteOptions: TransmuteOptions {} /// Options that may be used with unsafe transmutations. pub trait TransmuteOptions: private::Sealed {} impl SafeTransmuteOptions for () {} impl TransmuteOptions for () {} /// Neglect the static stability check. /// /// By default, [TransmuteFrom] and [TransmuteInto] require that the [layouts of the source and destination types are SemVer-stable][super::stability]. The [NeglectStability] option disables this requirement. /// /// Prior to the adoption of the [stability declaration traits][super::stability], crate authors documented the layout guarantees of their types with doc comments. The [TransmuteFrom] and [TransmuteInto] traits and methods may be used with these types by requesting that the stability check is neglected; for instance: /// /// ```rust /// fn serialize<W: Write>(val : LibraryType, dst: W) -> std::io::Result<()> /// where /// LibraryType: TransmuteInto<[u8; size_of::<LibraryType>()], NeglectStability> /// { /// ... /// } /// ``` /// /// Neglecting stability over-eagerly cannot cause unsoundness or unsafety. For this reason, it is the only transmutation option available on the safe methods `transmute_from` and `transmute_into`. However, neglecting stability over-eagerly may cause your code to cease compiling if the authors of the source and destination types make changes that affect their layout. /// /// By using the `NeglectStability` option to transmute types you do not own, you are committing to ensure that your reliance on these types' layouts is consistent with their documented stability guarantees. pub struct NeglectStability; // Uncomment this if/when constructibility is fully implemented: impl SafeTransmuteOptions for NeglectStability {} impl TransmuteOptions for NeglectStability {} /// Neglect the static alignment check. /// /// By default, [TransmuteFrom] and [TransmuteInto] are only implemented for references when the minimum alignment of the destination's referent type is no greater than the minimum alignment of the source's referent type. The `NeglectAlignment` option disables this requirement. /// /// By using the `NeglectAlignment` option, you are committing to ensure that the transmuted reference satisfies the alignment requirements of the destination's referent type. For instance: /// ```rust /// /// Try to convert a `&T` into `&U`. /// /// /// /// This produces `None` if the referent isn't appropriately /// /// aligned, as required by the destination type. /// pub fn try_cast_ref<'t, 'u, T, U>(src: &'t T) -> Option<&'u U> /// where /// &'t T: TransmuteInto<&'u U, NeglectAlignment>, /// { /// if (src as *const T as usize) % align_of::<U>() != 0 { /// None /// } else { /// // Safe because we dynamically enforce the alignment /// // requirement, whose static check we chose to neglect. /// Some(unsafe { src.unsafe_transmute_into() }) /// } /// } /// ``` pub struct NeglectAlignment; impl TransmuteOptions for NeglectAlignment {} /// Partially neglect the static validity check. /// /// By default, [TransmuteFrom] and [TransmuteInto]'s methods require that all instantiations of the source type are guaranteed to be valid instantiations of the destination type. This precludes transmutations which *might* be valid depending on the source value: /// ```rust /// #[derive(PromiseTransmutableFrom, PromiseTransmutableInto)] /// #[repr(u8)] /// enum Bool { /// True = 1, /// False = 0, /// } /// /// /* ⚠️ This example intentionally does not compile. */ /// let _ : Bool = some_u8_value.transmute_into(); // Compile Error! /// ``` /// The [NeglectValidity] option disables this check. /// /// By using the [NeglectValidity] option, you are committing to ensure dynamically source value is a valid instance of the destination type. For instance: /// ```rust /// #[derive(PromiseTransmutableFrom, PromiseTransmutableInto)] /// #[repr(u8)] /// enum Bool { /// True = 1, /// False = 0, /// } /// /// pub trait TryIntoBool /// { /// fn try_into_bool(self) -> Option<Bool>; /// } /// /// impl<T> TryIntoBool for T /// where /// T: TransmuteInto<u8>, /// u8: TransmuteInto<Bool, NeglectValidity> /// { /// fn try_into_bool(self) -> Option<Bool> { /// let val: u8 = self.transmute_into(); /// /// if val > 1 { /// None /// } else { /// // Safe, because we've first verified that /// // `val` is a bit-valid instance of a boolean. /// Some(unsafe {val.unsafe_transmute_into()}) /// } /// } /// } /// ``` /// /// Even with [NeglectValidity], the compiler will still statically reject transmutations that cannot possibly be valid: /// ```compile_fail /// #[derive(PromiseTransmutableInto)] /// #[repr(C)] enum Foo { A = 24 } /// /// #[derive(PromiseTransmutableFrom)] /// #[repr(C)] enum Bar { Z = 42 } /// /// let _ = <Bar as TransmuteFrom<Foo, NeglectValidity>::unsafe_transmute_from(Foo::N) // Compile error! /// ``` pub struct NeglectValidity; impl TransmuteOptions for NeglectValidity {} /* FILL: Implementations for tuple combinations of options */ // prevent third-party implementations of `TransmuteOptions` mod private { use super::*; pub trait Sealed {} impl Sealed for () {} impl Sealed for NeglectStability {} impl Sealed for NeglectAlignment {} impl Sealed for NeglectValidity {} /* FILL: Implementations for tuple combinations of options */ } } } /// **🌟** (Extension) Bit-altering conversions. /// /// This module demonstrates how the [transmute][module@transmute] API may be used to permit sound and complete slice casting and `Vec` casting. /// /// For more information on this extension, [**see here**](https://github.com/jswrenn/project-safe-transmute/blob/rfc/rfcs/0000-safe-transmute.md#case-study-abstractions-for-fast-parsing). #[cfg_attr(doc, unstable(feature = "cast", issue = "none"))] pub mod cast { use options::*; /// Cast `Self` into `Dst`. /// /// The reciprocal of [CastFrom]. This trait is implemented in terms of [CastFrom]. pub trait CastInto<Dst, Neglect=()> where Dst: CastFrom<Self, Neglect>, Neglect: CastOptions, { /// Cast `self` into a value of type `Dst`, safely. fn cast_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: SafeCastOptions, { CastFrom::<_, Neglect>::cast_from(self) } /// Cast `self` into a value of type `Dst`, potentially unsafely. unsafe fn unsafe_cast_into(self) -> Dst where Self: Sized, Dst: Sized, Neglect: CastOptions, { CastFrom::<_, Neglect>::unsafe_cast_from(self) } } impl<Src, Dst, Neglect> CastInto<Dst, Neglect> for Src where Dst: CastFrom<Self, Neglect>, Neglect: CastOptions, {} /// Instantiate `Self` from a value of type `Src`. /// /// The reciprocal of [CastInto]. pub trait CastFrom<Src: ?Sized, Neglect=()> where Neglect: CastOptions, { /// Instantiate `Self` by casting a value of type `Src`, safely. fn cast_from(src: Src) -> Self where Src: Sized, Self: Sized, Neglect: SafeCastOptions { unsafe { CastFrom::<_,Neglect>::unsafe_cast_from(src) } } /// Instantiate `Self` by casting a value of type `Src`, potentially safely. unsafe fn unsafe_cast_from(src: Src) -> Self where Src: Sized, Self: Sized, Neglect: CastOptions; } /// Options for casting. pub mod options { /// The super-trait of all *safe* casting options. #[marker] pub trait SafeCastOptions: CastOptions {} /// The super-trait of all casting options. #[marker] pub trait CastOptions {} impl SafeCastOptions for () {} impl CastOptions for () {} } } } use convert::transmute::*; /// Basic functions for dealing with memory. pub mod mem { #[doc(no_inline)] pub use core::mem::*; use crate::core::convert::transmute::{TransmuteFrom, stability::*, options::*}; /// Implemented if `align_of::<Self>() <= align_of::<Rhs>()` #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] pub trait AlignLtEq<Rhs, Neglect=()> where Neglect: TransmuteOptions, {} /// By wrapping a type in a zero-sized array, we neutralize its validity and size qualities. The only quality by which `[Lhs; 0]` and `[Dst; 0]` can differ is their alignment. We check *only* if the alignment of `Lhs` is less than `Rhs` by transmuting between references of these zero-sized gadgets. impl<Lhs, Rhs, Neglect> AlignLtEq<Rhs, Neglect> for Lhs where Neglect: TransmuteOptions, for<'a> &'a [Lhs; 0]: TransmuteFrom<&'a [Rhs; 0], Neglect> {} /// Implemented if `align_of::<Self>() == align_of::<Rhs>()` /// /// See the [`Vec` casting demonstration][super::convert::cast::CastFrom#impl-CastFrom<Vec<Src>%2C%20Neglect>-for-Vec<Dst>] for an example of its use. #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] pub trait AlignEq<Rhs, Neglect=()> where Neglect: TransmuteOptions, {} /// See [AlignLtEq]. impl<Lhs, Rhs, Neglect> AlignEq<Rhs, Neglect> for Lhs where Neglect: TransmuteOptions, Lhs: AlignLtEq<Rhs>, Rhs: AlignLtEq<Lhs>, {} mod private { use core::mem::MaybeUninit; // The alignment of this struct is always equal to `max(align_of::<A>(), align_of::<T>())`. // Its validity is always equal to `MaybeUninit<T>`. // Its size equals `T` /* #[derive(PromiseTransmutableFrom, PromiseTransmutableInto)] */ #[repr(C)] pub struct Aligned<A, T>(pub [A; 0], pub MaybeUninit<T>); } /// Implemented if `size_of::<Self>() <= size_of::<Rhs>()` #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] pub trait SizeLtEq<Rhs, Neglect=()> where Neglect: TransmuteOptions, {} /// We wrap the types in a struct that neutralizes their alignment and validity differences, leaving size as the only quality that might differ between `Aligned<Rhs, Lhs>` and `Aligned<Lhs, Rhs>`. #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] impl<Lhs, Rhs, Neglect> SizeLtEq<Rhs, Neglect> for Lhs where Neglect: TransmuteOptions, for<'a> &'a private::Aligned<Rhs, Lhs>: TransmuteFrom<&'a private::Aligned<Lhs, Rhs>>, {} /// Implemented if `size_of::<Self>() == size_of::<Rhs>()` /// /// See the [`Vec` casting demonstration][super::convert::cast::CastFrom#impl-CastFrom<Vec<Src>%2C%20Neglect>-for-Vec<Dst>] for an example of its use. #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] pub trait SizeEq<Rhs, Neglect=()> where Neglect: TransmuteOptions, {} /// See [SizeLtEq]. #[cfg_attr(doc, unstable(feature = "query", issue = "none"))] impl<Lhs, Rhs, Neglect> SizeEq<Rhs, Neglect> for Lhs where Neglect: TransmuteOptions, Lhs: SizeLtEq<Rhs>, Rhs: SizeLtEq<Lhs>, {} } /// A dynamically-sized view into a contiguous sequence, `[T]`. pub mod slice { #[doc(no_inline)] pub use core::slice::*; use crate::core::convert::{ transmute::{ TransmuteFrom, options::{SafeTransmuteOptions, TransmuteOptions}, }, cast::{ CastFrom, options::{ SafeCastOptions, CastOptions, }, }, }; use core::{ mem::{size_of, size_of_val}, slice }; /// **🌟** *Safe* options for casting **slices**. /// /// Slice casting transmutes the contents of the slice, and adjusts the slice's length as needed. All [SafeTransmuteOptions] are [SafeSliceCastOptions]. #[cfg_attr(doc, unstable(feature = "cast", issue = "none"))] pub trait SafeSliceCastOptions : SafeCastOptions + SafeTransmuteOptions + SliceCastOptions {} /// **🌟** Options for casting **slices**. /// /// Slice casting transmutes the contents of the slice, and adjusts the slice's length as needed. All [TransmuteOptions] are [SliceCastOptions]. #[cfg_attr(doc, unstable(feature = "cast", issue = "none"))] pub trait SliceCastOptions : CastOptions + TransmuteOptions {} impl<Neglect: SafeSliceCastOptions> SafeCastOptions for Neglect {} impl<Neglect: SafeTransmuteOptions> SafeSliceCastOptions for Neglect {} impl<Neglect: SliceCastOptions> CastOptions for Neglect {} impl<Neglect: TransmuteOptions> SliceCastOptions for Neglect {} /// #### `&[Src]` **🠮** `&[Dst]` /// If the sizes of `Src` and `Dst` differ, the length of the output slice is adjusted as-needed. /// /// ##### Static Options /// See [SliceCastOptions] and [SafeSliceCastOptions]. /// /// ##### Example /// ```rust /// let src : &[i8] = &[-1, -2, -3, -4][..]; /// let dst : &[[u8; 2]] = src.cast_into(); /// assert_eq!(dst, &[[-255, -254], [-253, -252]][..]); /// ``` impl<'i, 'o, Src, Dst, Neglect> CastFrom<&'i [Src], Neglect> for &'o [Dst] where Neglect: SliceCastOptions, &'o [Dst; 1]: TransmuteFrom<&'i [Src; usize::MAX], Neglect> { #[doc(hidden)] #[inline(always)] unsafe fn unsafe_cast_from(src: &'i [Src]) -> &'o [Dst] { let len = size_of_val(src).checked_div(size_of::<Dst>()).unwrap_or(0); unsafe { slice::from_raw_parts(src.as_ptr() as *const Dst, len) } } } /// #### `&mut [Src]` **🠮** `&mut [Dst]` /// If the sizes of `Src` and `Dst` differ, the length of the output slice is adjusted as-needed. /// /// ##### Static Options /// See [SliceCastOptions] and [SafeSliceCastOptions]. /// /// ##### Example /// ```rust /// let src : &mut [i8] = &mut [-1, -2, -3, -4][..]; /// let dst : &mut [[u8; 2]] = src.cast_into(); /// assert_eq!(dst, &mut [[-255, -254], [-253, -252]][..]); /// ``` impl<'i, 'o, Src, Dst, Neglect> CastFrom<&'i mut [Src], Neglect> for &'o mut [Dst] where Neglect: SliceCastOptions, &'o mut [Dst; 1]: TransmuteFrom<&'i mut [Src; usize::MAX], Neglect> { #[doc(hidden)] #[inline(always)] unsafe fn unsafe_cast_from(src: &'i mut [Src]) -> &'o mut [Dst] { let len = size_of_val(src).checked_div(size_of::<Dst>()).unwrap_or(0); unsafe { slice::from_raw_parts_mut(src.as_ptr() as *mut Dst, len) } } } /// #### `&mut [Src]` **🠮** `&[Dst]` /// If the sizes of `Src` and `Dst` differ, the length of the output slice is adjusted as-needed. /// /// ##### Static Options /// See [SliceCastOptions] and [SafeSliceCastOptions]. /// /// ##### Example /// ```rust /// let src : &mut [i8] = &mut [-1, -2, -3, -4][..]; /// let dst : &[[u8; 2]] = src.cast_into(); /// assert_eq!(dst, &[[-255, -254], [-253, -252]][..]); /// ``` impl<'i, 'o, Src, Dst, Neglect> CastFrom<&'i mut [Src], Neglect> for &'o [Dst] where Neglect: SliceCastOptions, &'o [Dst; 1]: TransmuteFrom<&'i mut [Src; usize::MAX], Neglect> { #[doc(hidden)] #[inline(always)] unsafe fn unsafe_cast_from(src: &'i mut [Src]) -> &'o [Dst] { let len = size_of_val(src).checked_div(size_of::<Dst>()).unwrap_or(0); unsafe { slice::from_raw_parts(src.as_ptr() as *const Dst, len) } } } } } /// Additions to `libstd` pub mod std { /// A contiguous growable array type with heap-allocated contents, `Vec<T>`. pub mod vec { #[doc(no_inline)] pub use std::vec::*; use crate::core::convert::{ transmute::{ TransmuteFrom, options::{SafeTransmuteOptions, TransmuteOptions, NeglectAlignment}, }, cast::{ CastFrom, options::{ SafeCastOptions, CastOptions, }, }, }; /// **🌟** Safe options for casting `Vec<T>` to `Vec<U>`. /// /// Vec casting transmutes the contents of the vec. All [SafeTransmuteOptions] are [SafeVecCastOptions]. /// /// See the [here][crate::core::convert::cast::CastFrom#impl-CastFrom<Vec<Src>%2C%20Neglect>-for-Vec<Dst>] for examples. #[cfg_attr(doc, unstable(feature = "cast", issue = "none"))] pub trait SafeVecCastOptions : SafeCastOptions + SafeTransmuteOptions + VecCastOptions {} /// **🌟** Options for casting `Vec<T>` to `Vec<U>`. /// /// Vec casting transmutes the contents of the vec. All [TransmuteOptions] are [VecCastOptions]. /// /// See the [here][crate::core::convert::cast::CastFrom#impl-CastFrom<Vec<Src>%2C%20Neglect>-for-Vec<Dst>] for examples. #[cfg_attr(doc, unstable(feature = "cast", issue = "none"))] pub trait VecCastOptions : TransmuteOptions + CastOptions {} impl<Neglect: SafeVecCastOptions> SafeCastOptions for Neglect {} impl<Neglect: SafeTransmuteOptions> SafeVecCastOptions for Neglect {} impl<Neglect: VecCastOptions> CastOptions for Neglect {} impl<Neglect: TransmuteOptions> VecCastOptions for Neglect {} use core::mem::MaybeUninit; use crate::core::mem::{SizeEq, AlignEq}; /// #### `Vec<Src>` **🠮** `Vec<Dst>` /// [`Vec::from_raw_parts`][Vec::from_raw_parts] requires that the size and static alignment of `Src` and `Dst` be equal. [NeglectAlignment] is therefore ignored. We use the [AlignEq] and [SizeEq] traits to enforce these invariants statically. /// ##### Static Options /// See [VecCastOptions] and [SafeVecCastOptions]. /// /// ##### Example /// ```rust /// let src : Vec<i8> = vec![-1, -2, -3, -4]; /// let dst : Vec<u8> = src.cast_into(); /// assert_eq!(dst, vec![255, 254, 253, 252]); /// ``` impl<Src, Dst, Neglect> CastFrom<Vec<Src>, Neglect> for Vec<Dst> where Neglect: VecCastOptions, Dst: TransmuteFrom<Src, Neglect> + AlignEq<Src, Neglect> + SizeEq<Src, Neglect>, { #[doc(hidden)] #[inline(always)] unsafe fn unsafe_cast_from(src: Vec<Src>) -> Vec<Dst> { let (ptr, len, cap) = src.into_raw_parts(); Vec::from_raw_parts(ptr as *mut Dst, len, cap) } } } }