I want to implement a VecDeque with a maximum size limit. I have two strategies but I can't complete either.
First approach: Inheritance by composition.
I Created a new struct:
pub struct LimVecDeque<T> {
deque: VecDeque<T>,
limit: usize,
}
And create a new push function:
impl<T> LimVecDeque<T> {
...
pub fn push (&self, elem: T) {
self.deque.push_back(elem);
if self.limit < self.deque.len() {
self.deque.pop_front();
}
}
...
}
This works but, as my program grow up, I require to add functionality to my LimVecDeque Struct. Most of them is a copy from the original VecDeque:
pub fn len(&self) -> usize {
self.deque.len()
}
I have more problems to export VecDeque::iter(). I had problems with types and iterators (I'm not very good with iterators yet). This approach forces me to clone/export each function in VecDeque into LimVecDeque. Lot of work!
Second Approach: Create a new trait and implement for VecDeque:
trait Limited {
type Elem;
pub fn push_bounded(&self, limit: usize, elem: Elem);
}
and later impl the trait with VecDeque.
But I have to pass limit value in each insertion. How can pass limit value once?
In general, What is an easy way to add functionality to an struct from std (without loosing/hiding current ones)?