iota_bundle_preview/bundle/
bundle.rs

1use crate::transaction::{
2    Address,
3    Hash,
4    Transaction,
5    TransactionField,
6    Transactions,
7};
8
9use std::collections::HashMap;
10
11pub struct Bundle(pub(crate) Transactions);
12
13impl Bundle {
14    // TODO TEST
15    pub fn get(&self, index: usize) -> Option<&Transaction> {
16        self.0.get(index)
17    }
18
19    // TODO TEST
20    pub fn len(&self) -> usize {
21        self.0.len()
22    }
23
24    // TODO TEST
25    pub fn hash(&self) -> &Hash {
26        // Safe to unwrap because empty bundles can't be built
27        self.get(0).unwrap().bundle()
28    }
29
30    // TODO TEST
31    pub fn tail(&self) -> &Transaction {
32        // Safe to unwrap because empty bundles can't be built
33        self.get(0).unwrap()
34    }
35
36    // TODO TEST
37    pub fn head(&self) -> &Transaction {
38        // Safe to unwrap because empty bundles can't be built
39        self.get(self.len() - 1).unwrap()
40    }
41
42    // TODO TEST
43    pub fn trunk(&self) -> &Hash {
44        self.head().trunk()
45    }
46
47    // TODO TEST
48    pub fn branch(&self) -> &Hash {
49        self.head().branch()
50    }
51
52    // TODO TEST
53    pub fn ledger_diff(&self) -> HashMap<Address, i64> {
54        let mut diff = HashMap::new();
55
56        for transaction in self {
57            if *transaction.value.to_inner() != 0 {
58                *diff.entry(transaction.address().clone()).or_insert(0) += *transaction.value.to_inner();
59            }
60        }
61
62        diff
63    }
64}
65
66impl IntoIterator for Bundle {
67    type Item = Transaction;
68    type IntoIter = std::vec::IntoIter<Transaction>;
69
70    // TODO TEST
71    fn into_iter(self) -> Self::IntoIter {
72        (self.0).0.into_iter()
73    }
74}
75
76impl<'a> IntoIterator for &'a Bundle {
77    type Item = &'a Transaction;
78    type IntoIter = std::slice::Iter<'a, Transaction>;
79
80    // TODO TEST
81    fn into_iter(self) -> Self::IntoIter {
82        (&(self.0).0).into_iter()
83    }
84}
85
86impl std::ops::Index<usize> for Bundle {
87    type Output = Transaction;
88
89    // TODO TEST
90    fn index(&self, index: usize) -> &Self::Output {
91        // Unwrap because index is expected to panic if out of range
92        self.get(index).unwrap()
93    }
94}
95
96#[cfg(test)]
97mod tests {}