Skip to content

Commit

Permalink
Remove dyn Any methods from Value
Browse files Browse the repository at this point in the history
  • Loading branch information
ryutamago authored and johnyob committed Oct 20, 2023
1 parent 48ab8c0 commit bb74205
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 42 deletions.
4 changes: 2 additions & 2 deletions jstz_core/src/kv/transaction.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,15 +85,15 @@ impl SnapshotEntry {
where
V: Value,
{
self.value.downcast_ref().unwrap()
self.value.as_any().downcast_ref().unwrap()
}

fn as_mut<V>(&mut self) -> &mut V
where
V: Value,
{
self.dirty = true;
self.value.downcast_mut().unwrap()
self.value.as_any_mut().downcast_mut().unwrap()
}

fn into_value<V>(self) -> V
Expand Down
46 changes: 6 additions & 40 deletions jstz_core/src/kv/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::any::{Any, TypeId};
use std::any::Any;
use std::fmt::Debug;

use bincode::Options;
Expand Down Expand Up @@ -35,51 +35,17 @@ pub trait Value: Any + Debug + erased_serde::Serialize {
fn as_any_mut(&mut self) -> &mut dyn Any;
}

impl<T> Value for T where T: Any + Debug + erased_serde::Serialize {
impl<T> Value for T
where
T: Any + Debug + erased_serde::Serialize,
{
fn as_any(&self) -> &dyn Any {
self
}

fn as_any_mut(&mut self) -> &mut dyn Any {
self
}

// Since trait downcasting isn't permitted, we implement all methods
// from `dyn Any`.
impl dyn Value {
pub fn is<T: Any>(&self) -> bool {
let t = TypeId::of::<T>();
let concrete = self.type_id();
t == concrete
}

pub unsafe fn downcast_ref_unchecked<T: Any>(&self) -> &T {
unsafe { &*(self as *const dyn Value as *const T) }
}

pub fn downcast_ref<T: Any>(&self) -> Option<&T> {
if self.is::<T>() {
unsafe { Some(self.downcast_ref_unchecked()) }
} else {
None
}
}

pub fn downcast_mut<T: Any>(&mut self) -> Option<&mut T> {
if self.is::<T>() {
unsafe { Some(self.downcast_mut_unchecked()) }
} else {
None
}
}

pub unsafe fn downcast_mut_unchecked<T: Any>(&mut self) -> &mut T {
unsafe { &mut *(self as *mut dyn Value as *mut T) }
}

pub fn serialize(&self) -> Vec<u8> {
serialize(self)
}
}

#[derive(Debug, Deref, DerefMut)]
Expand All @@ -99,7 +65,7 @@ impl BoxedValue {
where
T: Any,
{
if self.is::<T>() {
if self.as_any().is::<T>() {
Ok(unsafe { self.downcast_unchecked() })
} else {
Err(self)
Expand Down

0 comments on commit bb74205

Please sign in to comment.