From 205e16de63a2a642394202ab57a06ff07273064d Mon Sep 17 00:00:00 2001 From: Ben Clayton Date: Wed, 30 Nov 2022 01:16:53 +0000 Subject: [PATCH] tint/utils: Add Vector::Sort() Convenience helper Change-Id: I1d9fabcb1a89df1bc23a1e8805e5fd1caa68500b Reviewed-on: https://dawn-review.googlesource.com/c/dawn/+/112285 Kokoro: Ben Clayton Reviewed-by: Dan Sinclair Commit-Queue: Ben Clayton --- src/tint/utils/vector.h | 13 +++++++++++++ src/tint/utils/vector_test.cc | 14 +++++++++++++- 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/tint/utils/vector.h b/src/tint/utils/vector.h index ecee17053e..cefd536a1e 100644 --- a/src/tint/utils/vector.h +++ b/src/tint/utils/vector.h @@ -423,6 +423,19 @@ class Vector { return val; } + /// Sort sorts the vector in-place using the predicate function @p pred + /// @param pred a function that has the signature `bool(const T& a, const T& b)` which returns + /// true if `a` is ordered before `b`. + template + void Sort(PREDICATE&& pred) { + std::sort(begin(), end(), std::forward(pred)); + } + + /// Sort sorts the vector in-place using `T::operator<()` + void Sort() { + Sort([](auto& a, auto& b) { return a < b; }); + } + /// @returns true if the vector is empty. bool IsEmpty() const { return impl_.slice.len == 0; } diff --git a/src/tint/utils/vector_test.cc b/src/tint/utils/vector_test.cc index 9a9bb4b455..8e6fa7a51c 100644 --- a/src/tint/utils/vector_test.cc +++ b/src/tint/utils/vector_test.cc @@ -17,7 +17,7 @@ #include #include -#include "gtest/gtest.h" +#include "gmock/gmock.h" #include "src/tint/utils/bitcast.h" @@ -2009,6 +2009,18 @@ TEST(TintVectorRefTest, Index) { EXPECT_EQ(vec_ref[1], "two"); } +TEST(TintVectorRefTest, Sort) { + Vector vec{1, 5, 3, 4, 2}; + vec.Sort(); + EXPECT_THAT(vec, testing::ElementsAre(1, 2, 3, 4, 5)); +} + +TEST(TintVectorRefTest, SortPredicate) { + Vector vec{1, 5, 3, 4, 2}; + vec.Sort([](int a, int b) { return b < a; }); + EXPECT_THAT(vec, testing::ElementsAre(5, 4, 3, 2, 1)); +} + TEST(TintVectorRefTest, ConstIndex) { Vector vec{"one", "two"}; const VectorRef vec_ref(vec);