totally_sync_variable/
lib.rs1#![deny(unsafe_code)]
15#![allow(dead_code)]
16use serde::{de::DeserializeOwned, Serialize};
17use std::fs;
18use std::io::{BufReader, BufWriter};
19use std::marker::PhantomData;
20use std::ops::*;
21use std::path::Path;
22
23pub struct Var<T>(&'static str, PhantomData<T>);
25
26impl<T> Var<T> {
27 pub fn new(name: &'static str) -> Self {
29 Self(name, PhantomData::default())
30 }
31}
32
33impl<T: Serialize> Var<T> {
34 pub fn set(&self, v: &T) {
41 let f = BufWriter::new(
42 fs::File::create(Path::new("/tmp/").join(self.0)).expect("become linux!"),
43 );
44 serde_json::to_writer(f, v).unwrap();
45 }
46}
47
48impl<T: DeserializeOwned> Var<T> {
49 pub fn get(&self) -> T {
56 let f = BufReader::new(fs::File::open(Path::new("/tmp/").join(self.0)).expect("oh no"));
57 serde_json::from_reader(f).unwrap()
58 }
59}
60
61macro_rules! op {
62 ($op: ident, $char: tt) => {paste::paste! {
63 impl<T: [<$op>]<T, Output = T> + Clone + DeserializeOwned + Serialize> [<$op Assign>] for Var<T> {
64 fn [<$op:lower _assign>](&mut self, rhs: Self) {
65 self.set(&(self.get().clone() $char rhs.get().clone()));
66 }
67 }
68
69 impl<T: [<$op>]<T, Output = T> + Clone + DeserializeOwned + Serialize> [<$op Assign>]<T> for Var<T> {
70 fn [<$op:lower _assign>](&mut self, rhs: T) {
71 self.set(&(self.get().clone() $char rhs));
72 }
73 }
74 }};
75}
76
77op!(Add, +);
78op!(Sub, -);
79op!(Mul, *);
80op!(Div, /);
81op!(BitAnd, &);
82op!(BitOr, |);
83op!(BitXor, ^);
84op!(Shl, <<);
85op!(Shr, >>);
86op!(Rem, %);
87
88#[macro_export]
89macro_rules! def {
95 ($name:ident = $value:expr) => {{
96 let v = $crate::Var::new(stringify!($name));
97 v.set(&$value);
98 v
99 }};
100}
101
102#[macro_export]
103macro_rules! refer {
113 ($name:ident) => {
114 $crate::Var::new(stringify!($name)).get()
115 };
116}
117
118#[test]
119fn it_works() {
120 {
121 let mut x = def!(x = 4u8);
122 x += 4;
123 assert_eq!(x.get(), 8);
124 }
125 let v: u8 = refer!(x);
126 assert_eq!(v, 8)
127}