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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2015-2020 Parity Technologies (UK) Ltd.
// This file is part of Tetsy Vapory.

// Tetsy Vapory is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Tetsy Vapory is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Tetsy Vapory.  If not, see <http://www.gnu.org/licenses/>.

//! Queue-like data structure including notion of usage.

/// Special queue-like data structure that includes the notion of
/// usage to avoid items that were queued but never used from making it into
/// the queue.
pub struct UsingQueue<T> {
	/// Not yet being sealed by a miner, but if one asks for work, we'd prefer they do this.
	pending: Option<T>,
	/// Currently being sealed by miners.
	in_use: Vec<T>,
	/// The maximum allowable number of items in_use.
	max_size: usize,
}

/// Take an item or just clone it?
pub enum GetAction {
	/// Remove the item, faster but you can't get it back.
	Take,
	/// Clone the item, slower but you can get it again.
	Clone,
}

impl<T> UsingQueue<T> {
	/// Create a new struct with a maximum size of `max_size`.
	pub fn new(max_size: usize) -> UsingQueue<T> {
		UsingQueue {
			pending: None,
			in_use: vec![],
			max_size,
		}
	}

	/// Return a reference to the item at the top of the queue (or `None` if the queue is empty);
	/// it doesn't constitute noting that the item is used.
	pub fn peek_last_ref(&self) -> Option<&T> {
		self.pending.as_ref().or(self.in_use.last())
	}

	/// Return a reference to the item at the top of the queue (or `None` if the queue is empty);
	/// this constitutes using the item and will remain in the queue for at least another
	/// `max_size` invocations of `set_pending() + use_last_ref()`.
	pub fn use_last_ref(&mut self) -> Option<&T> {
		if let Some(x) = self.pending.take() {
			self.in_use.push(x);
			if self.in_use.len() > self.max_size {
				self.in_use.remove(0);
			}
		}
		self.in_use.last()
	}

	/// Place an item on the end of the queue. The previously pending item will be removed
	/// if `use_last_ref()` since it was set.
	pub fn set_pending(&mut self, b: T) {
		self.pending = Some(b);
	}

	/// Is there anything in the queue currently?
	pub fn is_in_use(&self) -> bool { self.in_use.len() > 0 }

	/// Clears everything; the queue is entirely reset.
	pub fn reset(&mut self) {
		self.pending = None;
		self.in_use.clear();
	}

	/// Returns `Some` item which is the first that `f` returns `true` with a reference to it
	/// as a parameter or `None` if no such item exists in the queue.
	fn take_used_if<P>(&mut self, predicate: P) -> Option<T> where P: Fn(&T) -> bool {
		self.in_use.iter().position(|r| predicate(r)).map(|i| self.in_use.remove(i))
	}

	/// Returns `Some` item which is the first that `f` returns `true` with a reference to it
	/// as a parameter or `None` if no such item exists in the queue.
	fn clone_used_if<P>(&mut self, predicate: P) -> Option<T> where P: Fn(&T) -> bool, T: Clone {
		self.in_use.iter().find(|r| predicate(r)).cloned()
	}

	/// Fork-function for `take_used_if` and `clone_used_if`.
	pub fn get_used_if<P>(&mut self, action: GetAction, predicate: P) -> Option<T> where P: Fn(&T) -> bool, T: Clone {
		match action {
			GetAction::Take => self.take_used_if(predicate),
			GetAction::Clone => self.clone_used_if(predicate),
		}
	}

	/// Returns a clone of the pending block if `f` returns `true` with a reference to it as
	/// a parameter, otherwise `None`.
	///
	/// If pending block is not available will clone the first of the used blocks that match the predicate.
	pub fn get_pending_if<P>(&mut self, predicate: P) -> Option<T> where P: Fn(&T) -> bool, T: Clone {
		// a bit clumsy - TODO: think about a nicer way of expressing this.
		if let Some(ref x) = self.pending {
			if predicate(x) {
				Some(x.clone())
			} else {
				None
			}
		} else {
			self.in_use.last().into_iter().filter(|x| predicate(x)).next().cloned()
		}
	}
}

