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
use super::callback::{OnHeader, OnProgress, OnStatusCode};
use assert_impl::assert_impl;
use http::{
    header::HeaderMap,
    method::Method,
    request::{Parts as HttpRequestParts, Request as HttpRequest},
    uri::Uri,
    Extensions, Version,
};
use once_cell::sync::Lazy;
use qiniu_utils::{smallstr::SmallString, wrap_smallstr};
use serde::{
    de::{Deserialize, Deserializer, Error, Visitor},
    ser::{Serialize, Serializer},
};
use std::{
    borrow::{Borrow, BorrowMut, Cow},
    fmt::{self, Debug},
    iter::FromIterator,
    mem::take,
    net::IpAddr,
    ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeTo},
};

/// 用户代理信息
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct UserAgent {
    inner: SmallString<[u8; 256]>,
}
wrap_smallstr!(UserAgent);

static FULL_USER_AGENT: Lazy<Box<str>> = Lazy::new(|| {
    format!(
        "QiniuRust/qiniu-http-{}/rust-{}",
        env!("CARGO_PKG_VERSION"),
        env!("RUSTC_VERSION"),
    )
    .into()
});

/// HTTP 请求信息
///
/// 不包含请求体信息
pub struct RequestParts<'r> {
    inner: HttpRequestParts,

    // 请求配置属性
    appended_user_agent: UserAgent,
    resolved_ip_addrs: Option<Cow<'r, [IpAddr]>>,
    on_uploading_progress: Option<OnProgress<'r>>,
    on_receive_response_status: Option<OnStatusCode<'r>>,
    on_receive_response_header: Option<OnHeader<'r>>,
}

impl<'r> RequestParts<'r> {
    /// 获取 HTTP 请求 URL
    #[inline]
    pub fn url(&self) -> &Uri {
        &self.inner.uri
    }

    /// 获取 HTTP 请求 URL 的可变引用
    #[inline]
    pub fn url_mut(&mut self) -> &mut Uri {
        &mut self.inner.uri
    }

    /// 获取请求 HTTP 版本
    #[inline]
    pub fn version(&self) -> Version {
        self.inner.version
    }

    /// 获取请求 HTTP 版本的可变引用
    #[inline]
    pub fn version_mut(&mut self) -> &mut Version {
        &mut self.inner.version
    }

    /// 获取请求 HTTP 方法
    #[inline]
    pub fn method(&self) -> &Method {
        &self.inner.method
    }

    /// 获取请求 HTTP 方法的可变引用
    #[inline]
    pub fn method_mut(&mut self) -> &mut Method {
        &mut self.inner.method
    }

    /// 获取请求 HTTP Headers
    #[inline]
    pub fn headers(&self) -> &HeaderMap {
        &self.inner.headers
    }

