sync_chunk.rs 12.8 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/>.

17
18
19
20
21
use crate::{
	storage::{
		Key,
		chunk::{
			TypedChunk,
22
			TypedChunkCell,
23
		},
24
		Allocator,
25
	},
26
27
	memory::collections::btree_map::{
		BTreeMap,
28
		Entry,
29
	},
30
31
};

32
33
use core::cell::RefCell;

34
/// A chunk of synchronized cells.
35
36
37
38
39
40
41
///
/// Provides mutable and read-optimized access to the associated constract storage slot.
///
/// # Guarantees
///
/// - `Owned`
/// - `Typed`
42
/// - `Opt. Reads`
43
44
45
/// - `Mutable`
///
/// Read more about kinds of guarantees and their effect [here](../index.html#guarantees).
46
#[derive(Debug)]
47
pub struct SyncChunk<T> {
48
49
	/// The underlying chunk of cells.
	chunk: TypedChunk<T>,
50
	/// The cached element.
51
52
53
	elems: Cache<T>,
}

54
/// A single cache entry for a copy chunk cell.
55
#[cfg(not(feature = "std"))]
56
type CacheEntry<'a, T> = Entry<'a, u32, Option<T>>;
57

58
59
60
61
/// A single cache entry for a copy chunk cell.
#[cfg(feature = "std")]
type CacheEntry<'a, T> = Entry<'a, u32, Option<T>>;

62
63
/// A single cell within a chunk of copy cells.
#[derive(Debug)]
64
pub struct SyncChunkCell<'a, T> {
65
66
67
68
69
70
	/// The underlying cell within the chunk of cells.
	cell: TypedChunkCell<'a, T>,
	/// The cached entry for the cell.
	elem: CacheEntry<'a, T>,
}

71
impl<'a, T> SyncChunkCell<'a, T> {
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
	/// Creates a new cell within a chunk of copy cells.
	///
	/// # Safety
	///
	/// This is unsafe since it doesn't check aliasing of cells
	/// or if the cell and the cache entry are actually associated
	/// with each other.
	pub(self) unsafe fn new_unchecked(
		cell: TypedChunkCell<'a, T>,
		elem: CacheEntry<'a, T>
	) -> Self {
		Self{cell, elem}
	}

	/// Removes the value stored in this cell.
	pub fn clear(self) {
		let mut this = self;
		match this.elem {
			Entry::Occupied(mut occupied) => {
				this.cell.clear();
				occupied.insert(None);
			}
			Entry::Vacant(vacant) => {
				this.cell.clear();
				vacant.insert(None);
			}
		}
	}
}

102
impl<'a, T> SyncChunkCell<'a, T>
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
where
	T: parity_codec::Decode
{
	/// Removes the value from the cell and returns the removed value.
	///
	/// # Note
	///
	/// Prefer using `clear` if you are not interested in the return value.
	#[must_use]
	pub fn remove(self) -> Option<T> {
		let mut this = self;
		match this.elem {
			Entry::Occupied(mut occupied) => {
				this.cell.clear();
				occupied.insert(None)
			}
			Entry::Vacant(vacant) => {
				let old = this.cell.load();
				this.cell.clear();
				vacant.insert(None);
				old
			}
		}
	}
}

129
impl<'a, T> SyncChunkCell<'a, T>
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
where
	T: parity_codec::Encode
{
	/// Stores the new value into the cell.
	pub fn set(self, val: T) {
		let mut this = self;
		match this.elem {
			Entry::Occupied(mut occupied) => {
				this.cell.store(&val);
				occupied.insert(Some(val));
			}
			Entry::Vacant(vacant) => {
				this.cell.store(&val);
				vacant.insert(Some(val));
			}
		}
	}
}

