From 28f1dd4c5bca4a2982bde781745a39133e130f4f Mon Sep 17 00:00:00 2001 From: Simon Giesecke Date: Wed, 13 Nov 2019 09:06:42 +0000 Subject: [PATCH] Bug 1595750 - Add MakeBackInserter function to create a back-inserting output iterator for nsTArray. r=froydnj Differential Revision: https://phabricator.services.mozilla.com/D52685 --HG-- extra : moz-landing-system : lando --- xpcom/ds/nsTArray.h | 24 ++++++++++++++++++++++++ xpcom/tests/gtest/TestTArray.cpp | 18 ++++++++++++++++++ 2 files changed, 42 insertions(+) diff --git a/xpcom/ds/nsTArray.h b/xpcom/ds/nsTArray.h index 4a35ff4a5071..2407ef327656 100644 --- a/xpcom/ds/nsTArray.h +++ b/xpcom/ds/nsTArray.h @@ -2730,6 +2730,30 @@ Span MakeSpan( return aTArray; } +template +class nsTArrayBackInserter + : public std::iterator { + nsTArray* mArray; + + public: + explicit nsTArrayBackInserter(nsTArray& aArray) : mArray{&aArray} {} + + template + nsTArrayBackInserter& operator=(O&& aValue) { + mArray->EmplaceBack(std::forward(aValue)); + return *this; + } + + nsTArrayBackInserter& operator*() { return *this; } + + void operator++() {} +}; + +template +auto MakeBackInserter(nsTArray& aArray) { + return nsTArrayBackInserter{aArray}; +} + } // namespace mozilla // MOZ_DBG support diff --git a/xpcom/tests/gtest/TestTArray.cpp b/xpcom/tests/gtest/TestTArray.cpp index 7b6d891d28cd..2b2460e94e41 100644 --- a/xpcom/tests/gtest/TestTArray.cpp +++ b/xpcom/tests/gtest/TestTArray.cpp @@ -443,4 +443,22 @@ TEST(TArray, RemoveElementsAt_ByIterator) ASSERT_EQ(expected, array); } +static_assert(std::is_copy_assignable&>()))>::value, + "output iteraror must be copy-assignable"); +static_assert(std::is_copy_constructible&>()))>::value, + "output iterator must be copy-constructible"); + +TEST(TArray, MakeBackInserter) +{ + const std::vector src{1, 2, 3, 4}; + nsTArray dst; + + std::copy(src.begin(), src.end(), MakeBackInserter(dst)); + + const nsTArray expected{1, 2, 3, 4}; + ASSERT_EQ(expected, dst); +} + } // namespace TestTArray