vec.rs 7.84 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of pDSL.
//
// pDSL 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.
//
// pDSL 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 pDSL.  If not, see <http://www.gnu.org/licenses/>.

Hero Bird's avatar
Hero Bird committed
17
18
use crate::{
	storage::{
19
		self,
Hero Bird's avatar
Hero Bird committed
20
		chunk::SyncChunk,
21
		Allocator,
Hero Bird's avatar
Hero Bird committed
22
23
	},
};
24

25
use core::iter::{
Hero Bird's avatar
Hero Bird committed
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
	ExactSizeIterator,
	DoubleEndedIterator,
};

/// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
///
/// # Note
///
/// Despite the similarity to Rust's `Vec` type this storage `Vec` has many
/// differences in its internal data layout. While it stores its data in contiguous
/// storage slots this does not mean that the data is actually densely stored
/// in memory.
///
/// Also its technical performance characteristics may be different from Rust's
/// `Vec` due to the differences stated above.
///
/// Allows to store up to `2^32` elements and is guaranteed to not reallocate
/// upon pushing new elements to it.
44
#[derive(Debug)]
Hero Bird's avatar
Hero Bird committed
45
46
pub struct Vec<T> {
	/// The length of the vector.
47
	len: storage::Value<u32>,
Hero Bird's avatar
Hero Bird committed
48
49
50
51
52
	/// The synchronized cells to operate on the contract storage.
	cells: SyncChunk<T>,
}

/// An iterator over the values of a storage `Vec`.
53
#[derive(Debug)]
Hero Bird's avatar
Hero Bird committed
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
pub struct Iter<'a, T> {
	/// The storage vector to iterate over.
	vec: &'a Vec<T>,
	/// The current begin of the iteration.
	begin: u32,
	/// The current end of the iteration.
	end: u32,
}

impl<'a, T> Iter<'a, T> {
	/// Creates a new iterator for the given storage vector.
	pub(crate) fn new(vec: &'a Vec<T>) -> Self {
		Self{
			vec,
			begin: 0,
			end: vec.len(),
		}
	}
}

impl<'a, T> Iterator for Iter<'a, T>
where
	T: parity_codec::Codec
{
	type Item = &'a T;

	fn next(&mut self) -> Option<Self::Item> {
		debug_assert!(self.begin <= self.end);
		if self.begin == self.end {
			return None
		}
		let cur = self.begin;
		self.begin += 1;
		self.vec.get(cur)
	}

	fn size_hint(&self) -> (usize, Option<usize>) {
		let remaining = (self.end - self.begin) as usize;
		(remaining, Some(remaining))
	}
}

impl<'a, T> ExactSizeIterator for Iter<'a, T>
where
	T: parity_codec::Codec
{}

impl<'a, T> DoubleEndedIterator for Iter<'a, T>
where
	T: parity_codec::Codec
{
	fn next_back(&mut self) -> Option<Self::Item> {
		debug_assert!(self.begin <= self.end);
		if self.begin == self.end {
			return None
		}
		debug_assert_ne!(self.end, 0);
		self.end -= 1;
		self.vec.get(self.end)
	}
}

116
117
118
119
120
121
122
123
124
impl<T> parity_codec::Encode for Vec<T> {
	fn encode_to<W: parity_codec::Output>(&self, dest: &mut W) {
		self.len.encode_to(dest);
		self.cells.encode_to(dest);
	}
}

impl<T> parity_codec::Decode for Vec<T> {
	fn decode<I: parity_codec::Input>(input: &mut I) -> Option<Self> {
125
		let len = storage::Value::decode(input)?;
126
127
128
129
130
		let cells = SyncChunk::decode(input)?;
		Some(Self{len, cells})
	}
}

Hero Bird's avatar
Hero Bird committed
131
impl<T> Vec<T> {
132
133
134
135
136
137
138
139
140
141
142
	/// Allocates a new storage vector using the given storage allocator.
	///
	/// # Safety
	///
	/// The is unsafe because it does not check if the associated storage
	/// does not alias with storage allocated by other storage allocators.
	pub unsafe fn new_using_alloc<A>(alloc: &mut A) -> Self
	where
		A: Allocator
	{
		Self{
143
			len: storage::Value::new_using_alloc(alloc, 0),
144
145
146
147
			cells: SyncChunk::new_using_alloc(alloc),
		}
	}

Hero Bird's avatar
Hero Bird committed
148
149
	/// Returns the number of elements in the vector, also referred to as its 'length'.
	pub fn len(&self) -> u32 {
150
		*self.len.get()
Hero Bird's avatar
Hero Bird committed
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
	}

	/// Returns `true` if the vector contains no elements.
	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}
}