149
impl<'a, T> SyncChunkCell<'a, T>
150
151
152
153
154
where
	T: parity_codec::Codec
{
	/// Mutates the value of this cell.
	///
155
156
	/// Returns an immutable reference to the result if
	/// a mutation happened, otherwise `None` is returned.
157
158
159
160
	///
	/// # Note
	///
	/// Prefer using `set` if you are not interested in the return value.
161
	pub fn mutate_with<F>(self, f: F) -> Option<&'a T>
162
163
164
165
166
	where
		F: FnOnce(&mut T)
	{
		let mut this = self;
		match this.elem {
167
168
			Entry::Occupied(occupied) => {
				if let Some(elem) = occupied.into_mut() {
169
170
					f(elem);
					this.cell.store(elem);
171
					return Some(&*elem)
172
				}
173
				None
174
175
176
177
178
179
			}
			Entry::Vacant(vacant) => {
				let mut ret = false;
				let mut elem = this.cell.load();
				if let Some(elem) = &mut elem {
					f(elem);
180
					this.cell.store(&*elem);
181
182
					ret = true;
				}
183
184
185
186
187
				let res = (&*vacant.insert(elem)).into();
				if ret {
					return res
				}
				None
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
			}
		}
	}

	/// Replaces the value of this cell and returns its previous value.
	///
	/// # Note
	///
	/// Prefer using `set` if you are not interested in the return value.
	#[must_use]
	pub fn replace(self, val: T) -> Option<T> {
		let mut this = self;
		match this.elem {
			Entry::Occupied(mut occupied) => {
				this.cell.store(&val);
				occupied.insert(Some(val))
			}
			Entry::Vacant(vacant) => {
				let old = this.cell.load();
				this.cell.store(&val);
				vacant.insert(Some(val));
				old
			}
		}
	}
}

/// Stores the values of synchronized cells.
///
/// # Note
///
/// An element counts as synchronized if its version in the contract
/// storage and the version in the cache are identical.
221
222
#[derive(Debug, PartialEq, Eq)]
struct Cache<T> {
223
	/// The synchronized values of associated cells.
224
	elems: RefCell<BTreeMap<u32, Option<T>>>,
225
226
227
228
}

impl<T> Default for Cache<T> {
	fn default() -> Self {
229
		Self{ elems: RefCell::new(BTreeMap::new()) }
230
231
232
233
234
235
236
237
238
239
240
241
242
	}
}

/// A cached entity.
///
/// This is either in sync with the contract storage or out of sync.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Cached<T> {
	Desync,
	Sync(Option<T>),
}

impl<T> Cache<T> {
243
	/// Inserts or updates a value associated with the `n`-th cell.
244
	///
245
246
	/// Returns an immutable reference to the new value.
	pub fn upsert(&self, n: u32, val: Option<T>) -> Option<&T> {
247
		let elems: &mut BTreeMap<u32, Option<T>> = unsafe {
248
249
250
251
252
			&mut *self.elems.as_ptr()
		};
		match elems.entry(n) {
			Entry::Occupied(mut occupied) => {
				occupied.insert(val);
253
				(&*occupied.into_mut()).into()
254
255
			}
			Entry::Vacant(vacant) => {
256
				(&*vacant.insert(val)).into()
257
258
259
260
			}
		}
	}

261
	/// Returns the synchronized value of the `n`-th cell if any.
262
	pub fn get(&self, n: u32) -> Cached<&T> {
263
		let elems: &mut BTreeMap<u32, Option<T>> = unsafe {
264
265
266
267
268
269
270
271
			&mut *self.elems.as_ptr()
		};
		match elems.get(&n) {
			Some(opt_elem) => Cached::Sync(opt_elem.into()),
			None => Cached::Desync,
		}
	}

272
273
274
	/// Returns the cache entry for the `n`-th cell.
	pub fn entry(&mut self, n: u32) -> CacheEntry<T> {
		self.elems.get_mut().entry(n)
275
276
277
	}
}

278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
impl<T> parity_codec::Encode for SyncChunk<T> {
	fn encode_to<W: parity_codec::Output>(&self, dest: &mut W) {
		self.chunk.encode_to(dest)
	}
}

impl<T> parity_codec::Decode for SyncChunk<T> {
	fn decode<I: parity_codec::Input>(input: &mut I) -> Option<Self> {
		TypedChunk::decode(input)
			.map(|typed_chunk| Self{
				chunk: typed_chunk,
				elems: Cache::default(),
			})
	}
}

294
impl<T> SyncChunk<T> {
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
	/// Allocates a new sync cell chunk 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{
			chunk: TypedChunk::new_using_alloc(alloc),
			elems: Cache::default(),
		}
	}

