rquickjs_core/loader/
builtin_loader.rs1use crate::{loader::Loader, module::Declared, Ctx, Error, Module, Result};
2use alloc::{string::String, vec::Vec};
3#[cfg(not(feature = "std"))]
4use hashbrown::HashMap;
5#[cfg(feature = "std")]
6use std::collections::HashMap;
7
8#[derive(Debug, Default)]
12pub struct BuiltinLoader {
13 modules: HashMap<String, Vec<u8>>,
14}
15
16impl BuiltinLoader {
17 pub fn add_module<N: Into<String>, S: Into<Vec<u8>>>(
19 &mut self,
20 name: N,
21 source: S,
22 ) -> &mut Self {
23 self.modules.insert(name.into(), source.into());
24 self
25 }
26
27 #[must_use]
29 pub fn with_module<N: Into<String>, S: Into<Vec<u8>>>(mut self, name: N, source: S) -> Self {
30 self.add_module(name, source);
31 self
32 }
33}
34
35impl Loader for BuiltinLoader {
36 fn load<'js>(&mut self, ctx: &Ctx<'js>, path: &str) -> Result<Module<'js, Declared>> {
37 match self.modules.remove(path) {
38 Some(source) => Module::declare(ctx.clone(), path, source),
39 _ => Err(Error::new_loading(path)),
40 }
41 }
42}