1#ifndef AWS_COMMON_RING_BUFFER_INL
2#define AWS_COMMON_RING_BUFFER_INL
3/*
4 * Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License").
7 * You may not use this file except in compliance with the License.
8 * A copy of the License is located at
9 *
10 * http://aws.amazon.com/apache2.0
11 *
12 * or in the "license" file accompanying this file. This file is distributed
13 * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
14 * express or implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 */
17
18#include <aws/common/ring_buffer.h>
19
20AWS_EXTERN_C_BEGIN
21/*
22 * Checks whether atomic_ptr correctly points to a memory location within the bounds of the aws_ring_buffer
23 */
24AWS_STATIC_IMPL bool aws_ring_buffer_check_atomic_ptr(
25 const struct aws_ring_buffer *ring_buf,
26 const uint8_t *atomic_ptr) {
27 return (atomic_ptr >= ring_buf->allocation && atomic_ptr <= ring_buf->allocation_end);
28}
29
30/**
31 * Checks whether the ring buffer is empty
32 */
33AWS_STATIC_IMPL bool aws_ring_buffer_is_empty(const struct aws_ring_buffer *ring_buf) {
34 uint8_t *head = (uint8_t *)aws_atomic_load_ptr(&ring_buf->head);
35 uint8_t *tail = (uint8_t *)aws_atomic_load_ptr(&ring_buf->tail);
36 return head == tail;
37}
38
39/**
40 * Evaluates the set of properties that define the shape of all valid aws_ring_buffer structures.
41 * It is also a cheap check, in the sense it run in constant time (i.e., no loops or recursion).
42 */
43AWS_STATIC_IMPL bool aws_ring_buffer_is_valid(const struct aws_ring_buffer *ring_buf) {
44 uint8_t *head = (uint8_t *)aws_atomic_load_ptr(&ring_buf->head);
45 uint8_t *tail = (uint8_t *)aws_atomic_load_ptr(&ring_buf->tail);
46 bool head_in_range = aws_ring_buffer_check_atomic_ptr(ring_buf, head);
47 bool tail_in_range = aws_ring_buffer_check_atomic_ptr(ring_buf, tail);
48 /* if head points-to the first element of the buffer then tail must too */
49 bool valid_head_tail = (head != ring_buf->allocation) || (tail == ring_buf->allocation);
50 return ring_buf && AWS_MEM_IS_READABLE(ring_buf->allocation, ring_buf->allocation_end - ring_buf->allocation) &&
51 head_in_range && tail_in_range && valid_head_tail && (ring_buf->allocator != NULL);
52}
53AWS_EXTERN_C_END
54#endif /* AWS_COMMON_RING_BUFFER_INL */
55