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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
use std::ops::Index;
use std::collections::{VecDeque, HashSet};
use std::iter::repeat;
use primitives::hash::H256;

/// Block position
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum HashPosition {
	/// Block is not in the queue
	Missing,
	/// Block is at the front of the queue
	Front,
	/// Block is somewhere inside in the queue
	Inside(u32),
}

/// Ordered queue with O(1) contains() && random access operations cost.
#[derive(Debug, Clone)]
pub struct HashQueue {
	queue: VecDeque<H256>,
	set: HashSet<H256>,
}

/// Chain of linked queues. First queue has index zero.
#[derive(Debug)]
pub struct HashQueueChain {
	chain: Vec<HashQueue>,
}

impl HashQueue {
	pub fn new() -> Self {
		HashQueue {
			queue: VecDeque::new(),
			set: HashSet::new(),
		}
	}

	/// Clears the queue
	pub fn clear(&mut self) {
		self.set.clear();
		self.queue.clear();
	}

	/// Returns len of the given queue.
	pub fn len(&self) -> u32 {
		self.queue.len() as u32
	}

	/// Returns front element from the given queue.
	pub fn front(&self) -> Option<H256> {
		self.queue.front().cloned()
	}

	/// Returns back element from the given queue.
	pub fn back(&self) -> Option<H256> {
		self.queue.back().cloned()
	}

	/// Returns position of the element in the queue
	pub fn position(&self, hash: &H256) -> Option<u32> {
		self.queue.iter().enumerate()
			.filter_map(|(pos, h)| if hash == h { Some(pos as u32) } else { None })
			.nth(0)
	}

	/// Returns element at position
	pub fn at(&self, position: u32) -> Option<H256> {
		self.queue.get(position as usize).cloned()
	}

	/// Returns previous-to back element from the given queue.
	pub fn pre_back(&self) -> Option<H256> {
		let queue_len = self.queue.len();
		if queue_len <= 1 {
			return None;
		}
		Some(self.queue[queue_len - 2].clone())
	}

	/// Returns true if queue contains element.
	pub fn contains(&self, hash: &H256) -> bool {
		self.set.contains(hash)
	}

	/// Returns n elements from the front of the queue
	pub fn front_n(&self, n: u32) -> Vec<H256> {
		self.queue.iter().cloned().take(n as usize).collect()
	}

	/// Removes element from the front of the queue.
	pub fn pop_front(&mut self) -> Option<H256> {
		match self.queue.pop_front() {
			Some(hash) => {
				self.set.remove(&hash);
				Some(hash)
			},
			None => None,
		}
	}

	/// Removes n elements from the front of the queue.
	pub fn pop_front_n(&mut self, n: u32) -> Vec<H256> {
		let mut result: Vec<H256> = Vec::new();
		for _ in 0..n {
			match self.pop_front() {
				Some(hash) => result.push(hash),
				None => return result,
			}
		}
		result
	}

	/// Removes element from the back of the queue.
	pub fn pop_back(&mut self) -> Option<H256> {
		match self.queue.pop_back() {
			Some(hash) => {
				self.set.remove(&hash);
				Some(hash)
			},
			None => None,
		}
	}


	/// Adds element to the back of the queue.
	pub fn push_back(&mut self, hash: H256) {
		if !self.set.insert(hash.clone()) {
			panic!("must be checked by caller");
		}
		self.queue.push_back(hash);
	}

	/// Adds elements to the back of the queue.
	pub fn push_back_n(&mut self, hashes: Vec<H256>) {
		for hash in hashes {
			self.push_back(hash);
		}
	}

	/// Removes element from the queue, returning its position.
	pub fn remove(&mut self, hash: &H256) -> HashPosition {
		if !self.set.remove(hash) {
			return HashPosition::Missing;
		}

		if self.queue.front().expect("checked one line above") == hash {
			self.queue.pop_front();
			return HashPosition::Front;
		}

		for i in 0..self.queue.len() {
			if self.queue[i] == *hash {
				self.queue.remove(i);
				return HashPosition::Inside(i as u32);
			}
		}

		// unreachable because hash is not missing, not at the front and not inside
		unreachable!()
	}

