1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use solana_sdk::{account::Account, clock::Slot};
solana_sdk::declare_id!("Feature111111111111111111111111111111111111");
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
pub struct Feature {
pub activated_at: Option<Slot>,
}
impl Feature {
pub fn size_of() -> usize {
bincode::serialized_size(&Self {
activated_at: Some(0),
})
.unwrap() as usize
}
pub fn from_account(account: &Account) -> Option<Self> {
if account.owner != id() {
None
} else {
bincode::deserialize(&account.data).ok()
}
}
pub fn to_account(&self, account: &mut Account) -> Option<()> {
bincode::serialize_into(&mut account.data[..], self).ok()
}
pub fn create_account(&self, lamports: u64) -> Account {
let data_len = Self::size_of().max(bincode::serialized_size(self).unwrap() as usize);
let mut account = Account::new(lamports, data_len, &id());
self.to_account(&mut account).unwrap();
account
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn feature_deserialize_none() {
let just_initialized = Account::new(42, Feature::size_of(), &id());
assert_eq!(
Feature::from_account(&just_initialized),
Some(Feature { activated_at: None })
);
}
#[test]
fn feature_sizeof() {
assert!(
Feature::size_of() >= bincode::serialized_size(&Feature::default()).unwrap() as usize
);
assert_eq!(Feature::default(), Feature { activated_at: None });
let features = [
Feature {
activated_at: Some(0),
},
Feature {
activated_at: Some(Slot::MAX),
},
];
for feature in &features {
assert_eq!(
Feature::size_of(),
bincode::serialized_size(feature).unwrap() as usize
);
}
}
}