impl<T> Vec<T>
where
	T: parity_codec::Codec
{
	/// Returns the given `n` if it is witihn bounds, otherwise `None`.
	fn within_bounds(&self, n: u32) -> Option<u32> {
		if n < self.len() {
			return Some(n)
		}
		None
	}

	/// Returns an iterator over the references of all elements stored in the vector.
172
173
174
	///
	/// # Note
	///
175
176
177
	/// - It is **not** recommended to iterate over all elements of a storage vector.
	/// - Try to avoid this if possible or iterate only over a minimal subset of
	///   all elements using e.g. `Iterator::take(n)`.
Hero Bird's avatar
Hero Bird committed
178
179
180
181
182
183
184
185
186
187
	pub fn iter(&self) -> Iter<T> {
		Iter::new(self)
	}

	/// Returns a reference to the `n`-th element of the vector.
	///
	/// Returns `None` if `n` is out of bounds.
	pub fn get(&self, n: u32) -> Option<&T> {
		self
			.within_bounds(n)
188
			.and_then(|n| self.cells.get(n))
Hero Bird's avatar
Hero Bird committed
189
190
191
192
193
194
195
196
197
198
199
200
	}

	/// Mutates the `n`-th element of the vector.
	///
	/// Returns a reference to the mutated element.
	/// Returns `None` and won't mutate if `n` out of bounds.
	pub fn mutate<F>(&mut self, n: u32, f: F) -> Option<&T>
	where
		F: FnOnce(&mut T)
	{
		self
			.within_bounds(n)
201
			.and_then(move |n| self.cells.mutate_with(n, f))
Hero Bird's avatar
Hero Bird committed
202
203
204
205
206
207
208
209
210
211
212
213
214
	}

	/// Appends an element to the back of the vector.
	pub fn push(&mut self, val: T) {
		if self.len() == u32::max_value() {
			panic!(
				"[pdsl_core::Vec::push] Error: \
				 cannot push more elements than `u32::MAX`"
			)
		}
		let last_index = self.len();
		self.len.set(last_index + 1);
		self.cells
215
			.set(last_index, val);
Hero Bird's avatar
Hero Bird committed
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
	}

	/// Removes the last element from the vector and returns it,
	/// or `None` if the vector is empty.
	pub fn pop(&mut self) -> Option<T> {
		if self.len() == 0 {
			return None
		}
		let last_index = self.len() - 1;
		self.len.set(last_index);
		self
			.cells
			.remove(last_index)
	}

	/// Replaces the `n`-th element of the vector and returns its replaced value.
	///
	/// Returns `None` if `n` is out of bounds.
	pub fn replace<F>(&mut self, n: u32, f: F) -> Option<T>
	where
		F: FnOnce() -> T
	{
		self
			.within_bounds(n)
			.and_then(|n| {
				Some(self
					.cells
					.replace(n, f())
					.expect(
						"[pdsl_core::Vec::replace] Error: \
						 expected success due to access within bounds"
					)
				)
			})
	}

	/// Swaps the `a`-th and the `b`-th elements.
	pub fn swap(&mut self, a: u32, b: u32) {
		// Bail out if both indices are equal.
		if a == b {
			return
		}
		self
			.within_bounds(a)
			.expect(
				"[pdsl_core::Vec::swap] Error: \
				 expected a to be within bounds"
			);
		self
			.within_bounds(b)
			.expect(
				"[pdsl_core::Vec::swap] Error: \
				 expected b to be within bounds"
			);
		let item_a = self
			.cells
			.remove(a)
			.expect(
				"[pdsl_core::Vec::swap] Error: \
				 expected succes due to `a` being within bounds"
			);
		let item_b = self
			.cells
			.replace(b, item_a)
			.expect(
				"[pdsl_core::Vec::swap] Error: \
				 expected success due to `b` being within bounds"
			);
		self
			.cells
286
			.set(a, item_b);
Hero Bird's avatar
Hero Bird committed
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
	}

	/// Removes the `n`-th element from the vector and returns it.
	///
	/// The removed element is replaced by the last element of the vector.
	///
	/// This does not preserve ordering, but is O(1).
	///
	/// Returns `None` and does not remove if `n` is out of bounds.
	pub fn swap_remove(&mut self, n: u32) -> Option<T> {
		if self.len() == 0 {
			return None
		}
		self
			.within_bounds(n)
			.expect(
				"[pdsl_core::Vec::swap_remove] Error: \
				 expected `index` to be within bounds"
			);
		let popped = self
			.pop()
			.expect(
				"[pdsl_core::Vec::swap_remove] Error: \
				 expected `Some` value since vector is not empty"
			);
		Some(
			self
				.cells
				.replace(n, popped)
				.expect(
					"[pdsl_core::Vec::swap_remove] Error: \
					expected success since the vector is not empty"
				)
		)
	}
}

324
impl<T> core::ops::Index<u32> for Vec<T>
Hero Bird's avatar
Hero Bird committed
325
326
327
328
329
330
331
332
333
334
335
336
337
338
where
	T: parity_codec::Codec
{
	type Output = T;

	fn index(&self, index: u32) -> &Self::Output {
		self
			.get(index)
			.expect(
				"[pdsl_core::Vec::index] Error: \
				 expected `index` to be within bounds"
			)
	}
}