	/// Removes all elements from the queue.
	pub fn remove_all(&mut self) -> VecDeque<H256> {
		use std::mem::replace;

		self.set.clear();
		replace(&mut self.queue, VecDeque::new())
	}
}

impl Index<u32> for HashQueue {
	type Output = H256;

	fn index(&self, index: u32) -> &Self::Output {
		&self.queue[index as usize]
	}
}

impl HashQueueChain {
	/// Creates chain with given number of queues.
	pub fn with_number_of_queues(number_of_queues: usize) -> Self {
		assert!(number_of_queues != 0);
		HashQueueChain {
			chain: repeat(HashQueue::new()).take(number_of_queues).collect(),
		}
	}

	/// Returns length of the whole chain.
	pub fn len(&self) -> u32 {
		self.chain.iter().fold(0, |total, chain| total + chain.len())
	}

	/// Returns length of the given queue.
	pub fn len_of(&self, queue_index: usize) -> u32 {
		self.chain[queue_index].len()
	}

	/// Returns element at the given position
	pub fn at(&self, mut index: u32) -> Option<H256> {
		for queue in &self.chain {
			let queue_len = queue.len();
			if index < queue_len {
				return queue.at(index);
			}

			index -= queue_len;
		}

		None
	}

	/// Returns element at the front of the given queue.
	pub fn front_at(&self, queue_index: usize) -> Option<H256> {
		let queue = &self.chain[queue_index];
		queue.front()
	}

	/// Returns element at the front of the given queue.
	pub fn back_at(&self, queue_index: usize) -> Option<H256> {
		let queue = &self.chain[queue_index];
		queue.back()
	}

	/// Returns previous-to back element from the given queue.
	pub fn pre_back_at(&self, chain_index: usize) -> Option<H256> {
		let queue = &self.chain[chain_index];
		queue.pre_back()
	}

	/// Returns the back of the whole chain.
	pub fn back(&self) -> Option<H256> {
		let mut queue_index = self.chain.len() - 1;
		loop {
			let queue = &self.chain[queue_index];
			let queue_back = queue.back();
			if queue_back.is_some() {
				return queue_back;
			}

			queue_index -= 1;
			if queue_index == 0 {
				return None;
			}
		}
	}

	/// Checks if hash is contained in given queue.
	#[cfg(test)]
	pub fn is_contained_in(&self, queue_index: usize, hash: &H256) -> bool {
		self.chain[queue_index].contains(hash)
	}

	/// Returns the index of queue, hash is contained in.
	pub fn contains_in(&self, hash: &H256) -> Option<usize> {
		for i in 0..self.chain.len() {
			if self.chain[i].contains(hash) {
				return Some(i);
			}
		}
		None
	}

	/// Returns n elements from the front of the given queue
	pub fn front_n_at(&self, queue_index: usize, n: u32) -> Vec<H256> {
		self.chain[queue_index].front_n(n)
	}

	/// Remove a number of hashes from the front of the given queue.
	pub fn pop_front_n_at(&mut self, queue_index: usize, n: u32) -> Vec<H256> {
		self.chain[queue_index].pop_front_n(n)
	}

	/// Push hash onto the back of the given queue.
	pub fn push_back_at(&mut self, queue_index: usize, hash: H256) {
		self.chain[queue_index].push_back(hash)
	}

	/// Push a number of hashes onto the back of the given queue.
	pub fn push_back_n_at(&mut self, queue_index: usize, hashes: Vec<H256>) {
		self.chain[queue_index].push_back_n(hashes)
	}

	/// Remove hash from given queue.
	pub fn remove_at(&mut self, queue_index: usize, hash: &H256) -> HashPosition {
		self.chain[queue_index].remove(hash)
	}

	/// Remove all items from given queue.
	pub fn remove_all_at(&mut self, queue_index: usize) -> VecDeque<H256> {
		self.chain[queue_index].remove_all()
	}
}

impl Index<u32> for HashQueueChain {
	type Output = H256;

	fn index(&self, mut index: u32) -> &Self::Output {
		for queue in &self.chain {
			let queue_len = queue.len();
			if index < queue_len {
				return &queue[index];
			}

			index -= queue_len;
		}

		panic!("invalid index");
	}
}