    /// 获取请求 HTTP Headers 的可变引用
    #[inline]
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.inner.headers
    }

    /// 获取扩展信息
    #[inline]
    pub fn extensions(&self) -> &Extensions {
        &self.inner.extensions
    }

    /// 获取扩展信息的可变引用
    #[inline]
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.inner.extensions
    }

    /// 获取用户代理
    #[inline]
    pub fn user_agent(&self) -> UserAgent {
        let mut user_agent = UserAgent::from(FULL_USER_AGENT.as_ref());
        user_agent.push_str(self.appended_user_agent().as_str());
        user_agent
    }

    /// 获取追加的用户代理
    #[inline]
    pub fn appended_user_agent(&self) -> &UserAgent {
        &self.appended_user_agent
    }

    /// 获取追加的用户代理的可变引用
    #[inline]
    pub fn appended_user_agent_mut(&mut self) -> &mut UserAgent {
        &mut self.appended_user_agent
    }

    /// 获取预解析的服务器套接字地址
    #[inline]
    pub fn resolved_ip_addrs(&self) -> Option<&[IpAddr]> {
        self.resolved_ip_addrs.as_deref()
    }

    /// 获取预解析的服务器套接字地址的可变引用
    #[inline]
    pub fn resolved_ip_addrs_mut(&mut self) -> &mut Option<Cow<'r, [IpAddr]>> {
        &mut self.resolved_ip_addrs
    }

    /// 获取上传进度回调
    #[inline]
    pub fn on_uploading_progress(&self) -> Option<OnProgress<'r>> {
        self.on_uploading_progress
    }

    /// 获取上传进度回调的可变引用
    #[inline]
    pub fn on_uploading_progress_mut(&mut self) -> &mut Option<OnProgress<'r>> {
        &mut self.on_uploading_progress
    }

    /// 获取接受到响应状态回调
    #[inline]
    pub fn on_receive_response_status(&self) -> Option<OnStatusCode> {
        self.on_receive_response_status
    }

    /// 获取接受到响应状态回调的可变引用
    #[inline]
    pub fn on_receive_response_status_mut(&mut self) -> &mut Option<OnStatusCode<'r>> {
        &mut self.on_receive_response_status
    }

    /// 获取接受到响应 Header 回调
    #[inline]
    pub fn on_receive_response_header(&self) -> Option<OnHeader> {
        self.on_receive_response_header
    }

    /// 获取接受到响应 Header 回调的可变引用
    #[inline]
    pub fn on_receive_response_header_mut(&mut self) -> &mut Option<OnHeader<'r>> {
        &mut self.on_receive_response_header
    }
}

impl Default for RequestParts<'_> {
    #[inline]
    fn default() -> Self {
        let (parts, _) = HttpRequest::new(()).into_parts();
        Self {
            inner: parts,
            appended_user_agent: Default::default(),
            resolved_ip_addrs: Default::default(),
            on_uploading_progress: Default::default(),
            on_receive_response_status: Default::default(),
            on_receive_response_header: Default::default(),
        }
    }
}

impl Debug for RequestParts<'_> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        macro_rules! field {
            ($ctx:ident, $method_name:expr, $method:ident) => {
                $ctx.field($method_name, &self.$method)
            };
        }
        macro_rules! closure_field {
            ($ctx:ident, $method_name:expr, $method:ident) => {
                $ctx.field(
                    $method_name,
                    &self
                        .$method
                        .map_or_else(|| Cow::Borrowed("Uninstalled"), |_| Cow::Borrowed("Installed")),
                )
            };
        }
        let s = &mut f.debug_struct("Request");
        field!(s, "inner", inner);
        field!(s, "appended_user_agent", appended_user_agent);
        field!(s, "resolved_ip_addrs", resolved_ip_addrs);
        closure_field!(s, "on_uploading_progress", on_uploading_progress);
        closure_field!(s, "on_receive_response_status", on_receive_response_status);
        closure_field!(s, "on_receive_response_header", on_receive_response_header);
        s.finish()
    }
}

/// HTTP 请求
///
/// 封装 HTTP 请求相关字段
#[derive(Default, Debug)]
pub struct Request<'r, B: 'r> {
    parts: RequestParts<'r>,
    body: B,
}

impl<'r, B: Default + 'r> Request<'r, B> {
    /// 创建 HTTP 响应构建器
    #[inline]
    pub fn builder() -> RequestBuilder<'r, B> {
        RequestBuilder::default()
    }
}

impl<'r, B: 'r> Request<'r, B> {
    /// 获取请求体
    #[inline]
    pub fn body(&self) -> &B {
        &self.body
    }

    /// 获取请求体的可变引用
    #[inline]
    pub fn body_mut(&mut self) -> &mut B {
        &mut self.body
    }

    /// 转换为 HTTP 请求体
    #[inline]
    pub fn into_body(self) -> B {
        self.body
    }

    /// 获取请求信息
    #[inline]
    pub fn parts(&self) -> &RequestParts<'r> {
        &self.parts
    }

    /// 获取请求信息的可变引用
    #[inline]
    pub fn parts_mut(&mut self) -> &mut RequestParts<'r> {
        &mut self.parts
    }

    /// 转换为请求信息和请求体
    #[inline]
    pub fn into_parts_and_body(self) -> (RequestParts<'r>, B) {
        let Self { parts, body } = self;
        (parts, body)
    }

    /// 通过请求信息和请求体创建 HTTP 请求
    #[inline]
    pub fn from_parts_and_body<B2>(parts: RequestParts<'r>, body: B2) -> Request<'r, B2> {
        Request { parts, body }
    }
}

