Skip to content

Commit

Permalink
Add 81974
Browse files Browse the repository at this point in the history
Most likely low-priority; feel free to ignore

Issue: rust-lang/rust#81974
  • Loading branch information
fanninpm committed Feb 11, 2021
1 parent b156372 commit 5f160a0
Showing 1 changed file with 51 additions and 0 deletions.
51 changes: 51 additions & 0 deletions ices/81974.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
#![feature(unboxed_closures)]
#![feature(fn_traits)]

use std::collections::HashMap;
use std::hash::Hash;

struct CachedFun<A, B>{
cache: HashMap<A, B>,
fun: fn(&mut CachedFun<A, B>, A) -> B
}

impl<A: Eq + Hash, B> CachedFun<A, B> {
fn new(fun: fn(&mut Self, A) -> B) -> Self {
CachedFun {
cache: HashMap::new(),
fun
}
}
}

impl<A, B> FnOnce<A> for CachedFun<A, B> where
A: Eq + Hash + Clone,
B: Clone,
{
type Output = B;
extern "rust-call" fn call_once(mut self, a: A) -> Self::Output {
self.call_mut(a)
}
}


impl<A, B> FnMut<A> for CachedFun<A, B> where
A: Eq + Hash + Clone,
B: Clone,
{
extern "rust-call" fn call_mut(&mut self, a: A) -> Self::Output {
self.cache.get(&a)
.map(|a| a.clone())
.unwrap_or_else(|| {
let b = (self.fun)(self, a.clone());
self.cache.insert(a, b.clone());
b
})
}
}

fn main() -> () {
let pesce = |y: &mut CachedFun<i32, i32>, x| x + 1;
let cachedcoso = CachedFun::new(pesce);
cachedcoso.call_once(1);
}

0 comments on commit 5f160a0

Please sign in to comment.