From 6e39780b43e64975a79641ff9ec3aeb989a7aade Mon Sep 17 00:00:00 2001 From: Michel Heily Date: Fri, 29 May 2020 17:39:35 +0300 Subject: [PATCH] util: Add WeakPointer helper for passing around raw pointers Former-commit-id: eaab1057cf7bf8132ba7b59f6c5315e873064c30 Former-commit-id: 94f947733463b528dd3775d2bc6f55adebc36a2d --- core/src/sysbus.rs | 35 ++--------------------------------- core/src/util.rs | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 33 deletions(-) diff --git a/core/src/sysbus.rs b/core/src/sysbus.rs index f84395f..291bb5c 100644 --- a/core/src/sysbus.rs +++ b/core/src/sysbus.rs @@ -1,5 +1,4 @@ use std::fmt; -use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; @@ -7,6 +6,7 @@ use super::cartridge::Cartridge; use super::dma::DmaNotifer; use super::iodev::{IoDevices, WaitControl}; use super::{Addr, Bus}; +use super::util::WeakPointer; pub mod consts { pub const WORK_RAM_SIZE: usize = 256 * 1024; @@ -202,38 +202,7 @@ pub struct SysBus { pub trace_access: bool, } -#[repr(transparent)] -#[derive(Clone)] -pub struct SysBusPtr { - ptr: *mut SysBus, -} - -impl Default for SysBusPtr { - fn default() -> SysBusPtr { - SysBusPtr { - ptr: std::ptr::null_mut::(), - } - } -} - -impl SysBusPtr { - pub fn new(ptr: *mut SysBus) -> SysBusPtr { - SysBusPtr { ptr: ptr } - } -} - -impl Deref for SysBusPtr { - type Target = SysBus; - fn deref(&self) -> &Self::Target { - unsafe { &*self.ptr } - } -} - -impl DerefMut for SysBusPtr { - fn deref_mut(&mut self) -> &mut Self::Target { - unsafe { &mut *self.ptr } - } -} +pub type SysBusPtr = WeakPointer; macro_rules! memory_map { (read($sb:ident, $read_fn:ident, $addr:expr)) => { diff --git a/core/src/util.rs b/core/src/util.rs index b447bcc..e0217d4 100644 --- a/core/src/util.rs +++ b/core/src/util.rs @@ -1,7 +1,9 @@ use std::fs::File; use std::io; use std::io::prelude::*; +use std::ops::{Deref, DerefMut}; use std::path::Path; +use std::ptr; use std::time; @@ -153,3 +155,39 @@ pub mod audio { } } } + +#[repr(transparent)] +#[derive(Clone)] +/// Wrapper for passing raw pointers around. +/// Breaks compiler safety guaranties, so must be used with care. +pub struct WeakPointer { + ptr: *mut T, +} + +impl WeakPointer { + pub fn new(ptr: *mut T) -> Self { + WeakPointer { ptr } + } +} + +impl Deref for WeakPointer { + type Target = T; + + fn deref(&self) -> &T { + unsafe { &(*self.ptr) } + } +} + +impl DerefMut for WeakPointer { + fn deref_mut(&mut self) -> &mut T { + unsafe { &mut (*self.ptr) } + } +} + +impl Default for WeakPointer { + fn default() -> Self { + WeakPointer { + ptr: ptr::null_mut(), + } + } +}