Skip to content

Commit 29dabbc

Browse files
committed
Implement FileIO.read with nbytes
1 parent 27cde17 commit 29dabbc

File tree

2 files changed

+30
-6
lines changed

2 files changed

+30
-6
lines changed

tests/snippets/stdlib_io.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,9 @@
3030
fi.close()
3131
with assertRaises(ValueError):
3232
fi.read()
33+
34+
with FileIO('README.md') as fio:
35+
nres = fio.read(1)
36+
assert len(nres) == 1
37+
nres = fio.read(2)
38+
assert len(nres) == 2

vm/src/stdlib/io.rs

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -346,18 +346,36 @@ fn file_io_init(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
346346
}
347347

348348
fn file_io_read(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
349-
arg_check!(vm, args, required = [(file_io, None)]);
349+
arg_check!(
350+
vm,
351+
args,
352+
required = [(file_io, None)],
353+
optional = [(read_byte, Some(vm.ctx.int_type()))]
354+
);
350355

351356
let file_no = vm.get_attribute(file_io.clone(), "fileno")?;
352357
let raw_fd = objint::get_value(&file_no).to_i64().unwrap();
353358

354359
let mut handle = os::rust_file(raw_fd);
355360

356-
let mut bytes = vec![];
357-
match handle.read_to_end(&mut bytes) {
358-
Ok(_) => {}
359-
Err(_) => return Err(vm.new_value_error("Error reading from Buffer".to_string())),
360-
}
361+
let bytes = match read_byte {
362+
None => {
363+
let mut bytes = vec![];
364+
handle
365+
.read_to_end(&mut bytes)
366+
.map_err(|_| vm.new_value_error("Error reading from Buffer".to_string()))?;
367+
bytes
368+
}
369+
Some(read_byte) => {
370+
let mut bytes = vec![0; objint::get_value(&read_byte).to_usize().unwrap()];
371+
handle
372+
.read_exact(&mut bytes)
373+
.map_err(|_| vm.new_value_error("Error reading from Buffer".to_string()))?;
374+
let updated = os::raw_file_number(handle);
375+
vm.set_attr(file_io, "fileno", vm.ctx.new_int(updated))?;
376+
bytes
377+
}
378+
};
361379

362380
Ok(vm.ctx.new_bytes(bytes))
363381
}

0 commit comments

Comments
 (0)