#[test]
fn should_not_find_when_pushed() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	assert!(q.take_used_if(|i| i == &1).is_none());
}

#[test]
fn should_not_find_when_pushed_with_clone() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	assert!(q.clone_used_if(|i| i == &1).is_none());
}

#[test]
fn should_find_when_pushed_and_used() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).unwrap() == 1);
}

#[test]
fn should_have_same_semantics_for_get_take_clone() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	assert!(q.get_used_if(GetAction::Clone, |i| i == &1).is_none());
	assert!(q.get_used_if(GetAction::Take, |i| i == &1).is_none());
	q.use_last_ref();
	assert!(q.get_used_if(GetAction::Clone, |i| i == &1).unwrap() == 1);
	assert!(q.get_used_if(GetAction::Clone, |i| i == &1).unwrap() == 1);
	assert!(q.get_used_if(GetAction::Take, |i| i == &1).unwrap() == 1);
	assert!(q.get_used_if(GetAction::Clone, |i| i == &1).is_none());
	assert!(q.get_used_if(GetAction::Take, |i| i == &1).is_none());
}

#[test]
fn should_find_when_pushed_and_used_with_clone() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	q.use_last_ref();
	assert!(q.clone_used_if(|i| i == &1).unwrap() == 1);
}

#[test]
fn should_not_find_again_when_pushed_and_taken() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).unwrap() == 1);
	assert!(q.clone_used_if(|i| i == &1).is_none());
}

#[test]
fn should_find_again_when_pushed_and_cloned() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	q.use_last_ref();
	assert!(q.clone_used_if(|i| i == &1).unwrap() == 1);
	assert!(q.clone_used_if(|i| i == &1).unwrap() == 1);
	assert!(q.take_used_if(|i| i == &1).unwrap() == 1);
}

#[test]
fn should_find_when_others_used() {
	let mut q = UsingQueue::new(2);
	q.set_pending(1);
	q.use_last_ref();
	q.set_pending(2);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).is_some());
}

#[test]
fn should_not_find_when_too_many_used() {
	let mut q = UsingQueue::new(1);
	q.set_pending(1);
	q.use_last_ref();
	q.set_pending(2);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).is_none());
}

#[test]
fn should_not_find_when_not_used_and_then_pushed() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	q.set_pending(2);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).is_none());
}

#[test]
fn should_peek_correctly_after_push() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	assert_eq!(q.peek_last_ref(), Some(&1));
	q.set_pending(2);
	assert_eq!(q.peek_last_ref(), Some(&2));
}

#[test]
fn should_inspect_correctly() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	assert_eq!(q.use_last_ref(), Some(&1));
	assert_eq!(q.peek_last_ref(), Some(&1));
	q.set_pending(2);
	assert_eq!(q.use_last_ref(), Some(&2));
	assert_eq!(q.peek_last_ref(), Some(&2));
}

#[test]
fn should_not_find_when_not_used_peeked_and_then_pushed() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	q.peek_last_ref();
	q.set_pending(2);
	q.use_last_ref();
	assert!(q.take_used_if(|i| i == &1).is_none());
}

#[test]
fn should_pop_used() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	q.use_last_ref();
	let popped = q.get_pending_if(|i| i == &1);
	assert_eq!(popped, Some(1));
}

#[test]
fn should_not_pop_last_pending() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	assert_eq!(q.get_pending_if(|i| i == &1), Some(1));
	assert_eq!(q.get_pending_if(|i| i == &1), Some(1));
}

#[test]
fn should_not_pop_unused_before_used() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	q.set_pending(2);
	let popped = q.get_pending_if(|i| i == &1);
	assert_eq!(popped, None);
}

#[test]
fn should_not_remove_used_popped() {
	let mut q = UsingQueue::new(3);
	q.set_pending(1);
	q.use_last_ref();
	assert_eq!(q.get_pending_if(|i| i == &1), Some(1));
	assert_eq!(q.get_pending_if(|i| i == &1), Some(1));
}