chia_sdk_driver/action_system/
deltas.rs1use std::{
2 collections::{HashMap, HashSet},
3 ops::{Add, AddAssign, Neg},
4};
5
6use crate::{Action, Id, SpendAction};
7
8#[derive(Debug, Default, Clone)]
9pub struct Deltas {
10 items: HashMap<Id, Delta>,
11 needed: HashSet<Id>,
12}
13
14impl Deltas {
15 pub fn new() -> Self {
16 Self::default()
17 }
18
19 pub fn from_actions(actions: &[Action]) -> Self {
20 let mut deltas = Self::new();
21 for (index, action) in actions.iter().enumerate() {
22 action.calculate_delta(&mut deltas, index);
23 }
24 deltas
25 }
26
27 pub fn ids(&self) -> impl Iterator<Item = &Id> {
28 self.items.keys()
29 }
30
31 pub fn get(&self, id: &Id) -> Option<&Delta> {
32 self.items.get(id)
33 }
34
35 pub fn update(&mut self, id: Id) -> &mut Delta {
36 self.items.entry(id).or_default()
37 }
38
39 pub fn set_needed(&mut self, id: Id) {
40 self.needed.insert(id);
41 }
42
43 pub fn is_needed(&self, id: &Id) -> bool {
44 self.needed.contains(id)
45 }
46}
47
48#[derive(Debug, Default, Clone, Copy)]
49pub struct Delta {
50 pub input: u64,
51 pub output: u64,
52}
53
54impl Delta {
55 pub fn new(input: u64, output: u64) -> Self {
56 Self { input, output }
57 }
58}
59
60impl Add for Delta {
61 type Output = Self;
62
63 fn add(self, rhs: Self) -> Self::Output {
64 Self {
65 input: self.input + rhs.input,
66 output: self.output + rhs.output,
67 }
68 }
69}
70
71impl AddAssign for Delta {
72 fn add_assign(&mut self, rhs: Self) {
73 *self = *self + rhs;
74 }
75}
76
77impl Neg for Delta {
78 type Output = Self;
79
80 fn neg(self) -> Self::Output {
81 Self {
82 input: self.output,
83 output: self.input,
84 }
85 }
86}