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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
//! Abstractions for the [application layer](https://en.wikipedia.org/wiki/Application_layer),
//! providing a common interface for all HTTP versions supported.
//!
//! > **You should not have to interface with this module. Use [`handle_connection`] instead.**
//!
//! The main types are [`HttpConnection`], representing a single encrypted generic http connection.
//!
//! When accepting on the [`HttpConnection`], you get a [`FatRequest`]; a [`http::Request`] with a [`Body`].
//! The [`Body`] is a stream providing the body of the request if you need it, to avoid unnecessary allocations.
use crate::prelude::{internals::*, *};
pub use response::Http1Body;

/// General error for application-level logic.
///
/// Mostly, the [`Error::Parse`], [`Error::Io`], and [`Error::H2`]
/// signal errors with the request emitted from respective library.
#[derive(Debug)]
pub enum Error {
    /// A parse error from the module [`parse`].
    Parse(utils::parse::Error),
    /// An input-output error was encountered while reading or writing.
    Io(io::Error),
    /// [`h2`] emitted an error
    #[cfg(feature = "http2")]
    H2(h2::Error),
    /// The HTTP version assumed by the client is not supported.
    /// Invalid ALPN config is a candidate.
    VersionNotSupported,
    /// You tried to push a response on a HTTP/1 connection.
    ///
    /// *Use HTTP/2 instead, or check if the [`ResponsePipe`] is HTTP/1*.
    PushOnHttp1,
    /// Client closed connection before the response could be sent.
    ClientRefusedResponse,
}
impl From<utils::parse::Error> for Error {
    #[inline]
    fn from(err: utils::parse::Error) -> Self {
        Self::Parse(err)
    }
}
impl From<io::Error> for Error {
    #[inline]
    fn from(err: io::Error) -> Self {
        if let io::ErrorKind::BrokenPipe = err.kind() {
            return Self::ClientRefusedResponse;
        }
        Self::Io(err)
    }
}
#[cfg(feature = "http2")]
impl From<h2::Error> for Error {
    #[inline]
    fn from(err: h2::Error) -> Self {
        if !err.is_io() && err.reason().is_none() {
            return Self::ClientRefusedResponse;
        }
        Self::H2(err)
    }
}
impl From<Error> for io::Error {
    fn from(err: Error) -> io::Error {
        match err {
            Error::Parse(err) => err.into(),
            Error::Io(io) => io,
            #[cfg(feature = "http2")]
            Error::H2(h2) => io::Error::new(io::ErrorKind::InvalidData, h2),

            Error::VersionNotSupported => io::Error::new(
                io::ErrorKind::InvalidData,
                "http version unsupported. Invalid ALPN config.",
            ),
            Error::PushOnHttp1 => io::Error::new(
                io::ErrorKind::InvalidInput,
                "can not push requests on http/1",
            ),
            Error::ClientRefusedResponse => {
                io::Error::new(io::ErrorKind::ConnectionReset, "client refused response")
            }
        }
    }
}

/// A single HTTP connection.
///
/// See [`HttpConnection::new`] on how to make one and
/// [`HttpConnection::accept`] on getting a [`FatRequest`].
#[derive(Debug)]
pub enum HttpConnection {
    /// A HTTP/1 connection
    Http1(Arc<Mutex<Encryption>>),
    /// A HTTP/2 connection
    ///
    /// This is boxed because a [`h2::server::Connection`] takes up
    /// over 1000 bytes of memory, and an [`Arc`] 8 bytes.
    /// It will increase performance on servers with both HTTP/1 and HTTP/2
    /// connections, but slightly hurt exclusively HTTP/2 servers.
    ///
    /// We'll see how we move forward once HTTP/3 support lands.
    #[cfg(feature = "http2")]
    Http2(Box<h2::server::Connection<Encryption, bytes::Bytes>>),
}

/// The data for [`Body::Bytes`].
#[derive(Debug)]
#[must_use]
pub struct ByteBody {
    content: Bytes,
    read: usize,
}
impl ByteBody {
    /// Get a reference to the bytes of this body.
    pub fn inner(&self) -> &Bytes {
        &self.content
    }
}
impl From<Bytes> for ByteBody {
    fn from(b: Bytes) -> Self {
        Self {
            content: b,
            read: 0,
        }
    }
}