impl<'r, B: Send + Sync + 'r> Request<'r, B> {
    #[allow(dead_code)]
    fn ignore() {
        assert_impl!(Send: Self);
        assert_impl!(Sync: Self);
    }
}

impl<'r, B: 'r> Deref for Request<'r, B> {
    type Target = RequestParts<'r>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.parts
    }
}

impl<'r, B: 'r> DerefMut for Request<'r, B> {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.parts
    }
}

/// HTTP 请求构建器
#[derive(Default, Debug)]
pub struct RequestBuilder<'r, B> {
    inner: Request<'r, B>,
}

impl<'r, B: 'r> RequestBuilder<'r, B> {
    /// 设置请求 URL
    #[inline]
    pub fn url(&mut self, url: Uri) -> &mut Self {
        *self.inner.url_mut() = url;
        self
    }

    /// 设置请求 HTTP 方法
    #[inline]
    pub fn method(&mut self, method: Method) -> &mut Self {
        *self.inner.method_mut() = method;
        self
    }

    /// 设置请求 HTTP 版本
    #[inline]
    pub fn version(&mut self, version: Version) -> &mut Self {
        *self.inner.version_mut() = version;
        self
    }

    /// 设置请求 HTTP Headers
    #[inline]
    pub fn headers(&mut self, headers: HeaderMap) -> &mut Self {
        *self.inner.headers_mut() = headers;
        self
    }

    /// 设置请求 HTTP 请求体
    #[inline]
    pub fn body(&mut self, body: B) -> &mut Self {
        *self.inner.body_mut() = body;
        self
    }

    /// 设置扩展信息
    #[inline]
    pub fn extensions(&mut self, extensions: Extensions) -> &mut Self {
        *self.inner.extensions_mut() = extensions;
        self
    }

    /// 追加扩展信息
    #[inline]
    pub fn add_extension<T: Sync + Send + 'static>(&mut self, val: T) -> &mut Self {
        self.inner.extensions_mut().insert(val);
        self
    }

    /// 设置用户代理
    #[inline]
    pub fn appended_user_agent(&mut self, user_agent: impl Into<UserAgent>) -> &mut Self {
        *self.inner.appended_user_agent_mut() = user_agent.into();
        self
    }

    /// 设置预解析的服务器套接字地址
    #[inline]
    pub fn resolved_ip_addrs(&mut self, resolved_ip_addrs: impl Into<Cow<'r, [IpAddr]>>) -> &mut Self {
        *self.inner.resolved_ip_addrs_mut() = Some(resolved_ip_addrs.into());
        self
    }

    /// 设置上传进度回调
    #[inline]
    pub fn on_uploading_progress(&mut self, f: OnProgress<'r>) -> &mut Self {
        *self.inner.on_uploading_progress_mut() = Some(f);
        self
    }

    /// 设置接受到响应状态回调
    #[inline]
    pub fn on_receive_response_status(&mut self, f: OnStatusCode<'r>) -> &mut Self {
        *self.inner.on_receive_response_status_mut() = Some(f);
        self
    }

    /// 设置接受到响应 Header 回调
    #[inline]
    pub fn on_receive_response_header(&mut self, f: OnHeader<'r>) -> &mut Self {
        *self.inner.on_receive_response_header_mut() = Some(f);
        self
    }
}