311
312
313
314
315
316
317
318
319
320
	/// Returns the unterlying key to the cells.
	///
	/// # Note
	///
	/// This is a low-level utility getter and should
	/// normally not be required by users.
	pub fn cells_key(&self) -> Key {
		self.chunk.cells_key()
	}

321
	/// Returns an accessor to the `n`-th cell.
322
	fn cell_at(&mut self, n: u32) -> SyncChunkCell<T> {
323
		unsafe {
324
			SyncChunkCell::new_unchecked(
325
				self.chunk.cell_at(n),
326
327
				self.elems.entry(n)
			)
328
		}
329
	}
330
331
332
333
334
335

	/// Clear the `n`-th cell.
	///
	/// # Errors
	///
	/// If `n` is out of bounds.
336
337
	pub fn clear(&mut self, n: u32) {
		self.cell_at(n).clear()
338
	}
339
340
}

341
impl<T> SyncChunk<T>
342
343
344
where
	T: parity_codec::Decode
{
345
	/// Returns the value of the `n`-th cell if any.
346
347
348
	///
	/// # Errors
	///
349
	/// If `n` is out of bounds.
350
	pub fn get(&self, n: u32) -> Option<&T> {
351
		if let Cached::Sync(cached) = self.elems.get(n) {
352
			return cached
353
354
355
356
		}
		self.load(n)
	}

357
	/// Returns the value of the `n`-th cell if any.
358
359
360
	///
	/// # Note
	///
361
	/// Prefer using [`get`](struct.SyncChunk.html#method.get)
362
	/// to avoid unnecesary contract storage accesses.
363
364
365
	///
	/// # Errors
	///
366
	/// If `n` is out of bounds.
367
368
369
370
	fn load(&self, n: u32) -> Option<&T> {
		self.elems.upsert(
			n,
			self.chunk.load(n)
371
372
373
		)
	}

374
	/// Clears the `n`-th cell and returns its previous value if any.
375
376
377
	///
	/// # Note
	///
378
	/// Use [`clear`](struct.SyncChunk.html#method.clear) instead
379
	/// if you are not interested in the old return value.
380
381
382
	///
	/// # Errors
	///
383
384
	/// If `n` is out of bounds.
	#[must_use]
385
386
	pub fn remove(&mut self, n: u32) -> Option<T> {
		self.cell_at(n).remove()
387
	}
388
}
389

390
impl<T> SyncChunk<T>
391
392
393
394
where
	T: parity_codec::Encode
{
	/// Sets the value of the `n`-th cell.
395
396
397
	///
	/// # Errors
	///
398
	/// If `n` is out of bounds.
399
400
	pub fn set(&mut self, n: u32, val: T) {
		self.cell_at(n).set(val)
401
402
403
	}
}

404
impl<T> SyncChunk<T>
405
406
407
where
	T: parity_codec::Codec
{
Hero Bird's avatar
Hero Bird committed
408
409
410
411
	/// Sets the value of the `n`-th cell and returns its old value if any.
	///
	/// # Note
	///
412
	/// Use [`set`](struct.SyncChunk.html#method.set) instead
Hero Bird's avatar
Hero Bird committed
413
414
415
416
417
418
	/// if you are not interested in the old return value.
	///
	/// # Errors
	///
	/// If `n` is out of bounds.
	#[must_use]
419
420
	pub fn replace(&mut self, n: u32, val: T) -> Option<T> {
		self.cell_at(n).replace(val)
Hero Bird's avatar
Hero Bird committed
421
	}
422
423
424

	/// Mutates the value of the `n`-th cell if any.
	///
425
426
	/// Returns an immutable reference to the result if
	/// a mutation happened, otherwise `None` is returned.
427
428
429
	///
	/// # Errors
	///
430
	/// If `n` is out of bounds.
431
	pub fn mutate_with<F>(&mut self, n: u32, f: F) -> Option<&T>
432
433
434
	where
		F: FnOnce(&mut T)
	{
435
		self.cell_at(n).mutate_with(f)
436
437
438
439
440
441
442
	}
}

