custom_info/
custom_info.rs1
2fn main() {
3 slice::run();
4 string::run();
5}
6
7mod slice {
8 use std::ops::Range;
9 use splitter::{Info, Splitter};
10
11 pub fn run() {
12 #[derive(Default)]
13 struct CustomCtx {
14 cursor: usize,
15 }
16
17 #[derive(Debug, PartialEq)]
18 struct Custom<'a, T> {
19 content: &'a [T],
20 span: Range<usize>,
21 }
22
23 impl<'a, T> Info<'a, T> for Custom<'a, T> {
24 type Context = CustomCtx;
25 fn generate(ctx: &mut Self::Context, ts: &'a [T]) -> Self {
26 let start = ctx.cursor;
27 ctx.cursor += ts.len();
28 Custom { content: ts, span: start..ctx.cursor }
29 }
30 }
31
32 let sp = Splitter::new(b"bytes example", b" ").with_info::<Custom<u8>>();
33 assert_eq!(
34 sp.collect::<Vec<_>>(),
35 vec![
36 Custom { content: b"bytes", span: 0..5 },
37 Custom { content: b" ", span: 5..6 },
38 Custom { content: b"example", span: 6..13 },
39 ],
40 );
41 }
42}
43
44mod string {
45 use std::ops::Range;
46 use splitter::{StrInfo, StrSplitter};
47
48 pub fn run() {
49 #[derive(Default)]
50 struct CustomCtx {
51 cursor: usize,
52 }
53
54 #[derive(Debug, PartialEq)]
55 struct Custom<'a> {
56 content: &'a str,
57 span: Range<usize>,
58 }
59
60 impl<'a> StrInfo<'a> for Custom<'a> {
61 type Context = CustomCtx;
62 fn generate(ctx: &mut Self::Context, s: &'a str) -> Self {
63 let start = ctx.cursor;
64 ctx.cursor += s.len();
65 Custom { content: s, span: start..ctx.cursor }
66 }
67 }
68
69 let sp = StrSplitter::new("bytes example", " ").with_info::<Custom>();
70 assert_eq!(
71 sp.collect::<Vec<_>>(),
72 vec![
73 Custom { content: "bytes", span: 0..5 },
74 Custom { content: " ", span: 5..6 },
75 Custom { content: "example", span: 6..13 },
76 ],
77 );
78 }
79}