/// A body of a [`Request`].
///
/// The inner variables are streams. To get the bytes, use [`Body::read_to_bytes()`] when needed.
///
/// Also see [`FatRequest`].
#[derive(Debug)]
pub enum Body {
    /// A body of [`Bytes`].
    ///
    /// Can be used by HTTP/2 push to simulate a GET request,
    /// or any other extensions which wants a Kvarn response.
    Bytes(ByteBody),
    /// A buffered HTTP/1 body.
    ///
    /// While the HTTP/1 headers were read, it reads too much
    /// and some of the body will be read.
    /// Therefore, the already read bytes are stored.
    /// [`Body::read_to_bytes`] leverages this and just
    /// continues writing to the buffer.
    Http1(response::Http1Body<Encryption>),
    /// A HTTP/2 body provided by [`h2`].
    #[cfg(feature = "http2")]
    Http2(h2::RecvStream),
}

/// A pipe to send a [`Response`] through.
///
/// You may also push requests if the pipe is [`ResponsePipe::Http2`]
/// by calling [`ResponsePipe::push_request`].
#[derive(Debug)]
#[must_use]
pub enum ResponsePipe {
    /// A HTTP/1 stream to send a response.
    Http1(Arc<Mutex<Encryption>>),
    /// A HTTP/2 response pipe.
    #[cfg(feature = "http2")]
    Http2(h2::server::SendResponse<Bytes>),
}
/// A pipe to send a body after the [`Response`] is sent by
/// [`ResponsePipe::send_response`].
///
/// The [`AsyncWriteExt::shutdown`] does nothing, and will immediately return with Ok(())
#[derive(Debug)]
pub enum ResponseBodyPipe {
    /// HTTP/1 pipe
    Http1(Arc<Mutex<Encryption>>),
    /// HTTP/2 pipe
    #[cfg(feature = "http2")]
    Http2(h2::SendStream<Bytes>),
}
/// A [`ResponsePipe`]-like for a pushed request-response pair.
///
/// The only logic difference between this and [`ResponsePipe`] is the
/// lack of a `push_request` method. If you want to push more than one request,
/// use the same method on [`ResponsePipe`] more times.
#[derive(Debug)]
#[must_use]
pub enum PushedResponsePipe {
    /// A HTTP/2 pushed response pipe.
    ///
    /// This is the only variant for now, but as HTTP/3
    /// is implemented, a `Http3` variant will be added.
    #[cfg(feature = "http2")]
    Http2(h2::server::SendPushedResponse<Bytes>),
}

impl HttpConnection {
    /// Creates a new [`HttpConnection`] from an [`Encryption`] stream.
    ///
    /// # Errors
    ///
    /// Returns [`Error::VersionNotSupported`] when a unsupported version is passed.
    ///
    /// Also passes errors from [`h2::server::handshake`].
    #[allow(clippy::unused_async)] // cfg
    pub async fn new(stream: Encryption, version: Version) -> Result<Self, Error> {
        #[allow(clippy::match_same_arms)] // When http2 isn't enabled
        match version {
            Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => {
                Ok(Self::Http1(Arc::new(Mutex::new(stream))))
            }
            #[cfg(feature = "http2")]
            Version::HTTP_2 => {
                let result = h2::server::Builder::new()
                    .max_concurrent_streams(512)
                    .handshake(stream)
                    .await;
                match result {
                    Ok(connection) => Ok(HttpConnection::Http2(Box::new(connection))),
                    Err(err) => Err(err.into()),
                }
            }
            #[cfg(not(feature = "http2"))]
            Version::HTTP_2 => Err(Error::VersionNotSupported),
            _ => Err(Error::VersionNotSupported),
        }
    }

