-
-
Save therustmonk/15e15d3261ceb20fa3b7ecbf09629d64 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::marker::PhantomData; | |
use std::convert::TryInto; | |
use std::sync::Arc; | |
use std::ops::Deref; | |
use std::sync::mpsc::channel; | |
#[derive(Debug)] | |
struct MsgOne { | |
} | |
#[derive(Debug)] | |
struct MsgTwo { | |
} | |
#[derive(Debug)] | |
enum GreatWrapper { | |
One(MsgOne), | |
Two(MsgTwo), | |
Many(Vec<GreatWrapper>), | |
} | |
impl<'a> TryInto<&'a MsgOne> for &'a GreatWrapper { | |
type Error = (); | |
fn try_into(self) -> Result<&'a MsgOne, Self::Error> { | |
if let GreatWrapper::One(ref msg) = self { Ok(msg) } else { Err(()) } | |
} | |
} | |
impl<'a> TryInto<&'a MsgTwo> for &'a GreatWrapper { | |
type Error = (); | |
fn try_into(self) -> Result<&'a MsgTwo, Self::Error> { | |
if let GreatWrapper::Two(ref msg) = self { Ok(msg) } else { Err(()) } | |
} | |
} | |
trait GetFastAccess { | |
fn fast_access<T>(&self, idx: usize) -> FastAccess<T>; | |
} | |
impl GetFastAccess for Arc<GreatWrapper> { | |
fn fast_access<T>(&self, idx: usize) -> FastAccess<T> { | |
FastAccess { | |
base: Arc::clone(self), | |
idx, | |
_type: PhantomData, | |
} | |
} | |
} | |
struct FastAccess<T> { | |
base: Arc<GreatWrapper>, | |
idx: usize, | |
_type: PhantomData<T>, | |
} | |
impl<T> Deref for FastAccess<T> | |
where | |
for<'l> &'l GreatWrapper: TryInto<&'l T, Error= ()>, | |
{ | |
type Target = T; | |
fn deref(&self) -> &Self::Target { | |
if let GreatWrapper::Many(ref vec) = &*self.base { | |
(&vec[self.idx]).try_into().unwrap() | |
} else { | |
unreachable!(); | |
} | |
} | |
} | |
fn main() { | |
let (tx, rx) = channel(); | |
let one = GreatWrapper::One(MsgOne {}); | |
let two = GreatWrapper::Two(MsgTwo {}); | |
let bunch = Arc::new(GreatWrapper::Many(vec![one, two])); | |
let fa = bunch.fast_access::<MsgTwo>(1); | |
tx.send(fa).unwrap(); | |
let bunch_with_idx = rx.recv().unwrap(); | |
println!("Dereferenced to: {:?}", &*bunch_with_idx); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment