1use crate::{
2 declaration::AllocationDeclaration, key::StableKey, slot::AllocationSlotDescriptor,
3 substrate::StorageSubstrate,
4};
5use serde::{Deserialize, Serialize};
6
7#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
12pub struct ValidatedAllocations {
13 generation: u64,
15 declarations: Vec<AllocationDeclaration>,
17 runtime_fingerprint: Option<String>,
19}
20
21impl ValidatedAllocations {
22 pub(crate) const fn new(
23 generation: u64,
24 declarations: Vec<AllocationDeclaration>,
25 runtime_fingerprint: Option<String>,
26 ) -> Self {
27 Self {
28 generation,
29 declarations,
30 runtime_fingerprint,
31 }
32 }
33
34 pub(crate) const fn with_generation(mut self, generation: u64) -> Self {
35 self.generation = generation;
36 self
37 }
38
39 #[must_use]
41 pub const fn generation(&self) -> u64 {
42 self.generation
43 }
44
45 #[must_use]
47 pub fn declarations(&self) -> &[AllocationDeclaration] {
48 &self.declarations
49 }
50
51 #[must_use]
53 pub fn runtime_fingerprint(&self) -> Option<&str> {
54 self.runtime_fingerprint.as_deref()
55 }
56
57 #[must_use]
59 pub fn slot_for(&self, key: &StableKey) -> Option<&AllocationSlotDescriptor> {
60 self.declarations
61 .iter()
62 .find(|declaration| &declaration.stable_key == key)
63 .map(|declaration| &declaration.slot)
64 }
65}
66
67pub struct AllocationSession<S: StorageSubstrate> {
72 substrate: S,
73 validated: ValidatedAllocations,
74}
75
76impl<S: StorageSubstrate> AllocationSession<S> {
77 #[must_use]
79 pub const fn new(substrate: S, validated: ValidatedAllocations) -> Self {
80 Self {
81 substrate,
82 validated,
83 }
84 }
85
86 #[must_use]
88 pub const fn validated(&self) -> &ValidatedAllocations {
89 &self.validated
90 }
91
92 pub fn open(
94 &self,
95 key: &StableKey,
96 ) -> Result<S::MemoryHandle, AllocationSessionError<S::Error>> {
97 let slot = self
98 .validated
99 .slot_for(key)
100 .ok_or_else(|| AllocationSessionError::UnknownStableKey(key.clone()))?;
101 self.substrate
102 .open_slot(slot)
103 .map_err(AllocationSessionError::Substrate)
104 }
105}
106
107#[derive(Clone, Debug, Eq, thiserror::Error, PartialEq)]
112pub enum AllocationSessionError<E> {
113 #[error("stable key '{0}' was not validated for this allocation session")]
115 UnknownStableKey(StableKey),
116 #[error("storage substrate failed to open allocation slot")]
118 Substrate(E),
119}