11
11
#pragma once
12
12
13
13
#include <lib/libc.h>
14
+ #include "private/utils.h"
14
15
15
16
/* State is managed entirely by head/tail indices. The capacity is always
16
17
* a power of two to allow for efficient bitwise masking instead of a more
@@ -28,7 +29,7 @@ typedef struct {
28
29
} queue_t ;
29
30
30
31
/* Creates and initializes a new queue.
31
- * @capacity The desired minimum capacity. The actual capacity will be rounded
32
+ * @capacity: The desired minimum capacity. The actual capacity will be rounded
32
33
* up to the next power of two.
33
34
* Return A pointer to the newly created queue, or NULL on failure.
34
35
*/
@@ -37,7 +38,7 @@ queue_t *queue_create(int32_t capacity);
37
38
/* Destroys a queue and frees its resources.
38
39
* This operation will fail if the queue is not empty, preventing memory
39
40
* leaks of the items contained within the queue.
40
- * @q The queue to destroy.
41
+ * @q: The queue to destroy.
41
42
*
42
43
* Return 0 on success, or a negative error code on failure.
43
44
*/
@@ -46,19 +47,27 @@ int32_t queue_destroy(queue_t *q);
46
47
/* Checks if the queue is empty. */
47
48
static inline bool queue_is_empty (const queue_t * q )
48
49
{
49
- return q -> head == q -> tail ;
50
+ return ! q || q -> head == q -> tail ;
50
51
}
51
52
52
- /* Returns the number of elements currently in the queue. */
53
+ /* Returns the number of elements currently in the queue.
54
+ *
55
+ * If the queue pointer is NULL, it is treated as an empty queue
56
+ * and this function returns 0. This ensures safe behavior even
57
+ * when invalid pointers are passed.
58
+ */
53
59
static inline uint32_t queue_count (const queue_t * q )
54
60
{
61
+ /* Treat NULL queue as empty to prevent undefined behavior */
62
+ if (unlikely (!q ))
63
+ return 0u ;
55
64
return (q -> tail - q -> head + q -> size ) & q -> mask ;
56
65
}
57
66
58
67
/* Checks if the queue is full. */
59
68
static inline bool queue_is_full (const queue_t * q )
60
69
{
61
- return (( q -> tail + 1 ) & q -> mask ) == q -> head ;
70
+ return q && ((( q -> tail + 1 ) & q -> mask ) == q -> head ) ;
62
71
}
63
72
64
73
/* Adds an element to the tail of the queue (FIFO). */
0 commit comments