Skip to content

Commit a30a736

Browse files
committed
Don't borrow mutably appdata container when working with require content cache
1 parent 8e1df48 commit a30a736

1 file changed

Lines changed: 21 additions & 16 deletions

File tree

src/luau/require.rs

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -455,34 +455,39 @@ unsafe fn write_to_buffer(
455455
size_out: *mut usize,
456456
data_fetcher: impl Fn() -> IoResult<Vec<u8>>,
457457
) -> WriteResult {
458-
struct DataCache(Vec<u8>);
458+
struct DataCache(Option<Vec<u8>>);
459459

460460
// The initial buffer size can be too small, to avoid making a second data fetch call,
461461
// we cache the content in the first call, and then re-use it.
462462

463463
let lua = Lua::get_or_init_from_ptr(state);
464-
if let Some(data_cache) = lua.app_data_ref::<DataCache>() {
465-
let data_len = data_cache.0.len();
466-
mlua_assert!(data_len <= buffer_size, "buffer is too small");
467-
*size_out = data_len;
468-
ptr::copy_nonoverlapping(data_cache.0.as_ptr(), buffer as *mut _, data_len);
469-
drop(data_cache);
470-
lua.remove_app_data::<DataCache>();
471-
return WriteResult::Success;
464+
match lua.try_app_data_mut::<DataCache>() {
465+
Ok(Some(mut data_cache)) => {
466+
if let Some(data) = data_cache.0.take() {
467+
mlua_assert!(data.len() <= buffer_size, "buffer is too small");
468+
*size_out = data.len();
469+
ptr::copy_nonoverlapping(data.as_ptr(), buffer as *mut _, data.len());
470+
return WriteResult::Success;
471+
}
472+
}
473+
Ok(None) => {
474+
// Init the cache
475+
_ = lua.try_set_app_data(DataCache(None));
476+
}
477+
Err(_) => {}
472478
}
473479

474480
match data_fetcher() {
475481
Ok(data) => {
476-
let data_len = data.len();
477-
*size_out = data_len;
478-
if data_len > buffer_size {
482+
*size_out = data.len();
483+
if *size_out > buffer_size {
479484
// Cache the data for the next call to avoid getting the contents again
480-
lua.set_app_data(DataCache(data));
481-
*size_out = data_len;
485+
if let Ok(Some(mut data_cache)) = lua.try_app_data_mut::<DataCache>() {
486+
data_cache.0 = Some(data);
487+
}
482488
return WriteResult::BufferTooSmall;
483489
}
484-
ptr::copy_nonoverlapping(data.as_ptr(), buffer as *mut _, data_len);
485-
*size_out = data_len;
490+
ptr::copy_nonoverlapping(data.as_ptr(), buffer as *mut _, data.len());
486491
WriteResult::Success
487492
}
488493
Err(_) => WriteResult::Failure,

0 commit comments

Comments
 (0)