stake.rs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  1. use codec::{Decode, Encode};
  2. use sp_arithmetic::traits::BaseArithmetic;
  3. use sp_std::cmp::Ordering;
  4. #[derive(Encode, Decode, Clone, Copy, Default, Debug)]
  5. pub struct Stake<Balance>
  6. where
  7. Balance: Copy + BaseArithmetic,
  8. {
  9. pub new: Balance,
  10. pub transferred: Balance,
  11. }
  12. impl<Balance> Stake<Balance>
  13. where
  14. Balance: Copy + BaseArithmetic,
  15. {
  16. pub fn total(&self) -> Balance {
  17. self.new + self.transferred
  18. }
  19. pub fn add(&self, v: &Self) -> Self {
  20. Self {
  21. new: self.new + v.new,
  22. transferred: self.transferred + v.transferred,
  23. }
  24. }
  25. }
  26. impl<T: Copy + BaseArithmetic> PartialOrd for Stake<T> {
  27. fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
  28. Some(self.cmp(&other))
  29. }
  30. }
  31. impl<T: Copy + BaseArithmetic> Ord for Stake<T> {
  32. fn cmp(&self, other: &Self) -> Ordering {
  33. self.total().cmp(&other.total())
  34. }
  35. }
  36. impl<T: Copy + BaseArithmetic> PartialEq for Stake<T> {
  37. fn eq(&self, other: &Self) -> bool {
  38. self.total() == other.total()
  39. }
  40. }
  41. impl<T: Copy + BaseArithmetic> Eq for Stake<T> {}
  42. #[cfg(test)]
  43. mod tests {
  44. use super::*;
  45. #[test]
  46. fn total() {
  47. let a: u128 = 4;
  48. let b: u128 = 5;
  49. let s = Stake {
  50. new: a,
  51. transferred: b,
  52. };
  53. assert_eq!(a + b, s.total());
  54. }
  55. #[test]
  56. fn adding() {
  57. let a1: u128 = 3;
  58. let b1: u128 = 2;
  59. let a2: u128 = 5;
  60. let b2: u128 = 7;
  61. let s1 = Stake {
  62. new: a1,
  63. transferred: b1,
  64. };
  65. let s2 = Stake {
  66. new: a2,
  67. transferred: b2,
  68. };
  69. let sum = s1.add(&s2);
  70. assert_eq!(sum.new, 8);
  71. assert_eq!(sum.transferred, 9);
  72. }
  73. #[test]
  74. fn equality() {
  75. let a1: u128 = 3;
  76. let b1: u128 = 2;
  77. let a2: u128 = 2;
  78. let b2: u128 = 3;
  79. let a3: u128 = 10;
  80. let b3: u128 = 10;
  81. let s1 = Stake {
  82. new: a1,
  83. transferred: b1,
  84. };
  85. let s2 = s1;
  86. assert_eq!(s1, s2);
  87. let s3 = Stake {
  88. new: a2,
  89. transferred: b2,
  90. };
  91. assert_eq!(s1, s3);
  92. let s4 = Stake {
  93. new: a3,
  94. transferred: b3,
  95. };
  96. assert_ne!(s1, s4);
  97. }
  98. }