value.rs 12.3 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
22
use crate::{
	storage::{
		self,
		cell::SyncCell,
	},
};
23
use parity_codec::{Encode, Decode};
24

25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// Missing traits:
//
// - DerefMut
// - IndexMut
// - Borrow

/// A value on the storage.
///
/// This is a generic wrapper around a value in the contract storage.
/// It tries to model the wrapped type as close as possible so that using
/// it feels like using the underlying wrapped type.
///
/// While optionally implementing several common core traits, such as `PartialEq`,
/// `Debug`, `Add`, `ShlAssign`, `Deref` etc. it does not implement `DerefMut` or
/// `IndexMut` for security reasons.
///
/// For assigning new values or mutating the value inside of it either use
/// [`set`](struct.Value.html#method.set) or
/// [`mutate_with`](struct.Value.html#method.mutate_with).
44
#[derive(Debug, Encode, Decode)]
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
pub struct Value<T> {
	/// The cell of the storage value.
	cell: SyncCell<T>,
}

impl<T> Value<T>
where
	T: parity_codec::Codec + Default
{
	/// Creates a new storage value initialized as its default value.
	///
	/// # 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 default_using_alloc<A>(alloc: &mut A) -> Self
	where
		A: storage::Allocator,
	{
		Self::new_using_alloc(alloc, Default::default())
	}
}

impl<T> Value<T>
where
	T: parity_codec::Codec,
{
	/// Creates a new storage value initialized by the given value.
	///
	/// # 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, val: T) -> Self
	where
		A: storage::Allocator,
	{
		let mut ret = Self{
			cell: SyncCell::new_using_alloc(alloc),
		};
		ret.set(val);
		ret
	}

	/// Returns the wrapped value as immutable reference.
	pub fn get(&self) -> &T {
		self.cell.get().unwrap()
	}

	/// Mutates the wrapped value inplace by the given closure.
	///
	/// Returns a reference to the resulting value.
	pub fn mutate_with<F>(&mut self, f: F) -> &T
	where
		F: FnOnce(&mut T)
	{
		self.cell.mutate_with(f).unwrap()
	}

	/// Sets the wrapped value to the given value.
	pub fn set(&mut self, val: T) {
		self.cell.set(val)
	}
}

impl<T, R> core::convert::AsRef<R> for Value<T>
where
	T: core::convert::AsRef<R> + parity_codec::Codec,
{
	fn as_ref(&self) -> &R {
		self.get().as_ref()
	}
}

impl<T> core::ops::Deref for Value<T>
where
	T: parity_codec::Codec,
{
	type Target = T;

	fn deref(&self) -> &Self::Target {
		self.get()
	}
}

impl<T> Drop for Value<T> {
	fn drop(&mut self) {
		self.cell.clear();
	}
}

macro_rules! impl_ops_for_value {
	(
		$trait_name:ident, $fn_name:ident,
		$trait_name_assign:ident, $fn_name_assign:ident;
		$tok:tt, $tok_eq:tt
	) => {
		impl<T> core::ops::$trait_name<T> for &Value<T>
		where
			T: core::ops::$trait_name<T> + Copy + parity_codec::Codec,
		{
			type Output = <T as core::ops::$trait_name>::Output;

			fn $fn_name(self, rhs: T) -> Self::Output {
				*self.get() $tok rhs
			}
		}

		impl<T> core::ops::$trait_name for &Value<T>
		where
			T: core::ops::$trait_name<T> + Copy + parity_codec::Codec,
		{
			type Output = <T as core::ops::$trait_name>::Output;

			fn $fn_name(self, rhs: Self) -> Self::Output {
				(*self.get()) $tok (*rhs.get())
			}
		}

		impl<T> core::ops::$trait_name_assign<T> for Value<T>
		where
			T: core::ops::$trait_name_assign<T> + parity_codec::Codec,
		{
			fn $fn_name_assign(&mut self, rhs: T) {
				self.mutate_with(|val| (*val) $tok_eq rhs);
			}
		}

		impl<T> core::ops::$trait_name_assign<&Self> for Value<T>
		where
			T: core::ops::$trait_name_assign<T> + Copy + parity_codec::Codec,
		{
			fn $fn_name_assign(&mut self, rhs: &Value<T>) {
				self.mutate_with(|val| (*val) $tok_eq *rhs.get());
			}
		}
	};
}

impl_ops_for_value!(Add, add, AddAssign, add_assign; +, +=);
impl_ops_for_value!(Sub, sub, SubAssign, sub_assign; -, -=);
impl_ops_for_value!(Mul, mul, MulAssign, mul_assign; *, *=);
impl_ops_for_value!(Div, div, DivAssign, div_assign; /, /=);
impl_ops_for_value!(Rem, rem, RemAssign, rem_assign; %, %=);

