Vincent Cantin
Vincent Cantin

Reputation: 17262

Rust custom adapter and generics

I am a beginner with Rust and I want to implement an adapter which takes an iterator of u8 or &u8 as input and outputs some chunks.

I don't know how to make my program compile. I made the adapter work without using ends_with_separator() where there is no constraint on the type of iterator, but now I need to define my adaptor so that it accepts only iterators of u8 or &u8 and I don't know how to do that.

pub struct Chunk<T> {
    pub data: Vec<T>,
}

pub struct Chunker<I> {
    pub iter: I,
}

impl<I> Chunker<I> {
    fn ends_with_separator(buf: &Vec<u8>) -> bool {
        match buf.last() {
            Some(v) => v % 7 == 0,
            None => true,
        }
    }
}

impl<I: Iterator> Iterator for Chunker<I> {
    type Item = Chunk<I::Item>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let mut buf = Vec::new();
        while let Some(v) = self.iter.next() {
            buf.push(v);
            if Self::ends_with_separator(&buf) {
                return Some(Chunk { data: buf });
            }
        }
        None
    }
}

fn main() {
    let chunker = Chunker { iter: (0u8..10) };
    for chunk in chunker {
        println!("{:?}", chunk.data);
    }
}

Upvotes: 0

Views: 533

Answers (1)

Vincent Cantin
Vincent Cantin

Reputation: 17262

I found the answer, my problem was purely syntaxic:

impl<I: Iterator<Item=u8>> Iterator for Chunker<I>

Upvotes: 1

Related Questions