#[cfg(all(test, feature = "test-env"))]
mod tests {
	use super::*;

443
444
445
446
	use crate::{
		test_utils::run_test,
		env::TestEnv,
	};
447

448
449
450
451
452
453
454
455
456
	fn dummy_chunk() -> SyncChunk<u32> {
		unsafe {
			let mut alloc = crate::storage::alloc::ForwardAlloc::from_raw_parts(
				Key([0x0; 32])
			);
			SyncChunk::new_using_alloc(&mut alloc)
		}
	}

457
458
	#[test]
	fn simple() {
459
460
		run_test(|| {
			const TEST_LEN: u32 = 5;
461

462
			let mut chunk = dummy_chunk();
463

464
465
466
467
			// Invariants after initialization
			for i in 0..TEST_LEN {
				assert_eq!(chunk.load(i), None);
			}
468

469
470
471
472
473
474
			// Store some elements
			for i in 0..TEST_LEN {
				chunk.set(i, i);
				assert_eq!(chunk.get(i), Some(&i));
				assert_eq!(chunk.load(i), Some(&i));
			}
475

476
477
478
479
480
481
482
			// Clear all elements.
			for i in 0..TEST_LEN {
				chunk.clear(i);
				assert_eq!(chunk.get(i), None);
				assert_eq!(chunk.load(i), None);
			}
		})
483
484
485
486
	}

	#[test]
	fn count_reads_writes() {
487
488
		run_test(|| {
			const TEST_LEN: u32 = 5;
489

490
			let mut chunk = dummy_chunk();
491

492
493
			// Reads and writes after init.
			assert_eq!(TestEnv::total_reads(), 0);
494
495
			assert_eq!(TestEnv::total_writes(), 0);

496
497
498
499
500
501
			// Loading from all cells.
			for i in 0..TEST_LEN {
				chunk.load(i);
				assert_eq!(TestEnv::total_reads(), i as u64 + 1);
				assert_eq!(TestEnv::total_writes(), 0);
			}
502
			assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
503
			assert_eq!(TestEnv::total_writes(), 0);
504

505
506
507
508
509
510
			// Writing to all cells.
			for i in 0..TEST_LEN {
				chunk.set(i, i);
				assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
				assert_eq!(TestEnv::total_writes(), i as u64 + 1);
			}
511
512
			assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
			assert_eq!(TestEnv::total_writes(), TEST_LEN as u64);
513

514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
			// Loading multiple times from a single cell.
			const LOAD_REPEATS: usize = 3;
			for _ in 0..LOAD_REPEATS {
				chunk.get(0);
				assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
				assert_eq!(TestEnv::total_writes(), TEST_LEN as u64);
			}

			// Storing multiple times to a single cell.
			const STORE_REPEATS: usize = 3;
			for n in 0..STORE_REPEATS {
				chunk.set(0, 10);
				assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
				assert_eq!(TestEnv::total_writes(), TEST_LEN as u64 + n as u64 + 1);
			}
529
			assert_eq!(TestEnv::total_reads(), TEST_LEN as u64);
530
531
			assert_eq!(TestEnv::total_writes(), TEST_LEN as u64 + STORE_REPEATS as u64);
		})
532
	}
533
534
535

	#[test]
	fn replace() {
536
		run_test(|| {
537
			let mut chunk = dummy_chunk();
538
539
540
541
542
543
544
545
546
547

			// Replace some with none.
			assert_eq!(chunk.replace(0, 42), None);
			// Again will yield previous result.
			assert_eq!(chunk.replace(0, 42), Some(42));

			// After clearing it will be none again.
			chunk.clear(0);
			assert_eq!(chunk.replace(0, 42), None);
		})
548
549
550
551
	}

	#[test]
	fn remove() {
552
		run_test(|| {
553
			let mut chunk = dummy_chunk();
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570

			// Remove at none.
			assert_eq!(chunk.remove(0), None);
			// Again will yield none again.
			assert_eq!(chunk.remove(0), None);
			// Also get will return none.
			assert_eq!(chunk.get(0), None);

			// After inserting it will yield the inserted value.
			chunk.set(0, 1337);
			// Before remove returns the inserted value.
			assert_eq!(chunk.get(0), Some(&1337));
			// Remove yields the removed value.
			assert_eq!(chunk.remove(0), Some(1337));
			// After remove returns none again.
			assert_eq!(chunk.get(0), None);
		})
571
	}
572
}