1 // Copyright (c) 2023 Huawei Device Co., Ltd.
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 //     http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 //! defines `BodyDataRef`.
15 
16 use std::pin::Pin;
17 use std::task::{Context, Poll};
18 
19 use ylong_http::h2::{ErrorCode, H2Error};
20 
21 use crate::runtime::{AsyncRead, ReadBuf};
22 use crate::util::request::RequestArc;
23 
24 pub(crate) struct BodyDataRef {
25     body: Option<RequestArc>,
26 }
27 
28 impl BodyDataRef {
new(request: RequestArc) -> Self29     pub(crate) fn new(request: RequestArc) -> Self {
30         Self {
31             body: Some(request),
32         }
33     }
34 
clear(&mut self)35     pub(crate) fn clear(&mut self) {
36         self.body = None;
37     }
38 
poll_read( &mut self, cx: &mut Context<'_>, buf: &mut [u8], ) -> Poll<Result<usize, H2Error>>39     pub(crate) fn poll_read(
40         &mut self,
41         cx: &mut Context<'_>,
42         buf: &mut [u8],
43     ) -> Poll<Result<usize, H2Error>> {
44         let request = if let Some(ref mut request) = self.body {
45             request
46         } else {
47             return Poll::Ready(Ok(0));
48         };
49         let data = request.ref_mut().body_mut();
50         let mut read_buf = ReadBuf::new(buf);
51         let data = Pin::new(data);
52         match data.poll_read(cx, &mut read_buf) {
53             Poll::Ready(Err(_e)) => {
54                 Poll::Ready(Err(H2Error::ConnectionError(ErrorCode::IntervalError)))
55             }
56             Poll::Ready(Ok(_)) => Poll::Ready(Ok(read_buf.filled().len())),
57             Poll::Pending => Poll::Pending,
58         }
59     }
60 }
61