wgtk/net/element/
reply.rs

1//! Reply elements, for builtin support of request/replies.
2//! These structures are used in `Bundle` structure and sub structures.
3
4use std::io::{self, Read, Write};
5
6use crate::util::io::*;
7
8use super::{Element, SimpleElement, TopElement, ElementLength};
9
10
11/// The element id for reply.
12pub const REPLY_ID: u8 = 0xFF;
13
14
15/// The element only decodes the request ID. This is used internally by bundle readers.
16#[derive(Debug)]
17pub struct ReplyHeader {
18    /// The request ID this reply is for.
19    pub request_id: u32,
20}
21
22impl SimpleElement for ReplyHeader {
23
24    fn encode(&self, write: &mut impl Write) -> io::Result<()> {
25        write.write_u32(self.request_id)
26    }
27
28    fn decode(read: &mut impl Read, _len: usize) -> io::Result<Self> {
29        Ok(Self { request_id: read.read_u32()? })
30    }
31
32}
33
34impl TopElement for ReplyHeader {
35    const LEN: ElementLength = ElementLength::Variable32;
36}
37
38
39/// A wrapper for a reply element, with the request ID and the underlying element.
40#[derive(Debug)]
41pub struct Reply<E> {
42    /// The request ID this reply is for.
43    pub request_id: u32,
44    /// The inner reply element.
45    pub element: E
46}
47
48impl<E> Reply<E> {
49
50    #[inline]
51    pub fn new(request_id: u32, element: E) -> Self {
52        Self { request_id, element }
53    }
54    
55}
56
57impl<E: Element> Element for Reply<E> {
58
59    type Config = E::Config;
60
61    fn encode(&self, write: &mut impl Write, config: &Self::Config) -> io::Result<()> {
62        write.write_u32(self.request_id)?;
63        self.element.encode(write, config)
64    }
65
66    fn decode(read: &mut impl Read, len: usize, config: &Self::Config) -> io::Result<Self> {
67        Ok(Self {
68            request_id: read.read_u32()?,
69            element: E::decode(read, len - 4, config)?,
70        })
71    }
72
73}
74
75impl<E: Element> TopElement for Reply<E> {
76    const LEN: ElementLength = ElementLength::Variable32;
77}