1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-27 00:28:10 +00:00

refactor(core/rust): allow Copy and Clone for Gc

This is legal for garbage-collected pointers and we only avoided the
implementation due to being careful.

Now is the first time we need that functionality.

[no changelog]
This commit is contained in:
matejcik 2024-05-14 13:17:13 +02:00 committed by cepetr
parent 3d74e30fa7
commit 12ff2e4570

View File

@ -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<T: ?Sized>(NonNull<T>);
impl<T: ?Sized> Clone for Gc<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T: ?Sized> Copy for Gc<T> {}
impl<T> Gc<T> {
/// 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<T: ?Sized> Gc<T> {
// 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<T: ?Sized> Deref for Gc<T> {