blob: dcf676be2985bda4cf8076c62ebb02daef5bd287 [file] [log] [blame]
Kristofer Jonsson3f5510f2023-02-08 14:23:00 +01001/*
2 * SPDX-FileCopyrightText: Copyright 2022-2023 Arm Limited and/or its affiliates <open-source-office@arm.com>
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 *
6 * Licensed under the Apache License, Version 2.0 (the License); you may
7 * not use _this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an AS IS BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19#pragma once
20
21/*****************************************************************************
22 * Includes
23 *****************************************************************************/
24
25#include <FreeRTOS.h>
26#include <queue.h>
27
28#include <cstdlib>
29#include <functional>
30
31#include <ethosu_log.h>
32
33/*****************************************************************************
34 * Queue
35 *****************************************************************************/
36
37template <typename T>
38class Queue {
39public:
40 using Predicate = std::function<bool(const T &data)>;
41
42 Queue(const size_t size = 10) : queue(xQueueCreate(size, sizeof(T))) {}
43
44 ~Queue() {
45 vQueueDelete(queue);
46 }
47
48 int send(const T &msg, TickType_t delay = portMAX_DELAY) {
49 if (pdPASS != xQueueSend(queue, &msg, delay)) {
50 LOG_ERR("Failed to send message");
51 return -1;
52 }
53
54 return 0;
55 }
56
57 int receive(T &msg, TickType_t delay = portMAX_DELAY) {
58 if (pdTRUE != xQueueReceive(queue, &msg, delay)) {
59 LOG_ERR("Failed to receive message");
60 return -1;
61 }
62
63 return 0;
64 }
65
66 void erase(Predicate pred) {
67 const size_t count = uxQueueMessagesWaiting(queue);
68 for (size_t i = 0; i < count; i++) {
69 T data;
70
71 if (pdPASS != xQueueReceive(queue, &data, 0)) {
72 LOG_ERR("Failed to dequeue message");
73 abort();
74 }
75
76 if (!pred(data)) {
77 if (pdPASS != xQueueSend(queue, &data, 0)) {
78 LOG_ERR("Failed to requeue message");
79 abort();
80 }
81 }
82 }
83 }
84
85private:
86 QueueHandle_t queue;
87};