    /// Accept a single request.
    /// `default_host` will be used if the `Host` header is not
    /// present on a HTTP/1.x request.
    ///
    /// # Errors
    ///
    /// Returns any errors emitted from [`h2::server::Connection::accept()`].
    #[inline]
    pub async fn accept(
        &mut self,
        default_host: Option<&[u8]>,
    ) -> Result<(Request<Body>, ResponsePipe), Error> {
        match self {
            Self::Http1(stream) => {
                let response = ResponsePipe::Http1(Arc::clone(stream));
                request::parse_http_1(Arc::clone(stream), 16 * 1024, default_host)
                    .await
                    .map(|request| (request, response))
            }
            #[cfg(feature = "http2")]
            Self::Http2(connection) => match connection.accept().await {
                Some(exchange) => match exchange {
                    Ok((request, response)) => {
                        Ok((request.map(Body::Http2), ResponsePipe::Http2(response)))
                    }
                    Err(err) => Err(err.into()),
                },
                None => Err(utils::parse::Error::Done.into()),
            },
        }
    }
    /// Ask this connection to shutdown.
    pub async fn shutdown(self) {
        match self {
            Self::Http1(h) => {
                drop(h.lock().await.shutdown().await);
            }
            #[cfg(feature = "http2")]
            Self::Http2(_h) => {}
        }
    }
}

mod request {
    use super::{
        io, response, utils, Arc, AsyncRead, Body, Bytes, Context, Encryption, Error, Mutex, Pin,
        Poll, ReadBuf, Request,
    };

    #[inline]
    pub(crate) async fn parse_http_1(
        stream: Arc<Mutex<Encryption>>,
        max_len: usize,
        default_host: Option<&[u8]>,
    ) -> Result<Request<Body>, Error> {
        let scheme = match &*stream.lock().await {
            Encryption::Tcp(_) => "http",
            #[cfg(feature = "https")]
            Encryption::TcpTls(_) => "https",
        };
        let lock = stream.lock().await;

        #[cfg(feature = "async-networking")]
        let (head, bytes) = kvarn_async::read::request(
            lock,
            max_len,
            default_host,
            scheme,
            std::time::Duration::from_secs(5),
        )
        .await?;

        #[cfg(not(feature = "async-networking"))]
        let (head, bytes) = async {
            use bytes::BytesMut;
            use kvarn_utils::{chars, parse::Error, parse::RequestParseStage, prelude::*};
            use std::io::Read;

            #[inline]
            fn contains_two_newlines(bytes: &[u8]) -> bool {
                let mut in_row = 0_u8;
                for byte in bytes.iter().copied() {
                    match byte {
                        chars::LF if in_row == 0 => in_row += 1,
                        chars::LF => return true,
                        chars::CR => {}
                        _ => in_row = 0,
                    }
                }
                false
            }

            let mut stream = lock;
            let buffer = {
                let mut buffer = BytesMut::with_capacity(512);
                let mut read = 0;
                let read = &mut read;

                loop {
                    if {
                        let buffer: &mut BytesMut = &mut buffer;
                        let read: &mut usize = read;
                        assert!(buffer.len() == *read);
                        if buffer.len() == max_len {
                            return Err(Error::HeaderTooLong);
                        }

                        if buffer.capacity() < buffer.len() + 512 {
                            if buffer.len() + 512 > max_len {
                                buffer.reserve((buffer.len() + 512) - max_len);
                            } else {
                                buffer.reserve(512);
                            }
                        }

                        unsafe { buffer.set_len(buffer.capacity()) };
                        let Encryption::Tcp(tcp) = &mut *stream;
                        let read_now = tcp.read(&mut buffer[*read..]).ok().ok_or(Error::Done)?;
                        *read += read_now;
                        unsafe { buffer.set_len(*read) };

                        read_now
                    } == 0
                    {
                        break;
                    };
                    if !(utils::valid_method(&buffer) || utils::valid_version(&buffer)) {
                        return Err(Error::Syntax);
                    }

                    if contains_two_newlines(&buffer) {
                        break;
                    }
                }
                buffer.freeze()
            };

            let mut parse_stage = RequestParseStage::Method;
            // Method is max 7 bytes long
            let mut method = [0; 7];
            let mut method_len = 0;
            let mut path_start = 0;
            let mut path_end = 0;
            // Version is at most 8 bytes long
            let mut version = [0; 8];
            let mut version_index = 0;
            let mut parsed = Request::builder();
            let mut lf_in_row = 0_u8;
            let mut header_end = 0;

            for (pos, byte) in buffer.iter().copied().enumerate() {
                header_end += 1;
                if byte == chars::CR {
                    continue;
                }
                if byte == chars::LF {
                    lf_in_row += 1;
                    if lf_in_row == 2 {
                        break;
                    }
                } else {
                    lf_in_row = 0;
                }
                match parse_stage {
                    RequestParseStage::Method => {
                        if byte == chars::SPACE || method_len == method.len() {
                            if Method::from_bytes(&buffer[..method_len]).is_err() {
                                return Err(Error::InvalidMethod);
                            }
                            parse_stage.next();
                            continue;
                        }
                        if method_len == method.len() {
                            return Err(Error::InvalidMethod);
                        }
                        method[method_len] = byte;
                        method_len += 1;
                    }
                    RequestParseStage::Path => {
                        if path_start == 0 {
                            path_start = pos;
                        }
                        if byte == chars::SPACE {
                            path_end = pos;
                            parse_stage.next();
                            continue;
                        }
                    }
                    RequestParseStage::Version => {
                        if byte == chars::LF || version_index == version.len() {
                            if parse::version(&version[..version_index]).is_none() {
                                return Err(Error::InvalidVersion);
                            }
                            parse_stage.next();
                            continue;
                        }
                        if version_index == version.len() {
                            return Err(Error::InvalidVersion);
                        }
                        version[version_index] = byte;
                        version_index += 1;
                    }
                    RequestParseStage::HeaderName(..) | RequestParseStage::HeaderValue(..) => {
                        match parsed.headers_mut() {
                            Some(h) => {
                                let (headers, end) =
                                    parse::headers(&buffer.slice(header_end - 1..))?;
                                *h = headers;
                                header_end += end;
                            }
                            None => return Err(Error::Syntax),
                        }
                        break;
                    }
                };
            }
            if path_end
                .checked_sub(path_start)
                .map_or(true, |len| len == 0)
            {
                return Err(Error::NoPath);
            }

            let host = if let Some(host) = parsed
                .headers_ref()
                .and_then(|headers| headers.get(header::HOST).map(HeaderValue::as_bytes))
                .or(default_host)
            {
                host
            } else {
                return Err(Error::NoHost);
            };

            let uri = {
                let mut uri = BytesMut::with_capacity(
                    scheme.len() + 3 + host.len() + (path_end - path_start),
                );

                uri.extend(scheme.as_bytes());
                uri.extend(b"://");
                uri.extend(host);
                uri.extend(&buffer[path_start..path_end]);
                uri.freeze()
            };

            match parsed
                .method(
                    Method::from_bytes(&method[..method_len])
                        .ok()
                        .ok_or(Error::InvalidMethod)?,
                )
                .uri(Uri::from_maybe_shared(uri).ok().ok_or(Error::InvalidPath)?)
                .version(parse::version(&version[..version_index]).ok_or(Error::InvalidVersion)?)
                .body(())
            {
                Err(err) => Err(Error::Http(err)),
                Ok(request) => Ok((request, buffer.slice(header_end - 1..))),
            }
        }
        .await?;
        let body = Body::Http1(response::Http1Body::new(
            stream,
            bytes,
            utils::get_body_length_request(&head),
        ));
        Ok(head.map(|()| body))
    }

