char/avril

(wip) why'd you have to go and make things so complicaaaaated?

git clone https://git.t4t.associates/char/avril

Charlotte Somsnapshot: capture and restore extension layouts in one artifactd71572b

main
2.3 KiB79 linesraw
1use std::collections::HashMap;
2use std::io;
3
4use crate::v8::{self, Global, WasmStreaming};
5
6const MAX_ID: u64 = 9_007_199_254_740_991;
7
8#[doc(hidden)]
9pub struct WasmStreamingStart {
10    pub id: u64,
11    pub callback: Option<Global<v8::Function>>,
12}
13
14#[doc(hidden)]
15pub struct WasmStreamingStartError {
16    pub message: String,
17    pub stream: WasmStreaming<false>,
18}
19
20#[derive(Default)]
21pub struct WasmStreamingRegistry {
22    next_id: u64,
23    callback: Option<Global<v8::Function>>,
24    streams: HashMap<u64, WasmStreaming<false>>,
25}
26
27impl WasmStreamingRegistry {
28    pub(crate) fn is_empty(&self) -> bool {
29        self.callback.is_none() && self.streams.is_empty() && self.next_id == 0
30    }
31
32    pub fn register(&mut self, callback: Global<v8::Function>) -> io::Result<()> {
33        if self.callback.is_some() {
34            return Err(io::Error::other(
35                "Wasm streaming callback is already registered",
36            ));
37        }
38        self.callback = Some(callback);
39        Ok(())
40    }
41
42    pub fn start(
43        &mut self,
44        stream: WasmStreaming<false>,
45    ) -> Result<WasmStreamingStart, WasmStreamingStartError> {
46        let callback = self.callback.as_ref().cloned();
47        let Some(id) = self.next_id.checked_add(1).filter(|id| *id <= MAX_ID) else {
48            return Err(WasmStreamingStartError {
49                message: "Wasm streaming resource IDs exhausted".to_owned(),
50                stream,
51            });
52        };
53        self.next_id = id;
54        self.streams.insert(id, stream);
55        Ok(WasmStreamingStart { id, callback })
56    }
57
58    pub fn stream_mut(&mut self, id: u64) -> io::Result<&mut WasmStreaming<false>> {
59        self.streams
60            .get_mut(&id)
61            .ok_or_else(|| io::Error::other("Wasm streaming resource is closed"))
62    }
63
64    pub fn finish(&mut self, id: u64) -> io::Result<()> {
65        self.streams
66            .remove(&id)
67            .ok_or_else(|| io::Error::other("Wasm streaming resource is closed"))?
68            .finish();
69        Ok(())
70    }
71
72    pub fn abort(&mut self, id: u64, exception: v8::Local<v8::Value>) -> io::Result<()> {
73        self.streams
74            .remove(&id)
75            .ok_or_else(|| io::Error::other("Wasm streaming resource is closed"))?
76            .abort(Some(exception));
77        Ok(())
78    }
79}