#[cfg(test)]
mod tests {
	use super::{HashQueue, HashQueueChain, HashPosition};
	use primitives::hash::H256;

	#[test]
	fn hash_queue_empty() {
		let mut queue = HashQueue::new();
		assert_eq!(queue.len(), 0);
		assert_eq!(queue.front(), None);
		assert_eq!(queue.back(), None);
		assert_eq!(queue.pre_back(), None);
		assert_eq!(queue.contains(&"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".into()), false);
		assert_eq!(queue.pop_front(), None);
		assert_eq!(queue.pop_front_n(100), vec![]);
		assert_eq!(queue.remove(&"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".into()), HashPosition::Missing);
	}

	#[test]
	fn hash_queue_chain_empty() {
		let mut chain = HashQueueChain::with_number_of_queues(3);
		assert_eq!(chain.len(), 0);
		assert_eq!(chain.len_of(0), 0);
		assert_eq!(chain.front_at(0), None);
		assert_eq!(chain.back_at(0), None);
		assert_eq!(chain.pre_back_at(0), None);
		assert_eq!(chain.back(), None);
		assert_eq!(chain.is_contained_in(0, &"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".into()), false);
		assert_eq!(chain.contains_in(&"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".into()), None);
		assert_eq!(chain.pop_front_n_at(0, 100), vec![]);
		assert_eq!(chain.remove_at(0, &"000000000019d6689c085ae165831e934ff763ae46a2a6c172b3f1b60a8ce26f".into()), HashPosition::Missing);
	}

	#[test]
	fn hash_queue_chain_not_empty() {
		let mut chain = HashQueueChain::with_number_of_queues(4);
		chain.push_back_n_at(0, vec![
			H256::from(0),
			H256::from(1),
			H256::from(2),
		]);
		chain.push_back_n_at(1, vec![
			H256::from(3),
			H256::from(4),
		]);
		chain.push_back_n_at(2, vec![
			H256::from(5),
		]);

		assert_eq!(chain.len(), 6);
		assert_eq!(chain.len_of(0), 3);
		assert_eq!(chain.len_of(1), 2);
		assert_eq!(chain.len_of(2), 1);
		assert_eq!(chain.len_of(3), 0);
		assert_eq!(chain.front_at(0), Some(H256::from(0)));
		assert_eq!(chain.front_at(1), Some(H256::from(3)));
		assert_eq!(chain.front_at(2), Some(H256::from(5)));
		assert_eq!(chain.front_at(3), None);
		assert_eq!(chain.back_at(0), Some(H256::from(2)));
		assert_eq!(chain.back_at(1), Some(H256::from(4)));
		assert_eq!(chain.back_at(2), Some(H256::from(5)));
		assert_eq!(chain.back_at(3), None);
		assert_eq!(chain.pre_back_at(0), Some(H256::from(1)));
		assert_eq!(chain.pre_back_at(1), Some(H256::from(3)));
		assert_eq!(chain.pre_back_at(2), None);
		assert_eq!(chain.pre_back_at(3), None);
		assert_eq!(chain.back(), Some(H256::from(5)));
		assert_eq!(chain.is_contained_in(0, &H256::from(2)), true);
		assert_eq!(chain.is_contained_in(1, &H256::from(2)), false);
		assert_eq!(chain.is_contained_in(2, &H256::from(2)), false);
		assert_eq!(chain.is_contained_in(3, &H256::from(2)), false);
		assert_eq!(chain.contains_in(&H256::from(2)), Some(0));
		assert_eq!(chain.contains_in(&H256::from(5)), Some(2));
		assert_eq!(chain.contains_in(&H256::from(9)), None);
	}

	#[test]
	fn hash_queue_front_n() {
		let mut queue = HashQueue::new();
		queue.push_back_n(vec![H256::from(0), H256::from(1)]);
		assert_eq!(queue.front_n(3), vec![H256::from(0), H256::from(1)]);
		assert_eq!(queue.front_n(3), vec![H256::from(0), H256::from(1)]);
		assert_eq!(queue.pop_front_n(3), vec![H256::from(0), H256::from(1)]);
		assert_eq!(queue.pop_front_n(3), vec![]);
	}
}