在 Rust 中迈向安全的嬗变

  • Ready to give LWN a try?: Offer a free trial subscription to LWN without a credit card. Stay updated in the Linux and free-software community and access subscriber-only features.
  • Rust's transmute issue: In Rust, there's no efficient and safe way to convert an array of bytes to a corresponding structure. Jack Wrenn's talk at RustConf focused on this, aiming to make "transmute" (conversion) safer.

    • Invariants to consider: Bit validity (whether bit patterns are valid between types), alignment (types must be aligned to a particular boundary), lifetimes (ensuring no lifetime issues), and safety invariants upheld by constructors.
  • Existing crates: Several crates like bytemuck and zerocopy provide safe abstractions around transmute. They add a marker trait that requires the programmer to ensure type meets the library's requirements.
  • "Project Safe Transmute": Created to bring native support for safe transmute to the Rust compiler. It uses a "theory of type alchemy" with finite-state machines to model types and automatically implements a TransmuteFrom trait.

    • Added generic parameters to handle user-defined types with safety requirements. The programmer can use Assume::SAFETY to promise the compiler about safety.
  • Future outlook: Need to support dynamically sized types, add an API for fallible transmutation, optimize bit-validity checks, improve type layout portability, and stabilize the work. Hopes for an RFC in 2025 after testing and feedback.
阅读 16
0 条评论