    impl Body {
        /// Reads all bytes from [`Body`] to a [`Bytes`].
        ///
        /// # Errors
        ///
        /// Passes any errors returned from the inner reader.
        /// See [`super::Http1Body::read_to_bytes()`] and [`h2::RecvStream::poll_data()`] for more info.
        #[inline]
        pub async fn read_to_bytes(&mut self) -> io::Result<Bytes> {
            match self {
                Self::Bytes(bytes) => Ok(bytes.inner().clone()),
                Self::Http1(h1) => h1.read_to_bytes().await,
                #[cfg(feature = "http2")]
                Self::Http2(h2) => {
                    let mut bytes = bytes::BytesMut::new();
                    while let Some(result) = h2.data().await {
                        let data = result
                            .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;

                        bytes.extend_from_slice(&data);

                        h2.flow_control().release_capacity(data.len()).unwrap();
                    }
                    Ok(bytes.freeze())
                }
            }
        }
    }

    impl AsyncRead for Body {
        fn poll_read(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<io::Result<()>> {
            match self.get_mut() {
                Self::Http1(s) => unsafe { Pin::new_unchecked(s).poll_read(cx, buf) },
                #[cfg(feature = "http2")]
                Self::Http2(tls) => {
                    let data = match tls.poll_data(cx) {
                        Poll::Ready(data) => data,
                        Poll::Pending => return Poll::Pending,
                    };
                    match data {
                        Some(d) => match d {
                            Ok(data) => buf.put_slice(&data),
                            Err(err) => {
                                let err = io::Error::new(io::ErrorKind::InvalidData, err);
                                return Poll::Ready(Err(err));
                            }
                        },
                        None => return Poll::Ready(Ok(())),
                    }
                    Poll::Ready(Ok(()))
                }
                Self::Bytes(byte_body) => {
                    let rest = byte_body.inner().get(byte_body.read..).unwrap_or(&[]);
                    if rest.is_empty() {
                        return Poll::Ready(Ok(()));
                    }
                    let len = std::cmp::min(buf.remaining(), rest.len());
                    buf.put_slice(&rest[..len]);
                    byte_body.read += len;
                    cx.waker().wake_by_ref();
                    Poll::Pending
                }
            }
        }
    }
}

mod response {
    use crate::prelude::{application::*, internals::*, *};