impl<'r, B: Default + 'r> RequestBuilder<'r, B> {
    /// 构建 HTTP 请求,同时构建器被重置
    #[inline]
    pub fn build(&mut self) -> Request<'r, B> {
        take(&mut self.inner)
    }

    /// 重置 HTTP 请求构建器
    #[inline]
    pub fn reset(&mut self) {
        self.inner = Default::default();
    }
}

mod body {
    use super::super::Reset;
    use std::{
        default::Default,
        fmt::Debug,
        io::{Cursor, Read, Result as IoResult},
    };

    trait ReadDebug: Read + Reset + Debug + Send + Sync {}
    impl<T: Read + Reset + Debug + Send + Sync> ReadDebug for T {}

    #[derive(Debug)]
    struct OwnedRequestBody(OwnedRequestBodyInner);

    #[derive(Debug)]
    enum OwnedRequestBodyInner {
        Reader { reader: Box<dyn ReadDebug>, size: u64 },
        Bytes(Cursor<Vec<u8>>),
    }

    impl OwnedRequestBody {
        fn from_reader(reader: impl Read + Reset + Debug + Send + Sync + 'static, size: u64) -> Self {
            Self(OwnedRequestBodyInner::Reader {
                reader: Box::new(reader),
                size,
            })
        }

        fn from_bytes(bytes: Vec<u8>) -> Self {
            Self(OwnedRequestBodyInner::Bytes(Cursor::new(bytes)))
        }

        fn size(&self) -> u64 {
            match &self.0 {
                OwnedRequestBodyInner::Reader { size, .. } => *size,
                OwnedRequestBodyInner::Bytes(bytes) => bytes.get_ref().len() as u64,
            }
        }
    }

    impl Default for OwnedRequestBody {
        #[inline]
        fn default() -> Self {
            Self::from_bytes(Default::default())
        }
    }

