webparse/http/http2/frame/
window_update.rs

1// Copyright 2022 - 2023 Wenmeng See the COPYRIGHT
2// file at the top-level directory of this distribution.
3// 
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8// 
9// Author: tickbh
10// -----
11// Created Date: 2023/09/01 04:39:00
12
13use algorithm::buf::{Bt, BtMut};
14use crate::{http::http2::frame::Kind, Http2Error, WebResult};
15
16use super::{StreamIdentifier, FrameHeader, frame::Frame, Flag};
17
18
19
20const SIZE_INCREMENT_MASK: u32 = 1 << 31;
21
22#[derive(Debug, Copy, Clone, Eq, PartialEq)]
23pub struct WindowUpdate {
24    stream_id: StreamIdentifier,
25    size_increment: u32,
26}
27
28impl WindowUpdate {
29    pub fn new(stream_id: StreamIdentifier, size_increment: u32) -> WindowUpdate {
30        WindowUpdate {
31            stream_id,
32            size_increment,
33        }
34    }
35
36    pub fn stream_id(&self) -> StreamIdentifier {
37        self.stream_id
38    }
39
40    pub fn size_increment(&self) -> u32 {
41        self.size_increment
42    }
43
44    /// Builds a `WindowUpdate` frame from a raw frame.
45    pub fn parse<B: Bt>(head: FrameHeader, payload: &mut B) -> WebResult<WindowUpdate> {
46        debug_assert_eq!(head.kind(), &Kind::WindowUpdate);
47        if payload.remaining() != 4 {
48            return Err(Http2Error::BadFrameSize.into());
49        }
50
51        // Clear the most significant bit, as that is reserved and MUST be ignored
52        // when received.
53        let size_increment = payload.get_u32() & !SIZE_INCREMENT_MASK;
54
55        if size_increment == 0 {
56            return Err(Http2Error::InvalidWindowUpdateValue.into());
57        }
58
59        Ok(WindowUpdate {
60            stream_id: head.stream_id(),
61            size_increment,
62        })
63    }
64
65    
66    pub(crate) fn head(&self) -> FrameHeader {
67        let mut head = FrameHeader::new(Kind::WindowUpdate, Flag::zero(), self.stream_id);
68        head.length = 4;
69        head
70    }
71
72    pub fn encode<B: Bt+BtMut>(&self, buffer: &mut B) -> crate::WebResult<usize> {
73        let mut size = 0;
74        size += self.head().encode(buffer)?;
75        size += buffer.put_u32(self.size_increment);
76        log::trace!("encoding WindowUpdate; len={}", size);
77        log::trace!("HTTP2: 编码窗口更新信息; len={}", size);
78        Ok(size)
79    }
80
81}
82
83
84
85impl<B> From<WindowUpdate> for Frame<B> {
86    fn from(src: WindowUpdate) -> Self {
87        Frame::WindowUpdate(src)
88    }
89}