From c7a66882f43cf81d3db7d81a9d1dd64986826b1e Mon Sep 17 00:00:00 2001 From: Sam Atkins Date: Fri, 20 Jan 2023 15:09:44 +0000 Subject: [PATCH] AK: Make NonnullPtrVectors shuffleable AK::shuffle() doesn't work on these, because their operator[] returns a reference to the pointed-at value, instead of to the NonnullPtr itself. --- AK/Random.h | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/AK/Random.h b/AK/Random.h index 1fc7c81c03..3d68bfa5dc 100644 --- a/AK/Random.h +++ b/AK/Random.h @@ -63,6 +63,19 @@ inline void shuffle(Collection& collection) } } +// shuffle() implementation for NonnullPtrVector, since its operator[] returns a reference to the pointed-at value +// instead of the pointer itself. +template +requires(requires(Collection collection) { collection.ptr_at(0); }) +inline void shuffle(Collection& collection) +{ + // Fisher-Yates shuffle + for (size_t i = collection.size() - 1; i >= 1; --i) { + size_t j = get_random_uniform(i + 1); + AK::swap(collection.ptr_at(i), collection.ptr_at(j)); + } +} + } #if USING_AK_GLOBALLY