1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::fmt;

use ntex_bytes::{BufMut, Bytes, BytesMut};

use crate::frame::{self, FrameError, Head, Kind, Reason, StreamId};

#[derive(Clone, Eq, PartialEq)]
pub struct GoAway {
    last_stream_id: StreamId,
    error_code: Reason,
    data: Bytes,
}

impl GoAway {
    pub fn new(reason: Reason) -> Self {
        GoAway {
            last_stream_id: 0.into(),
            data: Bytes::new(),
            error_code: reason,
        }
    }

    pub fn set_last_stream_id(mut self, id: StreamId) -> Self {
        self.last_stream_id = id;
        self
    }

    pub fn set_data<T>(mut self, data: T) -> Self
    where
        Bytes: From<T>,
    {
        self.data = data.into();
        self
    }

    pub fn set_reason(mut self, error_code: Reason) -> Self {
        self.error_code = error_code;
        self
    }

    pub fn last_stream_id(&self) -> StreamId {
        self.last_stream_id
    }

    pub fn reason(&self) -> Reason {
        self.error_code
    }

    pub fn data(&self) -> &Bytes {
        &self.data
    }

    pub fn load(payload: &[u8]) -> Result<GoAway, FrameError> {
        if payload.len() < 8 {
            return Err(FrameError::BadFrameSize);
        }

        let (last_stream_id, _) = StreamId::parse(&payload[..4]);
        let error_code = unpack_octets_4!(payload, 4, u32);
        let data = Bytes::copy_from_slice(&payload[8..]);

        Ok(GoAway {
            last_stream_id,
            data,
            error_code: error_code.into(),
        })
    }

    pub fn encode(&self, dst: &mut BytesMut) {
        log::trace!("encoding GO_AWAY; code={:?}", self.error_code);
        let head = Head::new(Kind::GoAway, 0, StreamId::zero());
        head.encode(8 + self.data.len(), dst);
        dst.put_u32(self.last_stream_id.into());
        dst.put_u32(self.error_code.into());
        dst.extend_from_slice(&self.data);
    }
}

impl From<GoAway> for frame::Frame {
    fn from(src: GoAway) -> Self {
        frame::Frame::GoAway(src)
    }
}

impl fmt::Debug for GoAway {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut builder = f.debug_struct("GoAway");
        builder.field("error_code", &self.error_code);
        builder.field("last_stream_id", &self.last_stream_id);

        if !self.data.is_empty() {
            builder.field("data", &self.data);
        }

        builder.finish()
    }
}