impl_ops_for_value!(BitAnd, bitand, BitAndAssign, bitand_assign; &, &=);
impl_ops_for_value!(BitOr, bitor, BitOrAssign, bitor_assign; |, |=);
impl_ops_for_value!(BitXor, bitxor, BitXorAssign, bitxor_assign; ^, ^=);

impl<T> core::ops::Neg for &Value<T>
where
	T: core::ops::Neg + Copy + parity_codec::Codec,
{
	type Output = <T as core::ops::Neg>::Output;

	fn neg(self) -> Self::Output {
		-(*self.get())
	}
}

impl<T> core::ops::Not for &Value<T>
where
	T: core::ops::Not + Copy + parity_codec::Codec,
{
	type Output = <T as core::ops::Not>::Output;

	fn not(self) -> Self::Output {
		!(*self.get())
	}
}

macro_rules! impl_shift_for_value {
	(
		$trait_name:ident, $fn_name:ident, $tok:tt;
		$trait_name_assign:ident, $fn_name_assign:ident, $tok_eq:tt
	) => {
		impl<T, R> core::ops::$trait_name<R> for &Value<T>
		where
			T: core::ops::$trait_name<R> + Copy + parity_codec::Codec,
		{
			type Output = <T as core::ops::$trait_name<R>>::Output;

			fn $fn_name(self, rhs: R) -> Self::Output {
				(*self.get()) $tok rhs
			}
		}

		impl<T, R> core::ops::$trait_name_assign<R> for Value<T>
		where
			T: core::ops::$trait_name_assign<R> + Copy + parity_codec::Codec,
		{
			fn $fn_name_assign(&mut self, rhs: R) {
				self.mutate_with(|value| (*value) $tok_eq rhs);
			}
		}
	};
}

impl_shift_for_value!(Shl, shl, <<; ShlAssign, shl_assign, <<=);
impl_shift_for_value!(Shr, shr, >>; ShrAssign, shr_assign, >>=);

impl<T, I> core::ops::Index<I> for Value<T>
where
	T: core::ops::Index<I> + parity_codec::Codec,
{
	type Output = <T as core::ops::Index<I>>::Output;

	fn index(&self, index: I) -> &Self::Output {
		&self.get()[index]
	}
}

impl<T> PartialEq<T> for Value<T>
where
	T: PartialEq + parity_codec::Codec,
{
	fn eq(&self, rhs: &T) -> bool {
		self.get().eq(rhs)
	}
}

impl<T> PartialEq for Value<T>
where
	T: PartialEq + parity_codec::Codec,
{
	fn eq(&self, rhs: &Self) -> bool {
		self.get().eq(rhs.get())
	}
}

impl<T> Eq for Value<T> where T: Eq + parity_codec::Codec {}

use core::cmp::Ordering;

impl<T> PartialOrd<T> for Value<T>
where
	T: PartialOrd + parity_codec::Codec,
{
	fn partial_cmp(&self, other: &T) -> Option<Ordering> {
		self.get().partial_cmp(other)
	}
}

impl<T> PartialOrd<Value<T>> for Value<T>
where
	T: PartialOrd + parity_codec::Codec,
{
	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
		self.get().partial_cmp(other.get())
	}
}

impl<T> Ord for Value<T> where T: Ord + parity_codec::Codec {
	fn cmp(&self, other: &Self) -> Ordering {
		self.get().cmp(other.get())
	}
}

impl<T> core::hash::Hash for Value<T>
where
	T: core::hash::Hash + parity_codec::Codec,
{
	fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
		self.get().hash(state)
	}
}

impl<T> core::fmt::Display for Value<T>
where
	T: core::fmt::Display + parity_codec::Codec,
{
	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
		self.get().fmt(f)
	}
}

#[cfg(all(test, feature = "test-env"))]
mod tests {
	use super::*;
324
	use crate::storage::Key;
325
326

	use crate::{
327
		test_utils::run_test,
328
329
330
331
332
333
334
335
336
		storage::{
			alloc::ForwardAlloc,
		},
	};

	macro_rules! test_ops_impl {
		( $test_name:ident, $tok:tt; $test_name_assign:ident, $tok_eq:tt) => {
			#[test]
			fn $test_name() {
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
				run_test(|| {
					let (val1, val2, val3) = unsafe {
						let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
						let val1: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 42);
						let val2: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 5);
						let val3 = Value::new_using_alloc(&mut fw_alloc, &val1 $tok &val2);
						(val1, val2, val3)
					};
					// Check init values
					assert_eq!(val1.get(), &42);
					assert_eq!(val2.get(), &5);
					assert_eq!(val3.get(), &(42 $tok 5));
					// Operations with primitives
					assert_eq!(&val1 $tok 5, 42 $tok 5);
					// Operations with `Value<T>`
					assert_eq!(&val1 $tok &val2, 42 $tok 5);
				})
354
355
356
357
			}

