webizen_runtime/
snapshot.rs1use sha2::{Digest, Sha256};
2use std::sync::{Arc, Mutex};
3
4#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5pub enum FrameHandle {
6 CpuRgbaSlot(u8),
7}
8
9#[derive(Clone)]
10pub struct SharedFrameBuffer {
11 slots: Arc<[Mutex<Box<[u8]>>; 2]>,
12 byte_len: usize,
13}
14
15impl SharedFrameBuffer {
16 pub fn new(byte_len: usize) -> Self {
18 Self {
19 slots: Arc::new([
20 Mutex::new(vec![0u8; byte_len].into_boxed_slice()),
21 Mutex::new(vec![0u8; byte_len].into_boxed_slice()),
22 ]),
23 byte_len,
24 }
25 }
26
27 pub fn byte_len(&self) -> usize {
29 self.byte_len
30 }
31
32 pub fn with_slot<R>(&self, slot: u8, reader: impl FnOnce(&[u8]) -> R) -> Option<R> {
34 let slot = self.slots.get(slot as usize)?;
35 let guard = slot.lock().ok()?;
36 Some(reader(&guard))
37 }
38
39 pub(crate) fn overwrite_slot(&self, slot: usize, writer: impl FnOnce(&mut [u8])) -> Option<()> {
41 let slot = self.slots.get(slot)?;
42 let mut guard = slot.lock().ok()?;
43 writer(&mut guard);
44 Some(())
45 }
46}
47
48pub type StateHash = [u8; 32];
49
50pub(crate) fn compute_state_hash(bytes: &[u8]) -> StateHash {
52 let mut hasher = Sha256::new();
53 hasher.update(bytes);
54 hasher.finalize().into()
55}
56
57#[derive(Debug, Clone)]
58pub struct SimulationSnapshot {
59 pub epoch: u64,
60 pub dimensions: (u32, u32),
61 pub state_hash: StateHash,
62 pub frame: FrameHandle,
63}