diff --git a/vm/src/stdlib/socket.rs b/vm/src/stdlib/socket.rs index 02794251f..b16cb8ef0 100644 --- a/vm/src/stdlib/socket.rs +++ b/vm/src/stdlib/socket.rs @@ -21,6 +21,7 @@ use crate::pyobject::{ BorrowValue, Either, IntoPyObject, PyClassImpl, PyObjectRef, PyRef, PyResult, PyValue, StaticType, TryFromObject, }; +use crate::stdlib::os::rust_file; use crate::vm::VirtualMachine; #[cfg(unix)] @@ -220,6 +221,31 @@ impl PySocket { Ok(()) } + #[pymethod] + fn sendfile(&self, fd: i64, offset: OptionalArg, count: OptionalArg, vm: &VirtualMachine) -> PyResult { + let mut file = rust_file(fd); + let mut bufsize: u64 = 0; + + if let Ok(metadata) = file.metadata() { + bufsize = metadata.len(); + } + + if let OptionalArg::Present(c) = count { + bufsize = c; + } + + let mut buffer = vec![0u8; bufsize as usize]; + + let n = file + .read(&mut buffer) + .map_err(|err| err.into_pyexception(vm))?; + + buffer.truncate(n); + + let bytes = PyBytesLike::try_from_object(vm, vm.ctx.new_bytes(buffer))?; + self.send(bytes, vm) + } + #[pymethod] fn close(&self) { *self.sock_mut() = invalid_sock();