			#[test]
			fn $test_name_assign() {
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
				run_test(|| {
					let (mut val1, mut copy, val2, val3) = unsafe {
						let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
						let val1: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 42);
						let copy: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 42);
						let val2: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 13);
						let val3 = Value::new_using_alloc(&mut fw_alloc, 42 $tok 13);
						(val1, copy, val2, val3)
					};
					// Check init values
					assert_eq!(val1.get(), &42);
					assert_eq!(val2.get(), &13);
					assert_eq!(val3.get(), &(42 $tok 13));
					// Operation with primitives
					{
						val1 $tok_eq 13;
						assert_eq!(val1.get(), &(42 $tok 13));
						assert_eq!(val1, val3);
					}
					// Operation between `Value<T>`
					{
						copy $tok_eq &val2;
						assert_eq!(copy.get(), &(42 $tok 13));
						assert_eq!(copy, val3);
					}
				})
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
			}
		};
	}

	test_ops_impl!(test_add   , +; test_add_assign   , +=);
	test_ops_impl!(test_sub   , -; test_sub_assign   , -=);
	test_ops_impl!(test_mul   , *; test_mul_assign   , *=);
	test_ops_impl!(test_div   , /; test_div_assign   , /=);
	test_ops_impl!(test_rem   , %; test_rem_assign   , %=);
	test_ops_impl!(test_bitand, &; test_bitand_assign, &=);
	test_ops_impl!(test_bitor , |; test_bitor_assign , |=);
	test_ops_impl!(test_bitxor, ^; test_bitxor_assign, ^=);

	macro_rules! test_unary_ops_impl {
		( $test_name:ident, $trait_name:ident, $fn_name:ident, $tok:tt ) => {
			#[test]
			fn $test_name() {
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
				run_test(|| {
					let (val1, val2) = unsafe {
						let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
						let val1: Value<i32>
							= Value::new_using_alloc(&mut fw_alloc, 42);
						let val2
							= Value::new_using_alloc(&mut fw_alloc, $tok 42);
						(val1, val2)
					};
					// Check init values
					assert_eq!(val1.get(), &42);
					assert_eq!(val2.get(), &($tok 42));
					// Simple test
					assert_eq!($tok &val1, $tok 42);
					use core::ops::$trait_name;
					assert_eq!(val1.$fn_name(), $tok 42);
				})
418
419
420
421
422
423
424
425
426
			}
		};
	}

	test_unary_ops_impl!(test_neg, Neg, neg, -);
	test_unary_ops_impl!(test_not, Not, not, !);

	#[test]
	fn test_shift() {
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
		run_test(|| {
			let (mut value, result) = unsafe {
				let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
				let value: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 10);
				let result = Value::new_using_alloc(&mut fw_alloc, 10 << 5);
				(value, result)
			};
			// Check init values
			assert_eq!(value.get(), &10);
			assert_eq!(result.get(), &(10 << 5));
			// Simple tests
			assert_eq!(&value << 5, 10 << 5);
			// Assign test
			value <<= 5;
			assert_eq!(&value, &result);
		})
443
444
445
446
	}

	#[test]
	fn test_eq_ord() {
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
		run_test(|| {
			let (val1, val2, val3) = unsafe {
				let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
				let val1: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 42);
				let val2: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 42);
				let val3: Value<i32> = Value::new_using_alloc(&mut fw_alloc, 1337);
				(val1, val2, val3)
			};
			// Eq & Ne
			assert!(val1 == val2);
			assert!(val2 != val3);
			// Less-Than
			assert!(!(val1 < val2));
			assert!(val2 < val3);
			assert!(val1 < val3);
			// Less-Than or Eq
			assert!(val1 <= val2);
			assert!(val2 <= val3);
			assert!(val1 <= val3);
		})
467
468
469
470
	}

	#[test]
	fn test_index() {
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
		run_test(|| {
			let val1 = unsafe {
				let mut fw_alloc = ForwardAlloc::from_raw_parts(Key([0x0; 32]));
				let val1: Value<Vec<i32>> = Value::new_using_alloc(
					&mut fw_alloc,
					vec![2, 3, 5, 7, 11, 13]
				);
				val1
			};
			assert_eq!(val1[0], 2);
			assert_eq!(val1[1], 3);
			assert_eq!(val1[2], 5);
			assert_eq!(val1[3], 7);
			assert_eq!(val1[4], 11);
			assert_eq!(val1[5], 13);
		})
487
488
	}
}