pub trait Adapter {
type Item;
// Required method
fn adapt(&mut self, v: Option<Result<Vec<u8>, RcErr>>) -> Option<Self::Item>;
}
Expand description
Trait used to implement a CustomChunker
by
transforming the output of a ByteChunker
.
This is more powerful than simply calling
.map()
,
.map_while()
,
or .filter_map()
on a ByteChunker
because the type implementing Adapter
can be stateful.
The example below shows a struct implementing Adapter
to count the number of
chunks returned so far.
use regex_chunker::{Adapter, ByteChunker, RcErr};
use std::io::Cursor;
struct ChunkCounter {
lines: usize,
}
impl Adapter for ChunkCounter {
type Item = Result<Vec<u8>, RcErr>;
fn adapt(&mut self, v: Option<Result<Vec<u8>, RcErr>>) -> Option<Self::Item> {
match v {
Some(Ok(v)) => {
self.lines += 1;
Some(Ok(v))
},
x => x,
}
}
}
let text =
br#"What's he that wishes so?
My cousin Westmoreland? No, my fair cousin:
If we are mark'd to die, we are enow
To do our country loss; and if to live,
The fewer men, the greater share of honour."#;
let c = Cursor::new(text);
let mut chunker = ByteChunker::new(c, r#"\r?\n"#)?
.with_adapter(ChunkCounter { lines: 0 });
let _: Vec<String> = (&mut chunker).map(|res| {
let v: Vec<u8> = res.unwrap();
String::from_utf8(v).unwrap()
}).collect();
// Prints "5".
println!("{}", &chunker.get_adapter().lines);
Required Associated Types§
Sourcetype Item
type Item
The type into which it transforms the values returned by the
ByteChunker
’s Iterator
implementation.