From d1394a0a52ae98363483793d72c081f49ec866a8 Mon Sep 17 00:00:00 2001 From: Manos Pitsidianakis Date: Sun, 8 Nov 2020 20:10:44 +0200 Subject: [PATCH] Return allocation error in deserialize instead of panicking There's no way to catch allocation errors since out of memory errors cause an abort. Fail gracefully by returning the error instead of panicking. --- src/lib.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 8f4ba72..40ecde4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -233,6 +233,12 @@ pub enum CollectionAllocErr { }, } +impl fmt::Display for CollectionAllocErr { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "Allocation error: {:?}", self) + } +} + impl From for CollectionAllocErr { fn from(_: LayoutErr) -> Self { CollectionAllocErr::CapacityOverflow @@ -1543,8 +1549,10 @@ where where B: SeqAccess<'de>, { + use serde::de::Error; let len = seq.size_hint().unwrap_or(0); - let mut values = SmallVec::with_capacity(len); + let mut values = SmallVec::new(); + values.try_reserve(len).map_err(B::Error::custom)?; while let Some(value) = seq.next_element()? { values.push(value);