rquickjs_core/loader/
builtin_loader.rs

1use crate::{loader::Loader, module::Declared, Ctx, Error, Module, Result};
2use std::collections::HashMap;
3
4/// The builtin script module loader
5///
6/// This loader can be used as the nested backing loader in user-defined loaders.
7#[derive(Debug, Default)]
8pub struct BuiltinLoader {
9    modules: HashMap<String, Vec<u8>>,
10}
11
12impl BuiltinLoader {
13    /// Add builtin script module
14    pub fn add_module<N: Into<String>, S: Into<Vec<u8>>>(
15        &mut self,
16        name: N,
17        source: S,
18    ) -> &mut Self {
19        self.modules.insert(name.into(), source.into());
20        self
21    }
22
23    /// Add builtin script module
24    #[must_use]
25    pub fn with_module<N: Into<String>, S: Into<Vec<u8>>>(mut self, name: N, source: S) -> Self {
26        self.add_module(name, source);
27        self
28    }
29}
30
31impl Loader for BuiltinLoader {
32    fn load<'js>(&mut self, ctx: &Ctx<'js>, path: &str) -> Result<Module<'js, Declared>> {
33        match self.modules.remove(path) {
34            Some(source) => Module::declare(ctx.clone(), path, source),
35            _ => Err(Error::new_loading(path)),
36        }
37    }
38}