Skip to content

Commit

Permalink
fix: impl cast/cast_mut for Snapshot
Browse files Browse the repository at this point in the history
  • Loading branch information
ynqa committed Mar 16, 2024
1 parent c1e3c3b commit edaed85
Showing 1 changed file with 23 additions and 2 deletions.
25 changes: 23 additions & 2 deletions src/snapshot.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use std::{
any::Any,
any::{type_name, Any},
cell::{Ref, RefCell},
};

use crate::{pane::Pane, AsAny, Renderer};
use crate::{pane::Pane, AsAny, Error, Renderer, Result};

/// A `Snapshot` struct captures the state of a renderer at three different points:
/// initial (`init`), before any changes (`before`), and after changes have been applied (`after`).
/// It is generic over `R` where `R` must implement the `Renderer` and `Clone` traits.
Expand All @@ -22,6 +23,7 @@ impl<R: Renderer + Clone + 'static> Renderer for Snapshot<R> {
}
}

// TODO: enable Snapshot<R> to use impl_as_any macro.
impl<R: Renderer + Clone + 'static> AsAny for Snapshot<R> {
fn as_any(&self) -> &dyn Any {
self
Expand All @@ -32,6 +34,25 @@ impl<R: Renderer + Clone + 'static> AsAny for Snapshot<R> {
}
}

// TODO: enable Snapshot<R> to use impl_cast macro.
impl<R: Renderer + Clone + 'static> Snapshot<R> {
pub fn cast_mut(renderer: &mut dyn crate::Renderer) -> Result<&mut Self> {
let snapshot = renderer
.as_any_mut()
.downcast_mut::<Self>()
.ok_or_else(|| Error::DowncastError(type_name::<Self>().to_string()))?;
Ok(snapshot)
}

pub fn cast(renderer: &dyn crate::Renderer) -> Result<&Self> {
let snapshot = renderer
.as_any()
.downcast_ref::<Self>()
.ok_or_else(|| Error::DowncastError(type_name::<Self>().to_string()))?;
Ok(snapshot)
}
}

impl<R: Renderer + Clone + 'static> Snapshot<R> {
/// Constructs a new `Snapshot` instance with the given renderer. The `init`, `before`, and
/// `after` states are all initialized with clones of the provided renderer.
Expand Down

0 comments on commit edaed85

Please sign in to comment.