From 44c1285d758e4853c550808b5e3194a0beea4631 Mon Sep 17 00:00:00 2001 From: laizy Date: Sun, 13 Sep 2020 15:23:40 +0800 Subject: [PATCH] make u128 function as const (#92) * make u128 function as const * impl iter sum for U128 --- ontio-std/src/types/num.rs | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/ontio-std/src/types/num.rs b/ontio-std/src/types/num.rs index 49e2427..6f1ea63 100644 --- a/ontio-std/src/types/num.rs +++ b/ontio-std/src/types/num.rs @@ -1,6 +1,6 @@ -use core::fmt::{Debug, Display, Result}; +use core::fmt::{Debug, Display, Formatter, Result}; +use core::iter::Sum; use core::ops::{Add, AddAssign, Div, Mul, Sub, SubAssign}; -use fixed_hash::static_assertions::_core::fmt::Formatter; #[derive(Clone, Copy, PartialOrd, PartialEq, Eq, Default)] pub struct U128(u128); @@ -16,15 +16,15 @@ impl I128 { U128(self.0 as u128) } - pub fn from_le_bytes(bs: [u8; 16]) -> Self { + pub const fn from_le_bytes(bs: [u8; 16]) -> Self { I128(i128::from_le_bytes(bs)) } - pub fn to_le_bytes(self) -> [u8; 16] { + pub const fn to_le_bytes(self) -> [u8; 16] { self.0.to_le_bytes() } - pub fn raw(self) -> i128 { + pub const fn raw(self) -> i128 { self.0 } } @@ -33,27 +33,33 @@ impl U128 { pub const fn new(val: u128) -> Self { U128(val) } - pub fn from_le_bytes(bs: [u8; 16]) -> Self { + pub const fn from_le_bytes(bs: [u8; 16]) -> Self { U128(u128::from_le_bytes(bs)) } - pub fn is_zero(self) -> bool { + pub const fn is_zero(self) -> bool { self.0 == 0 } - pub fn to_le_bytes(self) -> [u8; 16] { + pub const fn to_le_bytes(self) -> [u8; 16] { self.0.to_le_bytes() } - pub fn raw(self) -> u128 { + pub const fn raw(self) -> u128 { self.0 } - pub fn to_i128(self) -> I128 { + pub const fn to_i128(self) -> I128 { I128(self.0 as i128) } } +impl Sum for U128 { + fn sum>(iter: I) -> Self { + iter.fold(U128::new(0), Add::add) + } +} + impl Add for U128 { type Output = U128;