quickjs_rusty/context/
builder.rs

1use super::Context;
2use crate::{console, ContextError};
3
4/// A builder for [Context](Context).
5///
6/// Create with [Context::builder](Context::builder).
7#[derive(Default)]
8pub struct ContextBuilder {
9    memory_limit: Option<usize>,
10    console_backend: Option<Box<dyn console::ConsoleBackend>>,
11}
12
13impl ContextBuilder {
14    pub fn new() -> Self {
15        Self {
16            memory_limit: None,
17            console_backend: None,
18        }
19    }
20
21    /// Sets the memory limit of the Javascript runtime (in bytes).
22    ///
23    /// If the limit is exceeded, methods like `eval` will return
24    /// a `Err(ExecutionError::Exception(JsValue::Null))`
25    // TODO: investigate why we don't get a proper exception message here.
26    pub fn memory_limit(self, max_bytes: usize) -> Self {
27        let mut s = self;
28        s.memory_limit = Some(max_bytes);
29        s
30    }
31
32    /// Set a console handler that will proxy `console.{log,trace,debug,...}`
33    /// calls.
34    ///
35    /// The given argument must implement the [console::ConsoleBackend] trait.
36    ///
37    /// A very simple logger could look like this:
38    pub fn console<B>(mut self, backend: B) -> Self
39    where
40        B: console::ConsoleBackend,
41    {
42        self.console_backend = Some(Box::new(backend));
43        self
44    }
45
46    /// Finalize the builder and build a JS Context.
47    pub fn build(self) -> Result<Context, ContextError> {
48        let context = Context::new(self.memory_limit)?;
49        if let Some(be) = self.console_backend {
50            context.set_console(be).map_err(ContextError::Execution)?;
51        }
52        Ok(context)
53    }
54}