summaryrefslogtreecommitdiff
path: root/src/support/unique_deferring_queue.h
blob: ad8f3967dab51d84faffb4389c06d0c768c3546e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
 * Copyright 2017 WebAssembly Community Group participants
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

//
// A FIFO queue of unique items, in which if an item is queued that already
// exists, it is placed at the end. That means that it is done at the
// last (most deferred) time from all the times it was queued.
//

#ifndef wasm_support_unique_deferring_queue_h
#define wasm_support_unique_deferring_queue_h

#include <queue>
#include <unordered_map>

namespace wasm {

template<typename T> struct UniqueDeferredQueue {
  // implemented as an internal queue, plus a map
  // that says how many times an element appears. we
  // can then skip non-final appearances. this lets us
  // avoid needing to remove elements from the middle
  // when there are duplicates.
  std::queue<T> data;
  std::unordered_map<T, size_t> count;

  size_t size() { return data.size(); }
  bool empty() { return size() == 0; }

  void push(T item) {
    data.push(item);
    count[item]++;
  }

  T pop() {
    while (1) {
      assert(!empty());
      T item = data.front();
      count[item]--;
      data.pop();
      if (count[item] == 0) {
        return item;
      }
      // skip this one, keep going
    }
  }
};

} // namespace wasm

#endif // wasm_support_unique_deferring_queue_h