casper_types/account/
weight.rs

1use alloc::vec::Vec;
2
3#[cfg(feature = "datasize")]
4use datasize::DataSize;
5#[cfg(feature = "json-schema")]
6use schemars::JsonSchema;
7
8use serde::{Deserialize, Serialize};
9
10use crate::{
11    bytesrepr::{self, Error, FromBytes, ToBytes, U8_SERIALIZED_LENGTH},
12    CLType, CLTyped,
13};
14
15/// The number of bytes in a serialized [`Weight`].
16pub const WEIGHT_SERIALIZED_LENGTH: usize = U8_SERIALIZED_LENGTH;
17
18/// The weight associated with public keys in an account's associated keys.
19#[derive(PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Debug, Serialize, Deserialize)]
20#[cfg_attr(feature = "datasize", derive(DataSize))]
21#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
22#[cfg_attr(
23    feature = "json-schema",
24    schemars(rename = "AccountAssociatedKeyWeight")
25)]
26pub struct Weight(u8);
27
28impl Weight {
29    /// Maximum possible weight.
30    pub const MAX: Weight = Weight(u8::MAX);
31
32    /// Constructs a new `Weight`.
33    pub const fn new(weight: u8) -> Weight {
34        Weight(weight)
35    }
36
37    /// Returns the value of `self` as a `u8`.
38    pub fn value(self) -> u8 {
39        self.0
40    }
41}
42
43impl ToBytes for Weight {
44    fn to_bytes(&self) -> Result<Vec<u8>, Error> {
45        self.0.to_bytes()
46    }
47
48    fn serialized_length(&self) -> usize {
49        WEIGHT_SERIALIZED_LENGTH
50    }
51
52    fn write_bytes(&self, writer: &mut Vec<u8>) -> Result<(), bytesrepr::Error> {
53        writer.push(self.0);
54        Ok(())
55    }
56}
57
58impl FromBytes for Weight {
59    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
60        let (byte, rem) = u8::from_bytes(bytes)?;
61        Ok((Weight::new(byte), rem))
62    }
63}
64
65impl CLTyped for Weight {
66    fn cl_type() -> CLType {
67        CLType::U8
68    }
69}