    /// A HTTP/1 body.
    ///
    /// The reason of this type and the inner buffer is described in [`super::Body::Http1`]
    #[must_use]
    pub struct Http1Body<R: AsyncRead + Unpin> {
        reader: Arc<Mutex<R>>,
        bytes: Bytes,
        offset: usize,

        content_length: usize,
        // also update Debug implementation when adding fields
    }
    impl<R: AsyncRead + Unpin> Http1Body<R> {
        /// Creates a new body.
        ///
        /// `content_length` should be the total length of the body, found in the [`Request::headers`].
        #[inline]
        pub fn new(reader: Arc<Mutex<R>>, bytes: Bytes, content_length: usize) -> Self {
            Self {
                reader,
                bytes,
                offset: 0,

                content_length,
            }
        }
        /// Reads all bytes from `self` to a [`Bytes`].
        ///
        /// # Errors
        ///
        /// Returns any errors from the underlying reader.
        #[inline]
        pub async fn read_to_bytes(&mut self) -> io::Result<Bytes> {
            let len = self.content_length;

            if len == 0 {
                return Ok(Bytes::new());
            }
            let mut buffer = BytesMut::with_capacity(len);
            if len < self.bytes.len() {
                buffer.extend_from_slice(&self.bytes[..len]);
                self.offset = len;
            } else {
                buffer.extend_from_slice(&self.bytes);
                self.offset = self.bytes.len();
            }
            if let Ok(result) = timeout(
                Duration::from_millis(250),
                async_bits::read_to_end_or_max(&mut buffer, &mut *self, len),
            )
            .await
            {
                result?;
            } else {
                self.content_length = 0;
                return Err(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "Reading of request body timed out.",
                ));
            }

