-
Notifications
You must be signed in to change notification settings - Fork 9
/
file.rs
318 lines (293 loc) · 11.3 KB
/
file.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
use crate::define_jsclass;
use crate::prelude::*;
use crate::vm::context::Context;
use crate::{gc::cell::GcPointer, vm::object::JsObject};
use std::{
fs::{File, OpenOptions},
intrinsics::unlikely,
io::{Read, Write},
mem::ManuallyDrop,
};
pub(super) fn std_init_file(
mut ctx: GcPointer<Context>,
mut std: GcPointer<JsObject>,
) -> Result<(), JsValue> {
let mut ctor = JsNativeFunction::new(ctx, "File".intern(), std_file_open, 2);
let mut proto = JsObject::new_empty(ctx);
def_native_method!(ctx, proto, read, std_file_read, 0)?;
def_native_method!(ctx, proto, write, std_file_write, 1)?;
def_native_method!(ctx, proto, writeAll, std_file_write_all, 1)?;
def_native_method!(ctx, proto, readBytes, std_file_read_bytes, 0)?;
def_native_method!(ctx, proto, readBytesExact, std_file_read_bytes_exact, 1)?;
def_native_method!(ctx, proto, readBytesToEnd, std_file_read_bytes_to_end, 0)?;
def_native_method!(ctx, proto, close, std_file_close, 0)?;
ctx.global_object()
.put(ctx, "@@File".intern().private(), JsValue::new(proto), false)?;
ctor.put(ctx, "prototype".intern(), JsValue::new(proto), false)?;
std.put(ctx, "File".intern(), JsValue::new(ctor), false)?;
Ok(())
}
pub fn std_file_open(mut ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let path = args.at(0).to_string(ctx)?;
let flags = if args.at(1).is_jsstring() {
args.at(1).to_string(ctx)?
} else {
"".to_string()
};
let path = std::path::Path::new(&path);
let mut opts = OpenOptions::new();
let mut opts_ = opts
.read(flags.contains('r'))
.write(flags.contains('w'))
.create(flags.contains('+'))
.append(flags.contains('a'))
.truncate(flags.contains('t'));
let file = match opts_.open(&path) {
Ok(file) => file,
Err(e) => {
return Err(JsValue::new(ctx.new_reference_error(format!(
"Failed to open file '{}': {}",
path.display(),
e
))))
}
};
let proto = ctx
.global_object()
.get(ctx, "@@File".intern().private())?
.to_object(ctx)?;
let structure = Structure::new_indexed(ctx, Some(proto), false);
let mut obj = JsObject::new(ctx, &structure, FileObject::class(), ObjectTag::Ordinary);
*obj.data::<FileObject>() = ManuallyDrop::new(FileObject { file: Some(file) });
Ok(JsValue::new(obj))
}
/// std.File.prototype.write takes array-like object or string to write to file
/// and returns count of bytes written.
pub fn std_file_write(ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if unlikely(!this.is_class(FileObject::class())) {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.write requires file object"),
));
}
let mut buffer: Vec<u8>;
if args.at(0).is_jsobject() {
letroot!(buffer_object = stack, args.at(0).get_jsobject());
let length = crate::jsrt::get_length(ctx, &mut buffer_object)?;
buffer = Vec::with_capacity(length as _);
for i in 0..length {
let uint = buffer_object.get(ctx, Symbol::Index(i))?.to_uint32(ctx)?;
if uint <= u8::MAX as u32 {
buffer.push(uint as u8);
} else if uint <= u16::MAX as u32 {
let ne = (uint as u16).to_ne_bytes();
buffer.push(ne[0]);
buffer.push(ne[1]);
} else {
let ne = (uint as u32).to_ne_bytes();
buffer.extend(&ne);
}
}
} else {
let string = args.at(0).to_string(ctx)?;
buffer = string.as_bytes().to_vec();
}
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.write(&mut buffer) {
Ok(count) => Ok(JsValue::new(count as u32)),
Err(e) => Err(JsValue::new(JsString::new(ctx, e.to_string()))),
}
}
/// std.File.prototype.writeAll takes array-like object or string to write to file.
pub fn std_file_write_all(ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if unlikely(!this.is_class(FileObject::class())) {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.write requires file object"),
));
}
let mut buffer: Vec<u8>;
if args.at(0).is_jsobject() {
letroot!(buffer_object = stack, args.at(0).get_jsobject());
let length = crate::jsrt::get_length(ctx, &mut buffer_object)?;
buffer = Vec::with_capacity(length as _);
for i in 0..length {
let uint = buffer_object.get(ctx, Symbol::Index(i))?.to_uint32(ctx)?;
if uint <= u8::MAX as u32 {
buffer.push(uint as u8);
} else if uint <= u16::MAX as u32 {
let ne = (uint as u16).to_ne_bytes();
buffer.push(ne[0]);
buffer.push(ne[1]);
} else {
let ne = (uint as u32).to_ne_bytes();
buffer.extend(&ne);
}
}
} else {
let string = args.at(0).to_string(ctx)?;
buffer = string.as_bytes().to_vec();
}
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.write_all(&mut buffer) {
Ok(_) => Ok(JsValue::encode_undefined_value()),
Err(e) => Err(JsValue::new(JsString::new(ctx, e.to_string()))),
}
}
/// std.File.prototype.read simply reads file contents to string.
pub fn std_file_read(ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if this.is_class(FileObject::class()) {
let mut buffer = String::new();
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.read_to_string(&mut buffer) {
Ok(_) => (),
Err(e) => {
return Err(JsValue::new(JsString::new(
ctx,
format!("failed to read file contents to string: {}", e),
)))
}
}
Ok(JsValue::new(JsString::new(ctx, buffer)))
} else {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.read requires file object"),
));
}
}
/// std.File.prototype.readBytes: returns array of bytes that was read from file
pub fn std_file_read_bytes(ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if this.is_class(FileObject::class()) {
let mut buffer = Vec::new();
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.read(&mut buffer) {
Ok(_) => {
let mut arr = JsArray::new(ctx, buffer.len() as _);
for (index, byte) in buffer.iter().enumerate() {
arr.put(ctx, Symbol::Index(index as _), JsValue::new(*byte), false)?;
}
return Ok(JsValue::new(arr));
}
Err(e) => {
return Err(JsValue::new(JsString::new(
ctx,
format!("failed to read file contents to string: {}", e),
)))
}
}
} else {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.read requires file object"),
));
}
}
/// std.File.prototype.readBytesToEnd: returns array of bytes that was read from file
pub fn std_file_read_bytes_to_end(
ctx: GcPointer<Context>,
args: &Arguments,
) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if this.is_class(FileObject::class()) {
let mut buffer = Vec::new();
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.read_to_end(&mut buffer) {
Ok(_) => {
let mut arr = JsArray::new(ctx, buffer.len() as _);
for (index, byte) in buffer.iter().enumerate() {
arr.put(ctx, Symbol::Index(index as _), JsValue::new(*byte), false)?;
}
return Ok(JsValue::new(arr));
}
Err(e) => {
return Err(JsValue::new(JsString::new(
ctx,
format!("failed to read file contents to string: {}", e),
)))
}
}
} else {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.read requires file object"),
));
}
}
/// std.File.prototype.readBytesExact: returns array of bytes that was read from file
pub fn std_file_read_bytes_exact(
ctx: GcPointer<Context>,
args: &Arguments,
) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
let count = args.at(0).to_uint32(ctx)?;
if this.is_class(FileObject::class()) {
let mut buffer = vec![0u8; count as usize];
let file = match this.data::<FileObject>().file {
Some(ref mut file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File closed"))),
};
match file.read_exact(&mut buffer) {
Ok(_) => {
let mut arr = JsArray::new(ctx, buffer.len() as _);
for (index, byte) in buffer.iter().enumerate() {
arr.put(ctx, Symbol::Index(index as _), JsValue::new(*byte), false)?;
}
return Ok(JsValue::new(arr));
}
Err(e) => {
return Err(JsValue::new(JsString::new(
ctx,
format!("failed to read file contents to string: {}", e),
)))
}
}
} else {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.read requires file object"),
));
}
}
pub fn std_file_close(ctx: GcPointer<Context>, args: &Arguments) -> Result<JsValue, JsValue> {
let this = args.this.to_object(ctx)?;
if this.is_class(FileObject::class()) {
let file = match this.data::<FileObject>().file.take() {
Some(file) => file,
None => return Err(JsValue::new(JsString::new(ctx, "File already closed"))),
};
drop(file);
Ok(JsValue::new(0))
} else {
return Err(JsValue::new(
ctx.new_type_error("std.File.prototype.read requires file object"),
));
}
}
pub struct FileObject {
pub file: Option<File>,
}
extern "C" fn drop_file_fn(obj: GcPointer<JsObject>) {
unsafe { ManuallyDrop::drop(obj.data::<FileObject>()) }
}
extern "C" fn fsz() -> usize {
std::mem::size_of::<FileObject>()
}
impl JsClass for FileObject {
fn class() -> &'static Class {
define_jsclass!(FileObject, File, Some(drop_file_fn), None, Some(fsz))
}
}