forked from tari-project/tari
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoutput_set.rs
188 lines (162 loc) · 6.26 KB
/
output_set.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
// Copyright 2021, The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{
cmp::Ordering,
collections::BTreeSet,
iter::FromIterator,
ops::{Deref, DerefMut},
};
use crate::{covenants::error::CovenantError, transactions::transaction_components::TransactionOutput};
#[derive(Debug, Clone)]
/// Structure wrapping a set of `TransactionOutput` references.
pub struct OutputSet<'a>(BTreeSet<Indexed<&'a TransactionOutput>>);
impl<'a> OutputSet<'a> {
/// Produces a new `OutputSet` from a slice of `TransactionOutput`.
pub fn new(outputs: &'a [TransactionOutput]) -> Self {
// This sets the internal index for each output
// Note there is no publicly accessible way to modify the indexes
outputs.iter().enumerate().collect()
}
/// Returns the length of the underlying data slice of `OutputSet`.
pub fn len(&self) -> usize {
self.0.len()
}
/// Checks if the underlying data slice is empty.
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
/// Sets the current instance data of another instance.
pub fn set(&mut self, new_set: Self) {
*self = new_set;
}
/// Retains all outputs for which the given predicate f return true.
pub fn retain<F>(&mut self, mut f: F) -> Result<(), CovenantError>
where F: FnMut(&'a TransactionOutput) -> Result<bool, CovenantError> {
let mut err = None;
self.0.retain(|output| match f(output) {
Ok(b) => b,
Err(e) => {
// Theres no way to stop retain early, so keep the error for when this completes
err = Some(e);
false
},
});
match err {
Some(err) => Err(err),
None => Ok(()),
}
}
/// Union of two instances.
pub fn union(&self, other: &Self) -> Self {
self.0.union(&other.0).copied().collect()
}
/// Difference of two instances.
pub fn difference(&self, other: &Self) -> Self {
self.0.difference(&other.0).copied().collect()
}
/// Symmetric difference of two instances.
pub fn symmetric_difference(&self, other: &Self) -> Self {
self.0.symmetric_difference(&other.0).copied().collect()
}
/// Finds a single matching output, modifying the output set in place. If no matching output is found, the output
/// set will be empty.
pub fn find_inplace<F>(&mut self, mut pred: F)
where F: FnMut(&TransactionOutput) -> bool {
match self.0.iter().find(|indexed| pred(indexed)) {
Some(output) => {
let output = *output;
self.clear();
self.0.insert(output);
},
None => {
self.clear();
},
}
}
/// Clears an instance.
pub fn clear(&mut self) {
self.0.clear();
}
#[cfg(test)]
/// Get the `TransactionOutput` at `index`. Returns `None`, if there is none such `TransactionOutput`.
pub(super) fn get(&self, index: usize) -> Option<&TransactionOutput> {
self.0
.iter()
.find(|output| output.index == index)
.map(|output| **output)
}
#[cfg(test)]
/// Gets vector of corresponding indexes.
pub(super) fn get_selected_indexes(&self) -> Vec<usize> {
self.0.iter().map(|idx| idx.index).collect()
}
}
impl<'a> FromIterator<(usize, &'a TransactionOutput)> for OutputSet<'a> {
/// Produces a new `OutputSet` out of an appropriate iterator.
fn from_iter<T: IntoIterator<Item = (usize, &'a TransactionOutput)>>(iter: T) -> Self {
iter.into_iter().map(|(i, output)| Indexed::new(i, output)).collect()
}
}
impl<'a> FromIterator<Indexed<&'a TransactionOutput>> for OutputSet<'a> {
/// Produces a new `OutputSet` out of an appropriate iterator.
fn from_iter<T: IntoIterator<Item = Indexed<&'a TransactionOutput>>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
/// A simple wrapper struct that implements PartialEq and PartialOrd using a numeric index
#[derive(Debug, Clone, Copy)]
struct Indexed<T> {
index: usize,
value: T,
}
impl<T> Indexed<T> {
pub fn new(index: usize, value: T) -> Self {
Self { index, value }
}
}
impl<T> PartialEq for Indexed<T> {
fn eq(&self, other: &Self) -> bool {
self.index == other.index
}
}
impl<T> Eq for Indexed<T> {}
impl<T> PartialOrd for Indexed<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<T> Ord for Indexed<T> {
fn cmp(&self, other: &Self) -> Ordering {
self.index.cmp(&other.index)
}
}
impl<T> Deref for Indexed<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.value
}
}
impl<T> DerefMut for Indexed<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.value
}
}