Skip to content

Commit b81b76c

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 ac6e86e commit b81b76c

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
@@ -66,6 +66,16 @@ impl FileHandle {
6666
&self.raw[HANDLE_STRUCT_SIZE..]
6767
}
6868

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

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

0 commit comments

Comments
 (0)