referrerpolicy=no-referrer-when-downgrade

sp_weights/
weight_v2.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
19use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign};
20use sp_arithmetic::traits::{Bounded, CheckedAdd, CheckedSub, Zero};
21
22use super::*;
23
24#[derive(
25	Encode,
26	Decode,
27	DecodeWithMemTracking,
28	MaxEncodedLen,
29	TypeInfo,
30	Eq,
31	PartialEq,
32	Copy,
33	Clone,
34	Debug,
35	Default,
36)]
37#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
38#[cfg_attr(feature = "json-schema", derive(schemars::JsonSchema))]
39pub struct Weight {
40	#[codec(compact)]
41	/// The weight of computational time used based on some reference hardware.
42	ref_time: u64,
43	#[codec(compact)]
44	/// The weight of storage space used by proof of validity.
45	proof_size: u64,
46}
47
48impl Weight {
49	/// Set the reference time part of the weight.
50	pub const fn set_ref_time(mut self, c: u64) -> Self {
51		self.ref_time = c;
52		self
53	}
54
55	/// Set the storage size part of the weight.
56	pub const fn set_proof_size(mut self, c: u64) -> Self {
57		self.proof_size = c;
58		self
59	}
60
61	/// Return the reference time part of the weight.
62	pub const fn ref_time(&self) -> u64 {
63		self.ref_time
64	}
65
66	/// Return the storage size part of the weight.
67	pub const fn proof_size(&self) -> u64 {
68		self.proof_size
69	}
70
71	/// Return a mutable reference to the reference time part of the weight.
72	pub fn ref_time_mut(&mut self) -> &mut u64 {
73		&mut self.ref_time
74	}
75
76	/// Return a mutable reference to the storage size part of the weight.
77	pub fn proof_size_mut(&mut self) -> &mut u64 {
78		&mut self.proof_size
79	}
80
81	/// The maximal weight in all dimensions.
82	pub const MAX: Self = Self { ref_time: u64::MAX, proof_size: u64::MAX };
83
84	/// Get the conservative min of `self` and `other` weight.
85	pub fn min(&self, other: Self) -> Self {
86		Self {
87			ref_time: self.ref_time.min(other.ref_time),
88			proof_size: self.proof_size.min(other.proof_size),
89		}
90	}
91
92	/// Get the aggressive max of `self` and `other` weight.
93	pub fn max(&self, other: Self) -> Self {
94		Self {
95			ref_time: self.ref_time.max(other.ref_time),
96			proof_size: self.proof_size.max(other.proof_size),
97		}
98	}
99
100	/// Try to add some `other` weight while upholding the `limit`.
101	pub fn try_add(&self, other: &Self, limit: &Self) -> Option<Self> {
102		let total = self.checked_add(other)?;
103		if total.any_gt(*limit) {
104			None
105		} else {
106			Some(total)
107		}
108	}
109
110	/// Construct [`Weight`] from weight parts, namely reference time and proof size weights.
111	pub const fn from_parts(ref_time: u64, proof_size: u64) -> Self {
112		Self { ref_time, proof_size }
113	}
114
115	/// Construct [`Weight`] from the same weight for all parts.
116	pub const fn from_all(value: u64) -> Self {
117		Self { ref_time: value, proof_size: value }
118	}
119
120	/// Saturating [`Weight`] addition. Computes `self + rhs`, saturating at the numeric bounds of
121	/// all fields instead of overflowing.
122	pub const fn saturating_add(self, rhs: Self) -> Self {
123		Self {
124			ref_time: self.ref_time.saturating_add(rhs.ref_time),
125			proof_size: self.proof_size.saturating_add(rhs.proof_size),
126		}
127	}
128
129	/// Saturating [`Weight`] subtraction. Computes `self - rhs`, saturating at the numeric bounds
130	/// of all fields instead of overflowing.
131	pub const fn saturating_sub(self, rhs: Self) -> Self {
132		Self {
133			ref_time: self.ref_time.saturating_sub(rhs.ref_time),
134			proof_size: self.proof_size.saturating_sub(rhs.proof_size),
135		}
136	}
137
138	/// Saturating [`Weight`] scalar multiplication. Computes `self.field * scalar` for all fields,
139	/// saturating at the numeric bounds of all fields instead of overflowing.
140	pub const fn saturating_mul(self, scalar: u64) -> Self {
141		Self {
142			ref_time: self.ref_time.saturating_mul(scalar),
143			proof_size: self.proof_size.saturating_mul(scalar),
144		}
145	}
146
147	/// Saturating [`Weight`] scalar division. Computes `self.field / scalar` for all fields,
148	/// saturating at the numeric bounds of all fields instead of overflowing.
149	pub const fn saturating_div(self, scalar: u64) -> Self {
150		Self {
151			ref_time: self.ref_time.saturating_div(scalar),
152			proof_size: self.proof_size.saturating_div(scalar),
153		}
154	}
155
156	/// Saturating [`Weight`] scalar exponentiation. Computes `self.field.pow(exp)` for all fields,
157	/// saturating at the numeric bounds of all fields instead of overflowing.
158	pub const fn saturating_pow(self, exp: u32) -> Self {
159		Self {
160			ref_time: self.ref_time.saturating_pow(exp),
161			proof_size: self.proof_size.saturating_pow(exp),
162		}
163	}
164
165	/// Increment [`Weight`] by `amount` via saturating addition.
166	pub fn saturating_accrue(&mut self, amount: Self) {
167		*self = self.saturating_add(amount);
168	}
169
170	/// Reduce [`Weight`] by `amount` via saturating subtraction.
171	pub fn saturating_reduce(&mut self, amount: Self) {
172		*self = self.saturating_sub(amount);
173	}
174
175	/// Checked [`Weight`] addition. Computes `self + rhs`, returning `None` if overflow occurred.
176	pub const fn checked_add(&self, rhs: &Self) -> Option<Self> {
177		let ref_time = match self.ref_time.checked_add(rhs.ref_time) {
178			Some(t) => t,
179			None => return None,
180		};
181		let proof_size = match self.proof_size.checked_add(rhs.proof_size) {
182			Some(s) => s,
183			None => return None,
184		};
185		Some(Self { ref_time, proof_size })
186	}
187
188	/// Checked [`Weight`] subtraction. Computes `self - rhs`, returning `None` if overflow
189	/// occurred.
190	pub const fn checked_sub(&self, rhs: &Self) -> Option<Self> {
191		let ref_time = match self.ref_time.checked_sub(rhs.ref_time) {
192			Some(t) => t,
193			None => return None,
194		};
195		let proof_size = match self.proof_size.checked_sub(rhs.proof_size) {
196			Some(s) => s,
197			None => return None,
198		};
199		Some(Self { ref_time, proof_size })
200	}
201
202	/// Checked [`Weight`] scalar multiplication. Computes `self.field * scalar` for each field,
203	/// returning `None` if overflow occurred.
204	pub const fn checked_mul(self, scalar: u64) -> Option<Self> {
205		let ref_time = match self.ref_time.checked_mul(scalar) {
206			Some(t) => t,
207			None => return None,
208		};
209		let proof_size = match self.proof_size.checked_mul(scalar) {
210			Some(s) => s,
211			None => return None,
212		};
213		Some(Self { ref_time, proof_size })
214	}
215
216	/// Checked [`Weight`] scalar division. Computes `self.field / scalar` for each field, returning
217	/// `None` if overflow occurred.
218	pub const fn checked_div(self, scalar: u64) -> Option<Self> {
219		let ref_time = match self.ref_time.checked_div(scalar) {
220			Some(t) => t,
221			None => return None,
222		};
223		let proof_size = match self.proof_size.checked_div(scalar) {
224			Some(s) => s,
225			None => return None,
226		};
227		Some(Self { ref_time, proof_size })
228	}
229
230	/// Calculates how many `other` fit into `self`.
231	///
232	/// Divides each component of `self` against the same component of `other`. Returns the minimum
233	/// of all those divisions. Returns `None` in case **all** components of `other` are zero.
234	///
235	/// This returns `Some` even if some components of `other` are zero as long as there is at least
236	/// one non-zero component in `other`. The division for this particular component will then
237	/// yield the maximum value (e.g u64::MAX). This is because we assume not every operation and
238	/// hence each `Weight` will necessarily use each resource.
239	pub const fn checked_div_per_component(self, other: &Self) -> Option<u64> {
240		let mut all_zero = true;
241		let ref_time = match self.ref_time.checked_div(other.ref_time) {
242			Some(ref_time) => {
243				all_zero = false;
244				ref_time
245			},
246			None => u64::MAX,
247		};
248		let proof_size = match self.proof_size.checked_div(other.proof_size) {
249			Some(proof_size) => {
250				all_zero = false;
251				proof_size
252			},
253			None => u64::MAX,
254		};
255		if all_zero {
256			None
257		} else {
258			Some(if ref_time < proof_size { ref_time } else { proof_size })
259		}
260	}
261
262	/// Try to increase `self` by `amount` via checked addition.
263	pub fn checked_accrue(&mut self, amount: Self) -> Option<()> {
264		self.checked_add(&amount).map(|new_self| *self = new_self)
265	}
266
267	/// Try to reduce `self` by `amount` via checked subtraction.
268	pub fn checked_reduce(&mut self, amount: Self) -> Option<()> {
269		self.checked_sub(&amount).map(|new_self| *self = new_self)
270	}
271
272	/// Return a [`Weight`] where all fields are zero.
273	pub const fn zero() -> Self {
274		Self { ref_time: 0, proof_size: 0 }
275	}
276
277	/// Constant version of Add for `ref_time` component with u64.
278	///
279	/// Is only overflow safe when evaluated at compile-time.
280	pub const fn add_ref_time(self, scalar: u64) -> Self {
281		Self { ref_time: self.ref_time + scalar, proof_size: self.proof_size }
282	}
283
284	/// Constant version of Add for `proof_size` component with u64.
285	///
286	/// Is only overflow safe when evaluated at compile-time.
287	pub const fn add_proof_size(self, scalar: u64) -> Self {
288		Self { ref_time: self.ref_time, proof_size: self.proof_size + scalar }
289	}
290
291	/// Constant version of Sub for `ref_time` component with u64.
292	///
293	/// Is only overflow safe when evaluated at compile-time.
294	pub const fn sub_ref_time(self, scalar: u64) -> Self {
295		Self { ref_time: self.ref_time - scalar, proof_size: self.proof_size }
296	}
297
298	/// Constant version of Sub for `proof_size` component with u64.
299	///
300	/// Is only overflow safe when evaluated at compile-time.
301	pub const fn sub_proof_size(self, scalar: u64) -> Self {
302		Self { ref_time: self.ref_time, proof_size: self.proof_size - scalar }
303	}
304
305	/// Constant version of Div with u64.
306	///
307	/// Is only overflow safe when evaluated at compile-time.
308	pub const fn div(self, scalar: u64) -> Self {
309		Self { ref_time: self.ref_time / scalar, proof_size: self.proof_size / scalar }
310	}
311
312	/// Constant version of Mul with u64.
313	///
314	/// Is only overflow safe when evaluated at compile-time.
315	pub const fn mul(self, scalar: u64) -> Self {
316		Self { ref_time: self.ref_time * scalar, proof_size: self.proof_size * scalar }
317	}
318
319	/// Returns true if any of `self`'s constituent weights is strictly greater than that of the
320	/// `other`'s, otherwise returns false.
321	pub const fn any_gt(self, other: Self) -> bool {
322		self.ref_time > other.ref_time || self.proof_size > other.proof_size
323	}
324
325	/// Returns true if all of `self`'s constituent weights is strictly greater than that of the
326	/// `other`'s, otherwise returns false.
327	pub const fn all_gt(self, other: Self) -> bool {
328		self.ref_time > other.ref_time && self.proof_size > other.proof_size
329	}
330
331	/// Returns true if any of `self`'s constituent weights is strictly less than that of the
332	/// `other`'s, otherwise returns false.
333	pub const fn any_lt(self, other: Self) -> bool {
334		self.ref_time < other.ref_time || self.proof_size < other.proof_size
335	}
336
337	/// Returns true if all of `self`'s constituent weights is strictly less than that of the
338	/// `other`'s, otherwise returns false.
339	pub const fn all_lt(self, other: Self) -> bool {
340		self.ref_time < other.ref_time && self.proof_size < other.proof_size
341	}
342
343	/// Returns true if any of `self`'s constituent weights is greater than or equal to that of the
344	/// `other`'s, otherwise returns false.
345	pub const fn any_gte(self, other: Self) -> bool {
346		self.ref_time >= other.ref_time || self.proof_size >= other.proof_size
347	}
348
349	/// Returns true if all of `self`'s constituent weights is greater than or equal to that of the
350	/// `other`'s, otherwise returns false.
351	pub const fn all_gte(self, other: Self) -> bool {
352		self.ref_time >= other.ref_time && self.proof_size >= other.proof_size
353	}
354
355	/// Returns true if any of `self`'s constituent weights is less than or equal to that of the
356	/// `other`'s, otherwise returns false.
357	pub const fn any_lte(self, other: Self) -> bool {
358		self.ref_time <= other.ref_time || self.proof_size <= other.proof_size
359	}
360
361	/// Returns true if all of `self`'s constituent weights is less than or equal to that of the
362	/// `other`'s, otherwise returns false.
363	pub const fn all_lte(self, other: Self) -> bool {
364		self.ref_time <= other.ref_time && self.proof_size <= other.proof_size
365	}
366
367	/// Returns true if any of `self`'s constituent weights is equal to that of the `other`'s,
368	/// otherwise returns false.
369	pub const fn any_eq(self, other: Self) -> bool {
370		self.ref_time == other.ref_time || self.proof_size == other.proof_size
371	}
372
373	// NOTE: `all_eq` does not exist, as it's simply the `eq` method from the `PartialEq` trait.
374}
375
376impl Zero for Weight {
377	fn zero() -> Self {
378		Self::zero()
379	}
380
381	fn is_zero(&self) -> bool {
382		self == &Self::zero()
383	}
384}
385
386impl Add for Weight {
387	type Output = Self;
388	fn add(self, rhs: Self) -> Self {
389		Self {
390			ref_time: self.ref_time + rhs.ref_time,
391			proof_size: self.proof_size + rhs.proof_size,
392		}
393	}
394}
395
396impl Sub for Weight {
397	type Output = Self;
398	fn sub(self, rhs: Self) -> Self {
399		Self {
400			ref_time: self.ref_time - rhs.ref_time,
401			proof_size: self.proof_size - rhs.proof_size,
402		}
403	}
404}
405
406impl<T> Mul<T> for Weight
407where
408	T: Mul<u64, Output = u64> + Copy,
409{
410	type Output = Self;
411	fn mul(self, b: T) -> Self {
412		Self { ref_time: b * self.ref_time, proof_size: b * self.proof_size }
413	}
414}
415
416#[cfg(any(test, feature = "std"))]
417impl From<u64> for Weight {
418	fn from(value: u64) -> Self {
419		Self::from_parts(value, value)
420	}
421}
422
423#[cfg(any(test, feature = "std"))]
424impl From<(u64, u64)> for Weight {
425	fn from(value: (u64, u64)) -> Self {
426		Self::from_parts(value.0, value.1)
427	}
428}
429
430macro_rules! weight_mul_per_impl {
431	($($t:ty),* $(,)?) => {
432		$(
433			impl Mul<Weight> for $t {
434				type Output = Weight;
435				fn mul(self, b: Weight) -> Weight {
436					Weight {
437						ref_time: self * b.ref_time,
438						proof_size: self * b.proof_size,
439					}
440				}
441			}
442		)*
443	}
444}
445weight_mul_per_impl!(
446	sp_arithmetic::Percent,
447	sp_arithmetic::PerU16,
448	sp_arithmetic::Permill,
449	sp_arithmetic::Perbill,
450	sp_arithmetic::Perquintill,
451);
452
453macro_rules! weight_mul_primitive_impl {
454	($($t:ty),* $(,)?) => {
455		$(
456			impl Mul<Weight> for $t {
457				type Output = Weight;
458				fn mul(self, b: Weight) -> Weight {
459					Weight {
460						ref_time: u64::from(self) * b.ref_time,
461						proof_size: u64::from(self) * b.proof_size,
462					}
463				}
464			}
465		)*
466	}
467}
468weight_mul_primitive_impl!(u8, u16, u32, u64);
469
470impl<T> Div<T> for Weight
471where
472	u64: Div<T, Output = u64>,
473	T: Copy,
474{
475	type Output = Self;
476	fn div(self, b: T) -> Self {
477		Self { ref_time: self.ref_time / b, proof_size: self.proof_size / b }
478	}
479}
480
481impl CheckedAdd for Weight {
482	fn checked_add(&self, rhs: &Self) -> Option<Self> {
483		self.checked_add(rhs)
484	}
485}
486
487impl CheckedSub for Weight {
488	fn checked_sub(&self, rhs: &Self) -> Option<Self> {
489		self.checked_sub(rhs)
490	}
491}
492
493impl core::fmt::Display for Weight {
494	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
495		write!(f, "Weight(ref_time: {}, proof_size: {})", self.ref_time, self.proof_size)
496	}
497}
498
499impl Bounded for Weight {
500	fn min_value() -> Self {
501		Zero::zero()
502	}
503	fn max_value() -> Self {
504		Self::MAX
505	}
506}
507
508impl AddAssign for Weight {
509	fn add_assign(&mut self, other: Self) {
510		*self = Self {
511			ref_time: self.ref_time + other.ref_time,
512			proof_size: self.proof_size + other.proof_size,
513		};
514	}
515}
516
517impl SubAssign for Weight {
518	fn sub_assign(&mut self, other: Self) {
519		*self = Self {
520			ref_time: self.ref_time - other.ref_time,
521			proof_size: self.proof_size - other.proof_size,
522		};
523	}
524}
525
526#[cfg(test)]
527mod tests {
528	use super::*;
529
530	#[test]
531	fn is_zero_works() {
532		assert!(Weight::zero().is_zero());
533		assert!(!Weight::from_parts(1, 0).is_zero());
534		assert!(!Weight::from_parts(0, 1).is_zero());
535		assert!(!Weight::MAX.is_zero());
536	}
537
538	#[test]
539	fn from_parts_works() {
540		assert_eq!(Weight::from_parts(0, 0), Weight { ref_time: 0, proof_size: 0 });
541		assert_eq!(Weight::from_parts(5, 5), Weight { ref_time: 5, proof_size: 5 });
542		assert_eq!(
543			Weight::from_parts(u64::MAX, u64::MAX),
544			Weight { ref_time: u64::MAX, proof_size: u64::MAX }
545		);
546	}
547
548	#[test]
549	fn from_all_works() {
550		assert_eq!(Weight::from_all(0), Weight::from_parts(0, 0));
551		assert_eq!(Weight::from_all(5), Weight::from_parts(5, 5));
552		assert_eq!(Weight::from_all(u64::MAX), Weight::from_parts(u64::MAX, u64::MAX));
553	}
554
555	#[test]
556	fn from_u64_works() {
557		assert_eq!(Weight::from_all(0), 0_u64.into());
558		assert_eq!(Weight::from_all(123), 123_u64.into());
559		assert_eq!(Weight::from_all(u64::MAX), u64::MAX.into());
560	}
561
562	#[test]
563	fn from_u64_pair_works() {
564		assert_eq!(Weight::from_parts(0, 1), (0, 1).into());
565		assert_eq!(Weight::from_parts(123, 321), (123u64, 321u64).into());
566		assert_eq!(Weight::from_parts(u64::MAX, 0), (u64::MAX, 0).into());
567	}
568
569	#[test]
570	fn saturating_reduce_works() {
571		let mut weight = Weight::from_parts(10, 20);
572		weight.saturating_reduce(Weight::from_all(5));
573		assert_eq!(weight, Weight::from_parts(5, 15));
574		weight.saturating_reduce(Weight::from_all(5));
575		assert_eq!(weight, Weight::from_parts(0, 10));
576		weight.saturating_reduce(Weight::from_all(11));
577		assert!(weight.is_zero());
578		weight.saturating_reduce(Weight::from_all(u64::MAX));
579		assert!(weight.is_zero());
580	}
581
582	#[test]
583	fn checked_accrue_works() {
584		let mut weight = Weight::from_parts(10, 20);
585		assert!(weight.checked_accrue(Weight::from_all(2)).is_some());
586		assert_eq!(weight, Weight::from_parts(12, 22));
587		assert!(weight.checked_accrue(Weight::from_parts(u64::MAX, 0)).is_none());
588		assert!(weight.checked_accrue(Weight::from_parts(0, u64::MAX)).is_none());
589		assert_eq!(weight, Weight::from_parts(12, 22));
590		assert!(weight
591			.checked_accrue(Weight::from_parts(u64::MAX - 12, u64::MAX - 22))
592			.is_some());
593		assert_eq!(weight, Weight::MAX);
594		assert!(weight.checked_accrue(Weight::from_parts(1, 0)).is_none());
595		assert!(weight.checked_accrue(Weight::from_parts(0, 1)).is_none());
596		assert_eq!(weight, Weight::MAX);
597	}
598
599	#[test]
600	fn checked_reduce_works() {
601		let mut weight = Weight::from_parts(10, 20);
602		assert!(weight.checked_reduce(Weight::from_all(2)).is_some());
603		assert_eq!(weight, Weight::from_parts(8, 18));
604		assert!(weight.checked_reduce(Weight::from_parts(9, 0)).is_none());
605		assert!(weight.checked_reduce(Weight::from_parts(0, 19)).is_none());
606		assert_eq!(weight, Weight::from_parts(8, 18));
607		assert!(weight.checked_reduce(Weight::from_parts(8, 0)).is_some());
608		assert_eq!(weight, Weight::from_parts(0, 18));
609		assert!(weight.checked_reduce(Weight::from_parts(0, 18)).is_some());
610		assert!(weight.is_zero());
611	}
612
613	#[test]
614	fn checked_div_per_component_works() {
615		assert_eq!(
616			Weight::from_parts(10, 20).checked_div_per_component(&Weight::from_parts(2, 10)),
617			Some(2)
618		);
619		assert_eq!(
620			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(2, 10)),
621			Some(5)
622		);
623		assert_eq!(
624			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(1, 10)),
625			Some(10)
626		);
627		assert_eq!(
628			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(2, 1)),
629			Some(5)
630		);
631		assert_eq!(
632			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(0, 10)),
633			Some(20)
634		);
635		assert_eq!(
636			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(1, 0)),
637			Some(10)
638		);
639		assert_eq!(
640			Weight::from_parts(0, 200).checked_div_per_component(&Weight::from_parts(2, 3)),
641			Some(0)
642		);
643		assert_eq!(
644			Weight::from_parts(10, 0).checked_div_per_component(&Weight::from_parts(2, 3)),
645			Some(0)
646		);
647		assert_eq!(
648			Weight::from_parts(10, 200).checked_div_per_component(&Weight::from_parts(0, 0)),
649			None,
650		);
651		assert_eq!(
652			Weight::from_parts(0, 0).checked_div_per_component(&Weight::from_parts(0, 0)),
653			None,
654		);
655	}
656}