Skip to content

Commit

Permalink
Sync the size_hint changes from serde
Browse files Browse the repository at this point in the history
Upstream serde has a new implementation of the cautious size hint
function, which takes into consideration the size of the elements.
Use the same implementation in serde_with.

serde-rs/serde#2495
  • Loading branch information
jonasbb committed Jul 31, 2023
1 parent b81abda commit 925fa81
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 6 deletions.
6 changes: 4 additions & 2 deletions serde_with/src/content/de.rs
Expand Up @@ -283,7 +283,7 @@ impl<'de> Visitor<'de> for ContentVisitor<'de> {
where
V: SeqAccess<'de>,
{
let mut vec = Vec::with_capacity(size_hint_cautious(visitor.size_hint()));
let mut vec = Vec::with_capacity(size_hint_cautious::<Content<'_>>(visitor.size_hint()));
while let Some(e) = visitor.next_element()? {
vec.push(e);
}
Expand All @@ -294,7 +294,9 @@ impl<'de> Visitor<'de> for ContentVisitor<'de> {
where
V: MapAccess<'de>,
{
let mut vec = Vec::with_capacity(size_hint_cautious(visitor.size_hint()));
let mut vec = Vec::with_capacity(size_hint_cautious::<(Content<'_>, Content<'_>)>(
visitor.size_hint(),
));
while let Some(kv) = visitor.next_entry()? {
vec.push(kv);
}
Expand Down
4 changes: 2 additions & 2 deletions serde_with/src/de/impls.rs
Expand Up @@ -400,7 +400,7 @@ macro_rules! seq_impl {
A: SeqAccess<'de>,
{
#[allow(clippy::redundant_closure_call)]
let mut values = ($with_capacity)(utils::size_hint_cautious(seq.size_hint()));
let mut values = ($with_capacity)(utils::size_hint_cautious::<T>(seq.size_hint()));

while let Some(value) = seq
.next_element()?
Expand Down Expand Up @@ -465,7 +465,7 @@ macro_rules! map_impl {
A: MapAccess<'de>,
{
#[allow(clippy::redundant_closure_call)]
let mut values = ($with_capacity)(utils::size_hint_cautious(map.size_hint()));
let mut values = ($with_capacity)(utils::size_hint_cautious::<(K, V)>(map.size_hint()));

while let Some((key, value)) = (map.next_entry())?.map(|(k, v): (DeserializeAsWrap::<K, KU>, DeserializeAsWrap::<V, VU>)| (k.into_inner(), v.into_inner())) {
values.insert(key, value);
Expand Down
13 changes: 11 additions & 2 deletions serde_with/src/utils.rs
Expand Up @@ -5,8 +5,17 @@ use crate::prelude::*;
/// Re-Implementation of `serde::private::de::size_hint::cautious`
#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn size_hint_cautious(hint: Option<usize>) -> usize {
core::cmp::min(hint.unwrap_or(0), 4096)
pub(crate) fn size_hint_cautious<Element>(hint: Option<usize>) -> usize {
const MAX_PREALLOC_BYTES: usize = 1024 * 1024;

if core::mem::size_of::<Element>() == 0 {
0
} else {
core::cmp::min(
hint.unwrap_or(0),
MAX_PREALLOC_BYTES / core::mem::size_of::<Element>(),
)
}
}

/// Re-Implementation of `serde::private::de::size_hint::from_bounds`
Expand Down

0 comments on commit 925fa81

Please sign in to comment.