diff --git a/core/embed/rust/src/micropython/gc.rs b/core/embed/rust/src/micropython/gc.rs index 3c0fe8e05c..ae29990eeb 100644 --- a/core/embed/rust/src/micropython/gc.rs +++ b/core/embed/rust/src/micropython/gc.rs @@ -9,11 +9,16 @@ use crate::error::Error; use super::ffi; /// A pointer type for values on the garbage-collected heap. -/// -/// Although a garbage-collected pointer type technically should implement -/// `Copy` and `Clone`, we avoid doing this until proven necessary. pub struct Gc(NonNull); +impl Clone for Gc { + fn clone(&self) -> Self { + *self + } +} + +impl Copy for Gc {} + impl Gc { /// Allocate memory on the heap managed by the MicroPython garbage collector /// and then place `v` into it. `v` will _not_ get its destructor called. @@ -100,6 +105,20 @@ impl Gc { // a mutable reference. unsafe { this.0.as_mut() } } + + /// Return a immutable reference to the value. + /// + /// # Safety + /// + /// `Gc` values can originate in the MicroPython interpreter, and these can + /// be both shared and mutable. Before calling this function, you have to + /// ensure that `this` does not get externally mutated and nobody + /// holds a mutable reference. + pub unsafe fn as_ref(this: &Self) -> &T { + // SAFETY: The caller must guarantee that `this` meets all the requirements for + // a immutable reference. + unsafe { this.0.as_ref() } + } } impl Deref for Gc {