git.delta.rocks / unique-network / refs/commits / 41e5db73da23

difftreelog

source

primitives/data-structs/src/budget.rs867 Bsourcehistory
1use sp_std::cell::Cell;23pub trait Budget {4	/// Returns true while not exceeded5	fn consume(&self) -> bool {6		self.consume_custom(1)7	}8	/// Returns true while not exceeded9	/// Implementations should use interior mutabilitiy10	fn consume_custom(&self, calls: u32) -> bool;11}1213pub struct Unlimited;14impl Budget for Unlimited {15	fn consume_custom(&self, _calls: u32) -> bool {16		true17	}18}1920pub struct Value(Cell<u32>);21impl Value {22	pub fn new(v: u32) -> Self {23		Self(Cell::new(v))24	}25	pub fn refund_amount(self) -> u32 {26		self.0.get()27	}28}29impl Budget for Value {30	fn consume_custom(&self, calls: u32) -> bool {31		let (result, overflown) = self.0.get().overflowing_sub(calls);32		if overflown {33			return false;34		}35		self.0.set(result);36		true37	}38}3940pub struct ZeroBudget;41impl Budget for ZeroBudget {42	fn consume_custom(&self, _calls: u32) -> bool {43		false44	}45}