Created
May 24, 2023 20:41
-
-
Save aidenfoxivey/5e7df96eebd2ab53da37d298f6ff6f00 to your computer and use it in GitHub Desktop.
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::cell::{RefCell, RefMut}; | |
use std::collections::HashMap; | |
use std::rc::Rc; | |
pub use num::{One, Zero}; | |
use std::cmp::PartialEq; | |
pub use std::ops::{Add, Mul}; | |
pub trait Numeric: Zero + One + Copy + Clone + Mul + Add + PartialEq + std::fmt::Debug {} | |
// https://stackoverflow.com/questions/42381185/specifying-generic-parameter-to-belong-to-a-small-set-of-types | |
macro_rules! numeric_impl { | |
($($t: ty),+) => { | |
$( | |
impl Numeric for $t {} | |
)+ | |
} | |
} | |
numeric_impl!(usize, u8, u32, u64, u128, i8, i32, i64, i128, f32, f64); | |
pub struct Tensor<T: Numeric>(Rc<RefCell<InternalTensor<T>>>); | |
pub struct InternalTensor<T> where T: Numeric { | |
contents: Vec<T>, | |
grad: Vec<T>, | |
next: Vec<Tensor<T>>, | |
} | |
fn main() { | |
let shared_map: Rc<RefCell<_>> = Rc::new(RefCell::new(HashMap::new())); | |
// Create a new block to limit the scope of the dynamic borrow | |
{ | |
let mut map: RefMut<_> = shared_map.borrow_mut(); | |
map.insert("africa", 92388); | |
map.insert("kyoto", 11837); | |
map.insert("piccadilly", 11826); | |
map.insert("marbles", 38); | |
} | |
// Note that if we had not let the previous borrow of the cache fall out | |
// of scope then the subsequent borrow would cause a dynamic thread panic. | |
// This is the major hazard of using `RefCell`. | |
let total: i32 = shared_map.borrow().values().sum(); | |
println!("{total}"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment