Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Add socket sendfile function
  • Loading branch information
rodrigocam committed Oct 26, 2020
commit 00920babba140b7c35e490288ef4e4399656b199
26 changes: 26 additions & 0 deletions vm/src/stdlib/socket.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -220,6 +221,31 @@ impl PySocket {
Ok(())
}

#[pymethod]
fn sendfile(&self, fd: i64, offset: OptionalArg<u64>, count: OptionalArg<u64>, vm: &VirtualMachine) -> PyResult<usize> {
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();
Expand Down