quickjs_jit_stdlib/llrt/llrt_buffer/
file.rs1use crate::utils::time;
6use rquickjs::{
7 atom::PredefinedAtom, class::Trace, function::Opt, ArrayBuffer, Coerced, Ctx, Exception,
8 IntoJs, Object, Result, Value,
9};
10
11use super::blob::Blob;
12
13#[rquickjs::class]
14#[derive(Trace, Clone, rquickjs::JsLifetime)]
15pub struct File<'js> {
16 blob: Blob<'js>,
17 filename: String,
18 last_modified: i64,
19}
20
21#[rquickjs::methods]
22impl<'js> File<'js> {
23 #[qjs(constructor)]
24 fn new(
25 ctx: Ctx<'js>,
26 data: Value<'js>,
27 filename: Coerced<String>,
28 options: Opt<Value<'js>>,
29 ) -> Result<Self> {
30 let mut last_modified = time::now_millis();
31
32 if let Some(ref opts) = options.0 {
33 if opts.is_bool() || opts.is_float() || opts.is_int() || opts.is_string() {
34 return Err(Exception::throw_type(&ctx, "Invalid options"));
35 }
36
37 if let Some(v) = opts.as_object() {
38 if let Some(x) = v.get::<_, Option<Coerced<i64>>>("lastModified")? {
39 last_modified = x.0;
40 }
41 }
42 }
43
44 let blob = Blob::from_parts(ctx, Opt(Some(data)), options)?;
45
46 Ok(Self {
47 blob,
48 filename: filename.0,
49 last_modified,
50 })
51 }
52
53 #[qjs(get)]
54 pub fn size(&self) -> usize {
55 self.blob.size()
56 }
57
58 #[qjs(get)]
59 pub fn name(&self) -> String {
60 self.filename.clone()
61 }
62
63 #[qjs(get, rename = "type")]
64 pub fn mime_type(&self) -> String {
65 self.blob.mime_type()
66 }
67
68 #[qjs(get, rename = "lastModified")]
69 pub fn last_modified(&self) -> i64 {
70 self.last_modified
71 }
72
73 pub fn slice(
74 &self,
75 ctx: Ctx<'js>,
76 start: Opt<isize>,
77 end: Opt<isize>,
78 content_type: Opt<Value<'js>>,
79 ) -> Result<Blob<'js>> {
80 self.blob.slice_blob(&ctx, start.0, end.0, content_type.0)
81 }
82
83 pub async fn text(&mut self) -> String {
84 self.blob.text().await
85 }
86
87 #[qjs(rename = "arrayBuffer")]
88 pub async fn array_buffer(&self, ctx: Ctx<'js>) -> Result<ArrayBuffer<'js>> {
89 self.blob.array_buffer(ctx).await
90 }
91
92 pub async fn bytes(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
93 self.blob.bytes(ctx).await
94 }
95
96 #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
97 pub fn to_string_tag() -> &'static str {
98 stringify!(File)
99 }
100}
101
102impl<'js> File<'js> {
103 pub fn from_bytes(
104 ctx: &Ctx<'js>,
105 data: Vec<u8>,
106 filename: String,
107 mime_type: Option<String>,
108 ) -> Result<Self> {
109 let options = Opt(Some({
110 let obj = Object::new(ctx.clone())?;
111 obj.set("type", mime_type.clone().unwrap_or("".into()).into_js(ctx)?)?;
112 obj.into_js(ctx)?
113 }));
114 let blob = Blob::from_parts(ctx.clone(), Opt(Some(data.into_js(ctx)?)), options)?;
115
116 Ok(Self {
117 blob,
118 filename,
119 last_modified: time::now_millis(),
120 })
121 }
122
123 pub fn get_blob(&self) -> Blob<'js> {
124 self.blob.clone()
125 }
126
127 pub fn set_filename(&mut self, filename: String) {
128 self.filename = filename;
129 }
130}