1
+ use std:: fs;
1
2
use std:: fs:: File ;
2
3
use std:: fs:: OpenOptions ;
3
- use std:: io:: ErrorKind ;
4
+ use std:: io:: { ErrorKind , Read , Write } ;
4
5
5
6
use num_traits:: cast:: ToPrimitive ;
6
7
7
8
use crate :: function:: PyFuncArgs ;
9
+ use crate :: obj:: objbytes:: PyBytesRef ;
8
10
use crate :: obj:: objint;
11
+ use crate :: obj:: objint:: PyIntRef ;
9
12
use crate :: obj:: objstr;
13
+ use crate :: obj:: objstr:: PyStringRef ;
10
14
use crate :: pyobject:: { PyObjectRef , PyResult , TypeProtocol } ;
11
15
use crate :: vm:: VirtualMachine ;
12
16
@@ -113,6 +117,40 @@ fn os_error(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
113
117
Err ( vm. new_os_error ( msg) )
114
118
}
115
119
120
+ fn os_read ( fd : PyIntRef , n : PyIntRef , vm : & VirtualMachine ) -> PyResult {
121
+ let mut buffer = vec ! [ 0u8 ; n. as_bigint( ) . to_usize( ) . unwrap( ) ] ;
122
+ let mut file = rust_file ( fd. as_bigint ( ) . to_i64 ( ) . unwrap ( ) ) ;
123
+ match file. read_exact ( & mut buffer) {
124
+ Ok ( _) => ( ) ,
125
+ Err ( s) => return Err ( vm. new_os_error ( s. to_string ( ) ) ) ,
126
+ } ;
127
+
128
+ // Avoid closing the fd
129
+ raw_file_number ( file) ;
130
+ Ok ( vm. ctx . new_bytes ( buffer) )
131
+ }
132
+
133
+ fn os_write ( fd : PyIntRef , data : PyBytesRef , vm : & VirtualMachine ) -> PyResult {
134
+ let mut file = rust_file ( fd. as_bigint ( ) . to_i64 ( ) . unwrap ( ) ) ;
135
+ let written = match file. write ( & data) {
136
+ Ok ( written) => written,
137
+ Err ( s) => return Err ( vm. new_os_error ( s. to_string ( ) ) ) ,
138
+ } ;
139
+
140
+ // Avoid closing the fd
141
+ raw_file_number ( file) ;
142
+ Ok ( vm. ctx . new_int ( written) )
143
+ }
144
+
145
+ fn os_remove ( path : PyStringRef , vm : & VirtualMachine ) -> PyResult {
146
+ match fs:: remove_file ( & path. value ) {
147
+ Ok ( _) => ( ) ,
148
+ Err ( s) => return Err ( vm. new_os_error ( s. to_string ( ) ) ) ,
149
+ }
150
+
151
+ Ok ( vm. get_none ( ) )
152
+ }
153
+
116
154
pub fn make_module ( vm : & VirtualMachine ) -> PyObjectRef {
117
155
let ctx = & vm. ctx ;
118
156
@@ -126,6 +164,10 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
126
164
"open" => ctx. new_rustfunc( os_open) ,
127
165
"close" => ctx. new_rustfunc( os_close) ,
128
166
"error" => ctx. new_rustfunc( os_error) ,
167
+ "read" => ctx. new_rustfunc( os_read) ,
168
+ "write" => ctx. new_rustfunc( os_write) ,
169
+ "remove" => ctx. new_rustfunc( os_remove) ,
170
+ "unlink" => ctx. new_rustfunc( os_remove) ,
129
171
"name" => ctx. new_str( os_name) ,
130
172
"O_RDONLY" => ctx. new_int( 0 ) ,
131
173
"O_WRONLY" => ctx. new_int( 1 ) ,
0 commit comments