            // Don't return anything next time we are called!
            self.content_length = 0;
            Ok(buffer.freeze())
        }
    }
    impl<R: AsyncRead + Unpin + Debug> Debug for Http1Body<R> {
        fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
            let mut s = f.debug_struct(utils::ident_str!(
                Http1Body,
                R,
                R: AsyncRead + Unpin + Debug
            ));
            utils::fmt_fields!(
                s,
                (self.reader),
                (self.bytes, &"[internal buffer]".as_clean()),
                (self.offset),
                (self.content_length)
            );
            s.finish()
        }
    }
    impl<R: AsyncRead + Unpin> AsyncRead for Http1Body<R> {
        fn poll_read(
            mut self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<io::Result<()>> {
            if self.offset < self.bytes.len() {
                let remaining = buf.remaining();
                if self.bytes.len() - self.offset > remaining {
                    buf.put_slice(&self.bytes[self.offset..self.offset + remaining]);
                    self.offset += remaining;
                } else {
                    buf.put_slice(&self.bytes[self.offset..]);
                    self.offset = self.bytes.len();
                }
                cx.waker().wake_by_ref();
                Poll::Pending
            } else {
                let mut lock = self.reader.lock();
                let mut reader = match unsafe { Pin::new_unchecked(&mut lock) }.poll(cx) {
                    Poll::Pending => return Poll::Pending,
                    Poll::Ready(r) => r,
                };
                let size = buf.filled().len();
                let result = unsafe { Pin::new_unchecked(&mut *reader).poll_read(cx, buf) };
                drop(reader);
                drop(lock);
                let difference = buf.filled().len() - size;
                self.offset += difference;
                if self.offset == self.content_length {
                    return Poll::Ready(Ok(()));
                }
                result
            }
        }
    }

    impl ResponsePipe {
        /// You must ensure the [`Response::version()`] is correct before calling this function.
        /// It can be guaranteed by first calling [`Self::ensure_version_and_length()`].
        ///
        /// It is critical to [`ResponseBodyPipe::close()`], else the message won't be seen as fully transmitted.
        ///
        /// # Errors
        ///
        /// Passes any errors from writing to the stream. see [`AsyncWriteExt::write()`] and
        /// [`h2::server::SendResponse::send_response()`] for more info.
        #[inline]
        pub async fn send_response(
            &mut self,
            mut response: Response<()>,
            #[allow(unused_variables)] end_of_stream: bool,
        ) -> Result<ResponseBodyPipe, Error> {
            match self {
                Self::Http1(s) => {
                    let mut writer = s.lock().await;
                    match response
                        .headers()
                        .get("connection")
                        .map(HeaderValue::to_str)
                        .and_then(Result::ok)
                    {
                        Some("close") | None => {
                            response
                                .headers_mut()
                                .insert("connection", HeaderValue::from_static("keep-alive"));
                        }
                        _ => {}
                    }
                    let mut writer = tokio::io::BufWriter::with_capacity(512, &mut *writer);
                    async_bits::write::response(&response, b"", &mut writer).await?;
                    writer.flush().await?;
                    writer.into_inner();

                    Ok(ResponseBodyPipe::Http1(Arc::clone(s)))
                }
                #[cfg(feature = "http2")]
                Self::Http2(s) => match s.send_response(response, end_of_stream) {
                    Err(ref err) if err.get_io().is_none() && err.reason().is_none() => {
                        Err(Error::ClientRefusedResponse)
                    }
                    Err(err) => Err(err.into()),
                    Ok(pipe) => Ok(ResponseBodyPipe::Http2(pipe)),
                },
            }
        }
        /// Pushes `request` to client.
        ///
        /// # Errors
        ///
        /// If you try to push if `self` is [`ResponsePipe::Http1`], an [`Error::PushOnHttp1`] is returned.
        /// Returns errors from [`h2::server::SendResponse::push_request()`].
        #[inline]
        #[allow(clippy::needless_pass_by_value)]
        pub fn push_request(
            &mut self,
            #[allow(unused_variables)] request: Request<()>,
        ) -> Result<PushedResponsePipe, Error> {
            match self {
                Self::Http1(_) => Err(Error::PushOnHttp1),
                #[cfg(feature = "http2")]
                Self::Http2(h2) => match h2.push_request(request) {
                    Ok(pipe) => Ok(PushedResponsePipe::Http2(pipe)),
                    Err(err) => Err(err.into()),
                },
            }
        }
        /// Ensures the version and length of the `response` using the variant of [`ResponsePipe`].
        #[inline]
        pub fn ensure_version_and_length<T>(&self, response: &mut Response<T>, len: usize) {
            match self {
                Self::Http1(_) => match response.version() {
                    Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => {
                        utils::set_content_length(response.headers_mut(), len);
                    }

                    _ => *response.version_mut() = Version::HTTP_11,
                },
                #[cfg(feature = "http2")]
                Self::Http2(_) => *response.version_mut() = Version::HTTP_2,
            }
        }
    }
    #[allow(unused_variables)]
    impl PushedResponsePipe {
        /// Sends a single push response.
        ///
        /// # Errors
        ///
        /// Errors are passed from the HTTP libraries, for now only [`mod@h2`].
        /// See [`h2::server::SendPushedResponse::send_response()`] for more information.
        #[inline]
        #[allow(clippy::needless_pass_by_value)]
        pub fn send_response(
            &mut self,
            response: Response<()>,
            end_of_stream: bool,
        ) -> Result<ResponseBodyPipe, Error> {
            match self {
                #[cfg(feature = "http2")]
                Self::Http2(s) => {
                    let mut response = response;
                    *response.version_mut() = Version::HTTP_2;

                    match s.send_response(response, end_of_stream) {
                        Err(err) => Err(err.into()),
                        Ok(pipe) => Ok(ResponseBodyPipe::Http2(pipe)),
                    }
                }
                #[cfg(not(any(feature = "http2")))]
                _ => unreachable!(),
            }
        }
        /// Ensures the version of `response` depending on inner version if [`PushedResponsePipe`].
        #[inline]
        #[allow(unused_variables)]
        pub fn ensure_version<T>(&self, response: &mut Response<T>) {
            match self {
                #[cfg(feature = "http2")]
                Self::Http2(_) => *response.version_mut() = Version::HTTP_2,
                #[cfg(not(any(feature = "http2")))]
                _ => unreachable!(),
            }
        }
    }

    impl ResponseBodyPipe {
        /// Sends `data` as the body.
        ///
        /// # Errors
        ///
        /// Passes any errors from writing to the stream.
        /// See [`AsyncWriteExt::write_all()`] and [`h2::SendStream::send_data()`].
        #[inline]
        pub async fn send(&mut self, data: Bytes) -> Result<(), Error> {
            self.send_with_maybe_close(data, false).await
        }
        /// Same as [`Self::send`] but with a `end_of_stream` variable.
        #[inline]
        pub(crate) async fn send_with_maybe_close(
            &mut self,
            data: Bytes,
            end_of_stream: bool,
        ) -> Result<(), Error> {
            match self {
                Self::Http1(h1) => {
                    let mut lock = h1.lock().await;
                    lock.write_all(&data).await?;
                    if end_of_stream {
                        lock.flush().await?;
                    }
                }
                #[cfg(feature = "http2")]
                Self::Http2(h2) => h2.send_data(data, end_of_stream)?,
            }
            Ok(())
        }
        /// Closes the pipe.
        ///
        /// # Errors
        ///
        /// Passes any errors emitted when closing the writer.
        /// See [`AsyncWriteExt::flush()`] and [`h2::SendStream::send_data()`].
        #[inline]
        pub async fn close(&mut self) -> Result<(), Error> {
            match self {
                Self::Http1(h1) => h1.lock().await.flush().await.map_err(Into::into),
                #[cfg(feature = "http2")]
                Self::Http2(h2) => h2.send_data(Bytes::new(), true).map_err(Error::from),
            }
        }
    }
    impl AsyncRead for ResponseBodyPipe {
        fn poll_read(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> Poll<io::Result<()>> {
            match self.get_mut() {
                Self::Http1(s) => match s.try_lock() {
                    Err(_) => Poll::Pending,
                    Ok(mut s) => Pin::new(&mut *s).poll_read(cx, buf),
                },
                #[cfg(feature = "http2")]
                Self::Http2(_) => Poll::Ready(Ok(())),
            }
        }
    }
    impl AsyncWrite for ResponseBodyPipe {
        fn poll_write(
            self: Pin<&mut Self>,
            cx: &mut Context<'_>,
            buf: &[u8],
        ) -> Poll<Result<usize, io::Error>> {
            match self.get_mut() {
                Self::Http1(s) => match s.try_lock() {
                    Err(_) => Poll::Pending,
                    Ok(mut s) => Pin::new(&mut *s).poll_write(cx, buf),
                },
                #[cfg(feature = "http2")]
                Self::Http2(s) => Poll::Ready(
                    s.send_data(Bytes::copy_from_slice(buf), false)
                        .map_err(|e| {
                            if e.is_io() {
                                // This is ok; we just checked it is IO.
                                e.into_io().unwrap()
                            } else {
                                io::Error::new(io::ErrorKind::Other, e.to_string())
                            }
                        })
                        .map(|()| buf.len()),
                ),
            }
        }
        fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
            Poll::Ready(Ok(()))
        }
        fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
            if let Self::Http1(s) = self.get_mut() {
                if let Ok(mut s) = s.try_lock() {
                    Pin::new(&mut *s).poll_flush(cx)
                } else {
                    Poll::Pending
                }
            } else {
                Poll::Ready(Ok(()))
            }
        }
    }
}