Skip to main content

ab_networking/protocols/request_response/
handlers.rs

1//! Handlers for different request-response protocols
2
3pub mod cached_piece_by_index;
4pub mod generic_request_handler;
5pub mod piece_by_index;
6pub mod segment_header;
7
8use crate::protocols::request_response::handlers::generic_request_handler::encode_to_buffer;
9use crate::protocols::request_response::request_response_factory::ResponsePayload;
10use ab_aligned_buffer::SharedAlignedBuffer;
11use ab_aligned_buffer::alignment::Align1;
12use ab_core_primitives::pieces::Piece;
13use parity_scale_codec::Encode;
14
15/// Append `prefix` and `piece` to the payload, encoded the same way as SCALE codec encodes them,
16/// without copying the contents of the piece
17fn encode_piece<P>(payload: &mut ResponsePayload, prefix: &P, piece: &Piece) -> Option<()>
18where
19    P: Encode + ?Sized,
20{
21    payload.push(encode_to_buffer(prefix)?);
22    payload.push(piece.buffer().clone());
23
24    Some(())
25}
26
27/// Decode a piece from `input`, which is the end of `payload`, without copying its contents, see
28/// [`encode_piece()`]
29fn decode_piece(
30    payload: &SharedAlignedBuffer<Align1>,
31    input: &mut &[u8],
32) -> Result<Piece, parity_scale_codec::Error> {
33    let remainder = input
34        .get(Piece::SIZE..)
35        .ok_or("Not enough bytes for a piece")?;
36    let start = payload.as_slice().len() - input.len();
37
38    let piece = u32::try_from(start)
39        .ok()
40        .zip(u32::try_from(start + Piece::SIZE).ok())
41        .and_then(|(start, end)| payload.get_slice(start..end))
42        .expect("Piece is within the payload, whose length is `u32`; qed");
43    *input = remainder;
44
45    Ok(Piece::try_from(piece).expect("Correct length; qed"))
46}