    impl Read for OwnedRequestBody {
        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
            match &mut self.0 {
                OwnedRequestBodyInner::Reader { reader, .. } => reader.read(buf),
                OwnedRequestBodyInner::Bytes(bytes) => bytes.read(buf),
            }
        }
    }

    impl Reset for OwnedRequestBody {
        #[inline]
        fn reset(&mut self) -> IoResult<()> {
            match &mut self.0 {
                OwnedRequestBodyInner::Reader { reader, .. } => reader.reset(),
                OwnedRequestBodyInner::Bytes(bytes) => bytes.reset(),
            }
        }
    }

    /// HTTP 请求体
    #[derive(Debug)]
    pub struct RequestBody<'a>(RequestBodyInner<'a>);

    #[derive(Debug)]
    enum RequestBodyInner<'a> {
        ReaderRef { reader: &'a mut dyn ReadDebug, size: u64 },
        BytesRef(Cursor<&'a [u8]>),
        Owned(OwnedRequestBody),
    }

    impl<'a> RequestBody<'a> {
        /// 通过输入流的可变引用创建 HTTP 请求体
        #[inline]
        pub fn from_referenced_reader<T: Read + Reset + Debug + Send + Sync + 'a>(
            reader: &'a mut T,
            size: u64,
        ) -> Self {
            Self(RequestBodyInner::ReaderRef { reader, size })
        }

        /// 通过二进制数据的引用创建 HTTP 请求体
        #[inline]
        pub fn from_referenced_bytes(bytes: &'a [u8]) -> Self {
            Self(RequestBodyInner::BytesRef(Cursor::new(bytes)))
        }

        /// 通过输入流创建 HTTP 请求体
        #[inline]
        pub fn from_reader(reader: impl Read + Reset + Debug + Send + Sync + 'static, size: u64) -> Self {
            Self(RequestBodyInner::Owned(OwnedRequestBody::from_reader(reader, size)))
        }

        /// 通过二进制数据创建 HTTP 请求体
        #[inline]
        pub fn from_bytes(bytes: Vec<u8>) -> Self {
            Self(RequestBodyInner::Owned(OwnedRequestBody::from_bytes(bytes)))
        }

        /// 获取请求体大小
        ///
        /// 单位为字节
        #[inline]
        pub fn size(&self) -> u64 {
            match &self.0 {
                RequestBodyInner::ReaderRef { size, .. } => *size,
                RequestBodyInner::BytesRef(bytes) => bytes.get_ref().len() as u64,
                RequestBodyInner::Owned(owned) => owned.size(),
            }
        }
    }

    impl Default for RequestBody<'_> {
        #[inline]
        fn default() -> Self {
            Self::from_bytes(Default::default())
        }
    }

    impl Read for RequestBody<'_> {
        #[inline]
        fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
            match &mut self.0 {
                RequestBodyInner::ReaderRef { reader, .. } => reader.read(buf),
                RequestBodyInner::BytesRef(bytes) => bytes.read(buf),
                RequestBodyInner::Owned(owned) => owned.read(buf),
            }
        }
    }

    impl Reset for RequestBody<'_> {
        #[inline]
        fn reset(&mut self) -> IoResult<()> {
            match &mut self.0 {
                RequestBodyInner::ReaderRef { reader, .. } => reader.reset(),
                RequestBodyInner::BytesRef(bytes) => bytes.reset(),
                RequestBodyInner::Owned(owned) => owned.reset(),
            }
        }
    }

    impl<'a> From<&'a mut RequestBody<'_>> for RequestBody<'a> {
        #[inline]
        fn from(body: &'a mut RequestBody<'_>) -> Self {
            Self::from_referenced_reader(body, body.size())
        }
    }

    #[cfg(feature = "async")]
    mod async_body {
        use super::super::super::{AsyncReset, BoxFuture};
        use futures_lite::{
            io::{AsyncRead, Cursor, Result as IoResult},
            pin,
        };
        use std::{
            fmt::Debug,
            pin::Pin,
            task::{Context, Poll},
        };

        trait AsyncReadDebug: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync {}
        impl<T: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync> AsyncReadDebug for T {}

        #[derive(Debug)]
        #[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
        struct OwnedAsyncRequestBody(OwnedAsyncRequestBodyInner);

        #[derive(Debug)]
        enum OwnedAsyncRequestBodyInner {
            Reader { reader: Box<dyn AsyncReadDebug>, size: u64 },
            Bytes(Cursor<Vec<u8>>),
        }

        impl OwnedAsyncRequestBody {
            fn from_reader(
                reader: impl AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'static,
                size: u64,
            ) -> Self {
                Self(OwnedAsyncRequestBodyInner::Reader {
                    reader: Box::new(reader),
                    size,
                })
            }

            fn from_bytes(bytes: Vec<u8>) -> Self {
                Self(OwnedAsyncRequestBodyInner::Bytes(Cursor::new(bytes)))
            }

            #[inline]
            pub fn size(&self) -> u64 {
                match &self.0 {
                    OwnedAsyncRequestBodyInner::Reader { size, .. } => *size,
                    OwnedAsyncRequestBodyInner::Bytes(bytes) => bytes.get_ref().len() as u64,
                }
            }
        }

        impl Default for OwnedAsyncRequestBody {
            #[inline]
            fn default() -> Self {
                Self::from_bytes(Default::default())
            }
        }

        impl AsyncRead for OwnedAsyncRequestBody {
            fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<IoResult<usize>> {
                match &mut self.as_mut().0 {
                    OwnedAsyncRequestBodyInner::Reader { reader, .. } => {
                        pin!(reader);
                        reader.poll_read(cx, buf)
                    }
                    OwnedAsyncRequestBodyInner::Bytes(bytes) => {
                        pin!(bytes);
                        bytes.poll_read(cx, buf)
                    }
                }
            }
        }

        impl AsyncReset for OwnedAsyncRequestBody {
            #[inline]
            fn reset(&mut self) -> BoxFuture<IoResult<()>> {
                Box::pin(async move {
                    match &mut self.0 {
                        OwnedAsyncRequestBodyInner::Reader { reader, .. } => reader.reset().await,
                        OwnedAsyncRequestBodyInner::Bytes(bytes) => bytes.reset().await,
                    }
                })
            }
        }

        /// 异步 HTTP 请求体
        #[derive(Debug)]
        #[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
        pub struct AsyncRequestBody<'a>(AsyncRequestBodyInner<'a>);

        #[derive(Debug)]
        enum AsyncRequestBodyInner<'a> {
            ReaderRef {
                reader: &'a mut dyn AsyncReadDebug,
                size: u64,
            },
            BytesRef(Cursor<&'a [u8]>),
            Owned(OwnedAsyncRequestBody),
        }

        impl<'a> AsyncRequestBody<'a> {
            /// 通过异步输入流的可变引用创建异步 HTTP 请求体
            #[inline]
            pub fn from_referenced_reader<T: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'a>(
                reader: &'a mut T,
                size: u64,
            ) -> Self {
                Self(AsyncRequestBodyInner::ReaderRef { reader, size })
            }

            /// 通过二进制数据的引用创建异步 HTTP 请求体
            #[inline]
            pub fn from_referenced_bytes(bytes: &'a [u8]) -> Self {
                Self(AsyncRequestBodyInner::BytesRef(Cursor::new(bytes)))
            }

            /// 通过异步输入流创建异步 HTTP 请求体
            #[inline]
            pub fn from_reader(
                reader: impl AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'static,
                size: u64,
            ) -> Self {
                Self(AsyncRequestBodyInner::Owned(OwnedAsyncRequestBody::from_reader(
                    reader, size,
                )))
            }

            /// 通过二进制数据创建异步 HTTP 请求体
            #[inline]
            pub fn from_bytes(bytes: Vec<u8>) -> Self {
                Self(AsyncRequestBodyInner::Owned(OwnedAsyncRequestBody::from_bytes(bytes)))
            }

            /// 获取请求体大小
            ///
            /// 单位为字节
            #[inline]
            pub fn size(&self) -> u64 {
                match &self.0 {
                    AsyncRequestBodyInner::ReaderRef { size, .. } => *size,
                    AsyncRequestBodyInner::BytesRef(bytes) => bytes.get_ref().len() as u64,
                    AsyncRequestBodyInner::Owned(owned) => owned.size(),
                }
            }
        }

        impl Default for AsyncRequestBody<'_> {
            #[inline]
            fn default() -> Self {
                Self::from_bytes(Default::default())
            }
        }

        impl AsyncRead for AsyncRequestBody<'_> {
            fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<IoResult<usize>> {
                match &mut self.as_mut().0 {
                    AsyncRequestBodyInner::ReaderRef { reader, .. } => {
                        pin!(reader);
                        reader.poll_read(cx, buf)
                    }
                    AsyncRequestBodyInner::BytesRef(bytes) => {
                        pin!(bytes);
                        bytes.poll_read(cx, buf)
                    }
                    AsyncRequestBodyInner::Owned(owned) => {
                        pin!(owned);
                        owned.poll_read(cx, buf)
                    }
                }
            }
        }

        impl AsyncReset for AsyncRequestBody<'_> {
            #[inline]
            fn reset(&mut self) -> BoxFuture<IoResult<()>> {
                Box::pin(async move {
                    match &mut self.0 {
                        AsyncRequestBodyInner::ReaderRef { reader, .. } => reader.reset().await,
                        AsyncRequestBodyInner::BytesRef(bytes) => bytes.reset().await,
                        AsyncRequestBodyInner::Owned(owned) => owned.reset().await,
                    }
                })
            }
        }

        impl<'a> From<&'a mut AsyncRequestBody<'_>> for AsyncRequestBody<'a> {
            #[inline]
            fn from(body: &'a mut AsyncRequestBody<'_>) -> Self {
                Self::from_referenced_reader(body, body.size())
            }
        }
    }

    #[cfg(feature = "async")]
    pub use async_body::*;
}

pub use body::RequestBody;

#[cfg(feature = "async")]
pub use body::AsyncRequestBody;