quickjs_jit_stdlib/llrt/llrt_buffer/
lib.rs1use crate::utils::{
6 module::{export_default, ModuleInfo},
7 object::define_subclass,
8 primordials::{BasePrimordials, Primordial},
9};
10use rquickjs::{
11 function::{Args, Constructor, Rest},
12 module::{Declarations, Exports, ModuleDef},
13 Class, Ctx, Function, IntoJs, Object, Result, Value,
14};
15
16pub use self::array_buffer_view::*;
17pub use self::blob::*;
18pub use self::buffer::*;
19pub use self::file::*;
20
21mod array_buffer_view;
22mod blob;
23mod buffer;
24mod file;
25
26pub struct BufferModule;
27
28impl ModuleDef for BufferModule {
29 fn declare(declare: &Declarations) -> Result<()> {
30 declare.declare(stringify!(Buffer))?;
31 declare.declare("atob")?;
32 declare.declare("btoa")?;
33 declare.declare("constants")?;
34 declare.declare("default")?;
35 Ok(())
36 }
37
38 fn evaluate<'js>(ctx: &Ctx<'js>, exports: &Exports<'js>) -> Result<()> {
39 let globals = ctx.globals();
40 let buf: Constructor = globals.get(stringify!(Buffer))?;
41
42 let constants = Object::new(ctx.clone())?;
43 constants.set("MAX_LENGTH", u32::MAX)?; constants.set("MAX_STRING_LENGTH", (1 << 30) - 1)?; let atob: Function = ctx.globals().get("atob")?;
47 let btoa: Function = ctx.globals().get("btoa")?;
48
49 export_default(ctx, exports, |default| {
50 default.set(stringify!(Buffer), buf)?;
51 default.set("atob", atob.into_js(ctx)?)?;
52 default.set("btoa", btoa.into_js(ctx)?)?;
53 default.set("constants", constants)?;
54 Ok(())
55 })?;
56
57 Ok(())
58 }
59}
60
61impl From<BufferModule> for ModuleInfo<BufferModule> {
62 fn from(val: BufferModule) -> Self {
63 ModuleInfo {
64 name: "buffer",
65 module: val,
66 }
67 }
68}
69
70pub fn init<'js>(ctx: &Ctx<'js>) -> Result<()> {
71 let globals = ctx.globals();
72 BasePrimordials::init(ctx)?;
73
74 let uint8array = BasePrimordials::get(ctx)?.constructor_uint8array.clone();
77 let buffer_ctor = define_subclass(
78 ctx,
79 stringify!(Buffer),
80 &uint8array,
81 |ctx: Ctx<'js>, args: Rest<Value<'js>>| {
82 let uint8array = &BasePrimordials::get(&ctx)?.constructor_uint8array;
83 let mut ctor_args = Args::new(ctx.clone(), args.0.len());
84 ctor_args.push_args(args.0)?;
85 ctor_args.construct::<Value>(uint8array)
86 },
87 )?;
88 let buffer: Object = buffer_ctor.into_value().into_object().unwrap();
89 set_prototype(ctx, buffer)?;
90
91 BufferPrimordials::init(ctx)?;
92
93 Class::<Blob>::define(&globals)?;
95
96 Class::<File>::define(&globals)?;
98
99 let _ = BufferPrimordials::get(ctx)?;
101
102 Ok(())
103}