diff --git a/tensorflow/core/example/feature_util.h b/tensorflow/core/example/feature_util.h index 092fabe6cbe427..6425995e65c3f3 100644 --- a/tensorflow/core/example/feature_util.h +++ b/tensorflow/core/example/feature_util.h @@ -437,7 +437,7 @@ void AppendFeatureValues(IteratorType first, IteratorType last, using FeatureType = typename internal::FeatureTrait< typename std::iterator_traits::value_type>::Type; auto& values = *GetFeatureValues(feature); - values.Reserve(std::distance(first, last)); + values.Reserve(values.size() + std::distance(first, last)); for (auto it = first; it != last; ++it) { *values.Add() = *it; } @@ -448,7 +448,7 @@ void AppendFeatureValues(std::initializer_list container, Feature* feature) { using FeatureType = typename internal::FeatureTrait::Type; auto& values = *GetFeatureValues(feature); - values.Reserve(container.size()); + values.Reserve(values.size() + container.size()); for (auto& elt : container) { *values.Add() = std::move(elt); } @@ -464,17 +464,17 @@ template struct HasSize().size())>> : std::true_type {}; -// Reserves the container's size, if a container.size() method exists. +// Reserves additional size, if a container.size() method exists. template -auto ReserveIfSizeAvailable(const ContainerType& container, - RepeatedFieldType& values) -> +auto ReserveAdditionalIfSizeAvailable(const ContainerType& container, + RepeatedFieldType& values) -> typename std::enable_if_t::value, void> { - values.Reserve(container.size()); + values.Reserve(values.size() + container.size()); } template -auto ReserveIfSizeAvailable(const ContainerType& container, - RepeatedFieldType& values) -> +auto ReserveAdditionalIfSizeAvailable(const ContainerType& container, + RepeatedFieldType& values) -> typename std::enable_if_t::value, void> {} } // namespace internal @@ -485,7 +485,7 @@ void AppendFeatureValues(const ContainerType& container, Feature* feature) { using FeatureType = typename internal::FeatureTrait< typename std::iterator_traits::value_type>::Type; auto* values = GetFeatureValues(feature); - internal::ReserveIfSizeAvailable(container, *values); + internal::ReserveAdditionalIfSizeAvailable(container, *values); // This is equivalent to std::copy into `values` with a // RepeatedFieldBackInserter, the difference is RFBI isn't compatible with // types that we want to convert (e.g. absl::string_view -> std::string).