Skip to main content

zenoh_collections/
stack_buffer.rs

1//
2// Copyright (c) 2023 ZettaScale Technology
3//
4// This program and the accompanying materials are made available under the
5// terms of the Eclipse Public License 2.0 which is available at
6// http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
7// which is available at https://www.apache.org/licenses/LICENSE-2.0.
8//
9// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
10//
11// Contributors:
12//   ZettaScale Zenoh Team, <zenoh@zettascale.tech>
13//
14use std::collections::VecDeque;
15
16#[derive(Debug)]
17pub struct StackBuffer<T> {
18    buffer: VecDeque<T>,
19}
20
21impl<T> StackBuffer<T> {
22    #[must_use]
23    pub fn new(capacity: usize) -> StackBuffer<T> {
24        let buffer = VecDeque::<T>::with_capacity(capacity);
25        StackBuffer { buffer }
26    }
27
28    #[inline]
29    pub fn push(&mut self, elem: T) -> Option<T> {
30        if self.len() < self.capacity() {
31            self.buffer.push_front(elem);
32            None
33        } else {
34            Some(elem)
35        }
36    }
37
38    #[inline]
39    pub fn pop(&mut self) -> Option<T> {
40        self.buffer.pop_front()
41    }
42
43    #[allow(dead_code)]
44    #[inline]
45    #[must_use]
46    pub fn is_empty(&self) -> bool {
47        self.buffer.is_empty()
48    }
49
50    #[inline]
51    #[must_use]
52    pub fn is_full(&self) -> bool {
53        self.len() == self.capacity()
54    }
55
56    #[inline]
57    #[must_use]
58    pub fn len(&self) -> usize {
59        self.buffer.len()
60    }
61
62    #[inline]
63    #[must_use]
64    pub fn capacity(&self) -> usize {
65        self.buffer.capacity()
66    }
67}