1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this
5  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 
7 #include "nsTPriorityQueue.h"
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include "gtest/gtest.h"
11 
12 template <class T, class Compare>
CheckPopSequence(const nsTPriorityQueue<T,Compare> & aQueue,const T * aExpectedSequence,const uint32_t aSequenceLength)13 void CheckPopSequence(const nsTPriorityQueue<T, Compare>& aQueue,
14                       const T* aExpectedSequence,
15                       const uint32_t aSequenceLength) {
16   nsTPriorityQueue<T, Compare> copy = aQueue.Clone();
17 
18   for (uint32_t i = 0; i < aSequenceLength; i++) {
19     EXPECT_FALSE(copy.IsEmpty());
20 
21     T pop = copy.Pop();
22     EXPECT_EQ(pop, aExpectedSequence[i]);
23   }
24 
25   EXPECT_TRUE(copy.IsEmpty());
26 }
27 
28 template <class A>
29 class MaxCompare {
30  public:
LessThan(const A & a,const A & b)31   bool LessThan(const A& a, const A& b) { return a > b; }
32 };
33 
TEST(PriorityQueue,Main)34 TEST(PriorityQueue, Main)
35 {
36   nsTPriorityQueue<int> queue;
37 
38   EXPECT_TRUE(queue.IsEmpty());
39 
40   queue.Push(8);
41   queue.Push(6);
42   queue.Push(4);
43   queue.Push(2);
44   queue.Push(10);
45   queue.Push(6);
46   EXPECT_EQ(queue.Top(), 2);
47   EXPECT_EQ(queue.Length(), 6u);
48   EXPECT_FALSE(queue.IsEmpty());
49   int expected[] = {2, 4, 6, 6, 8, 10};
50   CheckPopSequence(queue, expected, sizeof(expected) / sizeof(expected[0]));
51 
52   // copy ctor is tested by using CheckPopSequence, but check default assignment
53   // operator
54   nsTPriorityQueue<int> queue2;
55   queue2 = queue.Clone();
56   CheckPopSequence(queue2, expected, sizeof(expected) / sizeof(expected[0]));
57 
58   queue.Clear();
59   EXPECT_TRUE(queue.IsEmpty());
60 
61   // try same sequence with a max heap
62   nsTPriorityQueue<int, MaxCompare<int> > max_queue;
63   max_queue.Push(8);
64   max_queue.Push(6);
65   max_queue.Push(4);
66   max_queue.Push(2);
67   max_queue.Push(10);
68   max_queue.Push(6);
69   EXPECT_EQ(max_queue.Top(), 10);
70   int expected_max[] = {10, 8, 6, 6, 4, 2};
71   CheckPopSequence(max_queue, expected_max,
72                    sizeof(expected_max) / sizeof(expected_max[0]));
73 }
74