Skip to content

Commit 28c3ef1

Browse files
committed
Add os.write
1 parent 37e7972 commit 28c3ef1

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

vm/src/stdlib/os.rs

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,11 @@
11
use std::fs::File;
22
use std::fs::OpenOptions;
3-
use std::io::{ErrorKind, Read};
3+
use std::io::{ErrorKind, Read, Write};
44

55
use num_traits::cast::ToPrimitive;
66

77
use crate::function::PyFuncArgs;
8+
use crate::obj::objbytes;
89
use crate::obj::objint;
910
use crate::obj::objstr;
1011
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
@@ -132,6 +133,27 @@ fn os_read(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
132133
Ok(vm.ctx.new_bytes(buffer))
133134
}
134135

136+
fn os_write(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
137+
arg_check!(
138+
vm,
139+
args,
140+
required = [
141+
(fd, Some(vm.ctx.int_type())),
142+
(data, Some(vm.ctx.bytes_type()))
143+
]
144+
);
145+
146+
let mut file = rust_file(objint::get_value(fd).to_i64().unwrap());
147+
let written = match file.write(&objbytes::get_value(&data)) {
148+
Ok(written) => written,
149+
Err(s) => return Err(vm.new_os_error(s.to_string())),
150+
};
151+
152+
// Avoid closing the fd
153+
raw_file_number(file);
154+
Ok(vm.ctx.new_int(written))
155+
}
156+
135157
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
136158
let ctx = &vm.ctx;
137159

@@ -146,6 +168,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
146168
"close" => ctx.new_rustfunc(os_close),
147169
"error" => ctx.new_rustfunc(os_error),
148170
"read" => ctx.new_rustfunc(os_read),
171+
"write" => ctx.new_rustfunc(os_write),
149172
"name" => ctx.new_str(os_name),
150173
"O_RDONLY" => ctx.new_int(0),
151174
"O_WRONLY" => ctx.new_int(1),

0 commit comments

Comments
 (0)