Skip to content

Commit

Permalink
now with less memory leaks
Browse files Browse the repository at this point in the history
  • Loading branch information
dankmeme01 committed Dec 17, 2023
1 parent ff6f96c commit e0bcf5c
Showing 1 changed file with 16 additions and 3 deletions.
19 changes: 16 additions & 3 deletions server/esp/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -345,13 +345,26 @@ macro_rules! impl_extread {
// [(); N].try_map(|_| self.read_value::<T>())
// ^^ i would love to only use safe rust but a ~10% performance difference is a bit too big to ignore

let mut a = MaybeUninit::<T>::uninit_array::<N>();
let mut arr = MaybeUninit::<T>::uninit_array::<N>();
for i in 0..N {
a[i].write(self.read_value::<T>()?);
match self.read_value::<T>() {
Ok(val) => arr[i].write(val),
Err(err) => {
// cleanup the previous values and return the error
for j in 0..i {
// safety: we know that `j < i`, and we know that all elements in `arr` that are before `arr[i]` must already be initialized
unsafe {
arr[j].assume_init_drop();
}
}

return Err(err);
}
};
}

// safety: we have initialized all values as seen above. if decoding failed at any moment, this step woudln't be reachable.
Ok(a.map(|x| unsafe { x.assume_init() }))
Ok(arr.map(|x| unsafe { x.assume_init() }))
}

#[inline]
Expand Down

0 comments on commit e0bcf5c

Please sign in to comment.