casper_event_standard/
schema.rs1use alloc::{collections::BTreeMap, string::String, vec::Vec};
2use casper_types::{
3 bytesrepr::{self, FromBytes, ToBytes},
4 CLType, CLTyped,
5};
6
7#[cfg(feature = "serde")]
8use serde::{Deserialize, Serialize};
9
10use crate::{cl_type2::CLType2, EventInstance};
11
12#[derive(Default, Debug, PartialEq, Clone)]
14#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
15pub struct Schema(Vec<(String, CLType2)>);
16
17impl Schema {
18 pub fn new() -> Self {
20 Self::default()
21 }
22
23 pub fn with_elem(&mut self, name: &str, ty: CLType) {
25 self.0.push((String::from(name), CLType2(ty)));
26 }
27
28 pub fn to_vec(self) -> Vec<(String, CLType2)> {
30 self.0
31 }
32}
33
34impl CLTyped for Schema {
35 fn cl_type() -> CLType {
36 Vec::<(String, CLType2)>::cl_type()
37 }
38}
39
40impl ToBytes for Schema {
41 fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
42 self.0.to_bytes()
43 }
44
45 fn serialized_length(&self) -> usize {
46 self.0.serialized_length()
47 }
48}
49
50impl FromBytes for Schema {
51 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
52 Vec::<(String, CLType2)>::from_bytes(bytes).map(|(map, bytes)| (Schema(map), bytes))
53 }
54}
55
56#[derive(Default, Debug, PartialEq, Clone)]
58#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
59pub struct Schemas(pub BTreeMap<String, Schema>);
60
61impl Schemas {
62 pub fn new() -> Self {
64 Self::default()
65 }
66
67 pub fn add<T: EventInstance>(&mut self) {
69 self.0.insert(T::name(), T::schema());
70 }
71
72 pub fn with<T: EventInstance>(mut self) -> Self {
78 self.add::<T>();
79 self
80 }
81}
82
83impl CLTyped for Schemas {
84 fn cl_type() -> CLType {
85 BTreeMap::<String, Schema>::cl_type()
86 }
87}
88
89impl ToBytes for Schemas {
90 fn to_bytes(&self) -> Result<Vec<u8>, bytesrepr::Error> {
91 self.0.to_bytes()
92 }
93
94 fn serialized_length(&self) -> usize {
95 self.0.serialized_length()
96 }
97}
98
99impl FromBytes for Schemas {
100 fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), bytesrepr::Error> {
101 BTreeMap::<String, Schema>::from_bytes(bytes).map(|(map, bytes)| (Schemas(map), bytes))
102 }
103}