Skip to content

Commit ed58a55

Browse files
committed
Make segmenter as a trait, resue grandpa::Public
1 parent 8e84989 commit ed58a55

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed

src/events.rs

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -72,17 +72,25 @@ impl std::fmt::Debug for RawEvent {
7272
}
7373
}
7474

75-
/// Functions that take an input stream, consume an object, and output the serialized bytes.
76-
trait TypeSegmenterFn: Fn(&mut &[u8], &mut Vec<u8>) -> Result<(), Error> + Send {}
77-
impl<T> TypeSegmenterFn for T where
78-
T: Fn(&mut &[u8], &mut Vec<u8>) -> Result<(), Error> + Send
75+
trait TypeSegmenter: Send {
76+
/// Consumes an object from an input stream, and output the serialized bytes.
77+
fn segment(&self, input: &mut &[u8], output: &mut Vec<u8>) -> Result<(), Error>;
78+
}
79+
80+
impl<T> TypeSegmenter for PhantomData<T>
81+
where
82+
T: Codec + Send,
7983
{
84+
fn segment(&self, input: &mut &[u8], output: &mut Vec<u8>) -> Result<(), Error> {
85+
T::decode(input).map_err(Error::from)?.encode_to(output);
86+
Ok(())
87+
}
8088
}
8189

8290
/// Events decoder.
8391
pub struct EventsDecoder<T> {
8492
metadata: Metadata,
85-
type_segmenters: HashMap<String, Box<dyn TypeSegmenterFn>>,
93+
type_segmenters: HashMap<String, Box<dyn TypeSegmenter>>,
8694
marker: PhantomData<fn() -> T>,
8795
}
8896

@@ -141,15 +149,8 @@ impl<T: System> EventsDecoder<T> {
141149
let size = U::default().encode().len();
142150
// A segmenter decodes a type from an input stream (&mut &[u8]) and returns the serialized
143151
// type to the output stream (&mut Vec<u8>).
144-
self.type_segmenters.insert(
145-
name.to_string(),
146-
Box::new(
147-
|input: &mut &[u8], output: &mut Vec<u8>| -> Result<(), Error> {
148-
U::decode(input).map_err(Error::from)?.encode_to(output);
149-
Ok(())
150-
},
151-
),
152-
);
152+
self.type_segmenters
153+
.insert(name.to_string(), Box::new(PhantomData::<U>));
153154
size
154155
}
155156

@@ -221,7 +222,7 @@ impl<T: System> EventsDecoder<T> {
221222
_ => {
222223
if let Some(seg) = self.type_segmenters.get(name) {
223224
let mut buf = Vec::<u8>::new();
224-
seg(input, &mut buf)?;
225+
seg.segment(input, &mut buf)?;
225226
output.write(&buf);
226227
Ok(())
227228
} else {

0 commit comments

Comments
 (0)