Skip to content

Commit 7897a8c

Browse files
committed
filehandle: trim the filehandle slice before returning it to user
This way, once the user gets it, the filehandle slice is only as large as it needs to be. Then if the user copies it, excess unused bytes are not copied.
1 parent 8aeea4b commit 7897a8c

1 file changed

Lines changed: 13 additions & 0 deletions

File tree

src/fs/filehandle.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,16 @@ impl FileHandle {
6767
&self.raw[HANDLE_STRUCT_SIZE..]
6868
}
6969

70+
/// We allocate the "maximum" size for a file handle straight away in order to avoid needing
71+
/// multiple syscalls / reallocations whenever possible. However, that leaves raw.len()
72+
/// excessively high when the filehandle will usually be much smaller than MAX_HANDLE_SIZE.
73+
/// This function "trims" the filehandle so that the slice is only as large as it needs to be.
74+
fn trim(&mut self) {
75+
let len = self.get_handle_len() + HANDLE_STRUCT_SIZE;
76+
77+
self.raw = Box::from(&self.raw[0..len]);
78+
}
79+
7080
/// Set the `handle_bytes` field (first 4 bytes of the struct) to the given length.
7181
fn set_handle_len(&mut self, size: usize) {
7282
self.raw[0..size_of::<ffi::c_uint>()].copy_from_slice(&(size as ffi::c_uint).to_ne_bytes());
@@ -144,6 +154,9 @@ pub fn name_to_handle_at<Fd: AsFd, P: path::Arg>(
144154
mount_id_int as u64
145155
};
146156

157+
// Ensure the slice is only as large as it needs to be before returning it to the user.
158+
file_handle.trim();
159+
147160
return ret.map(|_| (file_handle, mount_id));
148161
})
149162
}

0 commit comments

Comments
 (0)