casper_types/
named_key.rs

1// TODO - remove once schemars stops causing warning.
2#![allow(clippy::field_reassign_with_default)]
3
4use alloc::{string::String, vec::Vec};
5
6#[cfg(feature = "datasize")]
7use datasize::DataSize;
8#[cfg(feature = "json-schema")]
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11
12use crate::bytesrepr::{self, FromBytes, ToBytes};
13
14/// A named key.
15#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Default, Debug)]
16#[cfg_attr(feature = "datasize", derive(DataSize))]
17#[cfg_attr(feature = "json-schema", derive(JsonSchema))]
18#[serde(deny_unknown_fields)]
19pub struct NamedKey {
20    /// The name of the entry.
21    pub name: String,
22    /// The value of the entry: a casper `Key` type.
23    pub key: String,
24}
25
26impl ToBytes for NamedKey {
27    fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
28        let mut buffer = bytesrepr::allocate_buffer(self)?;
29        buffer.extend(self.name.to_bytes()?);
30        buffer.extend(self.key.to_bytes()?);
31        Ok(buffer)
32    }
33
34    fn serialized_length(&self) -> usize {
35        self.name.serialized_length() + self.key.serialized_length()
36    }
37}
38
39impl FromBytes for NamedKey {
40    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
41        let (name, remainder) = String::from_bytes(bytes)?;
42        let (key, remainder) = String::from_bytes(remainder)?;
43        let named_key = NamedKey { name, key };
44        Ok((named_key, remainder))
45    }
46}