1use super::{
2 callback::{OnHeader, OnHeaderCallback, OnProgress, OnProgressCallback, OnStatusCode, OnStatusCodeCallback},
3 LIBRARY_USER_AGENT,
4};
5use assert_impl::assert_impl;
6use http::{
7 header::{HeaderMap, IntoHeaderName},
8 method::Method,
9 request::{Parts as HttpRequestParts, Request as HttpRequest},
10 uri::Uri,
11 Extensions, HeaderValue, Version,
12};
13use once_cell::sync::Lazy;
14use qiniu_utils::{smallstr::SmallString, wrap_smallstr};
15use serde::{
16 de::{Deserialize, Deserializer, Error, Visitor},
17 ser::{Serialize, Serializer},
18};
19use std::{
20 borrow::{Borrow, BorrowMut, Cow},
21 fmt::{self, Debug},
22 iter::FromIterator,
23 mem::take,
24 net::IpAddr,
25 ops::{Deref, DerefMut, Index, IndexMut, Range, RangeFrom, RangeFull, RangeTo},
26};
27
28#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
30pub struct UserAgent {
31 inner: SmallString<[u8; 256]>,
32}
33wrap_smallstr!(UserAgent);
34
35static FULL_USER_AGENT: Lazy<Box<str>> = Lazy::new(|| {
36 format!(
37 "QiniuRust/qiniu-http-{}/rust-{}",
38 env!("CARGO_PKG_VERSION"),
39 env!("RUSTC_VERSION"),
40 )
41 .into()
42});
43
44pub struct RequestParts<'r> {
48 inner: HttpRequestParts,
49
50 appended_user_agent: UserAgent,
52 resolved_ip_addrs: Option<Cow<'r, [IpAddr]>>,
53 on_uploading_progress: Option<OnProgressCallback<'r>>,
54 on_receive_response_status: Option<OnStatusCodeCallback<'r>>,
55 on_receive_response_header: Option<OnHeaderCallback<'r>>,
56}
57
58impl<'r> RequestParts<'r> {
59 #[inline]
61 pub fn builder() -> RequestPartsBuilder<'r> {
62 RequestPartsBuilder::default()
63 }
64
65 #[inline]
67 pub fn url(&self) -> &Uri {
68 &self.inner.uri
69 }
70
71 #[inline]
73 pub fn url_mut(&mut self) -> &mut Uri {
74 &mut self.inner.uri
75 }
76
77 #[inline]
79 pub fn version(&self) -> Version {
80 self.inner.version
81 }
82
83 #[inline]
85 pub fn version_mut(&mut self) -> &mut Version {
86 &mut self.inner.version
87 }
88
89 #[inline]
91 pub fn method(&self) -> &Method {
92 &self.inner.method
93 }
94
95 #[inline]
97 pub fn method_mut(&mut self) -> &mut Method {
98 &mut self.inner.method
99 }
100
101 #[inline]
103 pub fn headers(&self) -> &HeaderMap {
104 &self.inner.headers
105 }
106
107 #[inline]
109 pub fn headers_mut(&mut self) -> &mut HeaderMap {
110 &mut self.inner.headers
111 }
112
113 #[inline]
115 pub fn extensions(&self) -> &Extensions {
116 &self.inner.extensions
117 }
118
119 #[inline]
121 pub fn extensions_mut(&mut self) -> &mut Extensions {
122 &mut self.inner.extensions
123 }
124
125 #[inline]
127 pub fn user_agent(&self) -> UserAgent {
128 let mut user_agent = UserAgent::from(FULL_USER_AGENT.as_ref());
129 if let Some(lib_user_agent) = LIBRARY_USER_AGENT.get() {
130 user_agent.push_str(lib_user_agent);
131 }
132 user_agent.push_str(self.appended_user_agent().as_str());
133 user_agent
134 }
135
136 #[inline]
138 pub fn appended_user_agent(&self) -> &UserAgent {
139 &self.appended_user_agent
140 }
141
142 #[inline]
144 pub fn appended_user_agent_mut(&mut self) -> &mut UserAgent {
145 &mut self.appended_user_agent
146 }
147
148 #[inline]
150 pub fn resolved_ip_addrs(&self) -> Option<&[IpAddr]> {
151 self.resolved_ip_addrs.as_deref()
152 }
153
154 #[inline]
156 pub fn resolved_ip_addrs_mut(&mut self) -> &mut Option<Cow<'r, [IpAddr]>> {
157 &mut self.resolved_ip_addrs
158 }
159
160 #[inline]
162 pub fn on_uploading_progress(&'r self) -> Option<OnProgress<'r>> {
163 self.on_uploading_progress.as_deref()
164 }
165
166 #[inline]
168 pub fn on_uploading_progress_mut(&mut self) -> &mut Option<OnProgressCallback<'r>> {
169 &mut self.on_uploading_progress
170 }
171
172 #[inline]
174 pub fn on_receive_response_status(&'r self) -> Option<OnStatusCode<'r>> {
175 self.on_receive_response_status.as_deref()
176 }
177
178 #[inline]
180 pub fn on_receive_response_status_mut(&mut self) -> &mut Option<OnStatusCodeCallback<'r>> {
181 &mut self.on_receive_response_status
182 }
183
184 #[inline]
186 pub fn on_receive_response_header(&'r self) -> Option<OnHeader<'r>> {
187 self.on_receive_response_header.as_deref()
188 }
189
190 #[inline]
192 pub fn on_receive_response_header_mut(&mut self) -> &mut Option<OnHeaderCallback<'r>> {
193 &mut self.on_receive_response_header
194 }
195}
196
197impl Default for RequestParts<'_> {
198 #[inline]
199 fn default() -> Self {
200 let (parts, _) = HttpRequest::new(()).into_parts();
201 Self {
202 inner: parts,
203 appended_user_agent: Default::default(),
204 resolved_ip_addrs: Default::default(),
205 on_uploading_progress: Default::default(),
206 on_receive_response_status: Default::default(),
207 on_receive_response_header: Default::default(),
208 }
209 }
210}
211
212impl Debug for RequestParts<'_> {
213 #[inline]
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 macro_rules! field {
216 ($ctx:ident, $method_name:expr, $method:ident) => {
217 $ctx.field($method_name, &self.$method)
218 };
219 }
220 macro_rules! closure_field {
221 ($ctx:ident, $method_name:expr, $method:ident) => {
222 $ctx.field(
223 $method_name,
224 &self
225 .$method
226 .as_ref()
227 .map_or_else(|| Cow::Borrowed("Uninstalled"), |_| Cow::Borrowed("Installed")),
228 )
229 };
230 }
231 let s = &mut f.debug_struct("Request");
232 field!(s, "inner", inner);
233 field!(s, "appended_user_agent", appended_user_agent);
234 field!(s, "resolved_ip_addrs", resolved_ip_addrs);
235 closure_field!(s, "on_uploading_progress", on_uploading_progress);
236 closure_field!(s, "on_receive_response_status", on_receive_response_status);
237 closure_field!(s, "on_receive_response_header", on_receive_response_header);
238 s.finish()
239 }
240}
241
242#[derive(Debug, Default)]
246pub struct RequestPartsBuilder<'r>(RequestParts<'r>);
247
248impl<'r> RequestPartsBuilder<'r> {
249 #[inline]
251 pub fn new() -> Self {
252 Default::default()
253 }
254
255 #[inline]
257 pub fn url(&mut self, url: Uri) -> &mut Self {
258 self.0.inner.uri = url;
259 self
260 }
261
262 #[inline]
264 pub fn version(&mut self, version: Version) -> &mut Self {
265 self.0.inner.version = version;
266 self
267 }
268
269 #[inline]
271 pub fn method(&mut self, method: Method) -> &mut Self {
272 self.0.inner.method = method;
273 self
274 }
275
276 #[inline]
278 pub fn headers(&mut self, headers: HeaderMap) -> &mut Self {
279 self.0.inner.headers = headers;
280 self
281 }
282
283 #[inline]
285 pub fn header(&mut self, header_name: impl IntoHeaderName, header_value: impl Into<HeaderValue>) -> &mut Self {
286 self.0.inner.headers.insert(header_name, header_value.into());
287 self
288 }
289
290 #[inline]
292 pub fn extensions(&mut self, extensions: Extensions) -> &mut Self {
293 self.0.inner.extensions = extensions;
294 self
295 }
296
297 #[inline]
299 pub fn add_extension<T: Sync + Send + 'static>(&mut self, val: T) -> &mut Self {
300 self.0.inner.extensions.insert(val);
301 self
302 }
303
304 #[inline]
306 pub fn appended_user_agent(&mut self, user_agent: impl Into<UserAgent>) -> &mut Self {
307 self.0.appended_user_agent = user_agent.into();
308 self
309 }
310
311 #[inline]
313 pub fn resolved_ip_addrs(&mut self, resolved_ip_addrs: impl Into<Cow<'r, [IpAddr]>>) -> &mut Self {
314 self.0.resolved_ip_addrs = Some(resolved_ip_addrs.into());
315 self
316 }
317
318 #[inline]
320 pub fn on_uploading_progress(&mut self, f: impl Into<OnProgressCallback<'r>>) -> &mut Self {
321 self.0.on_uploading_progress = Some(f.into());
322 self
323 }
324
325 #[inline]
327 pub fn on_receive_response_status(&mut self, f: impl Into<OnStatusCodeCallback<'r>>) -> &mut Self {
328 self.0.on_receive_response_status = Some(f.into());
329 self
330 }
331
332 #[inline]
334 pub fn on_receive_response_header(&mut self, f: impl Into<OnHeaderCallback<'r>>) -> &mut Self {
335 self.0.on_receive_response_header = Some(f.into());
336 self
337 }
338
339 #[inline]
341 pub fn build(&mut self) -> RequestParts<'r> {
342 take(&mut self.0)
343 }
344
345 #[inline]
347 pub fn build_with_body<B: 'r>(&mut self, body: B) -> Request<'r, B> {
348 let parts = self.build();
349 Request { parts, body }
350 }
351}
352
353#[derive(Default, Debug)]
357pub struct Request<'r, B: 'r> {
358 parts: RequestParts<'r>,
359 body: B,
360}
361
362impl<'r, B: Default + 'r> Request<'r, B> {
363 #[inline]
365 pub fn builder() -> RequestBuilder<'r, B> {
366 RequestBuilder::default()
367 }
368}
369
370impl<'r, B: 'r> Request<'r, B> {
371 #[inline]
373 pub fn body(&self) -> &B {
374 &self.body
375 }
376
377 #[inline]
379 pub fn body_mut(&mut self) -> &mut B {
380 &mut self.body
381 }
382
383 #[inline]
385 pub fn into_body(self) -> B {
386 self.body
387 }
388
389 #[inline]
391 pub fn parts(&self) -> &RequestParts<'r> {
392 &self.parts
393 }
394
395 #[inline]
397 pub fn parts_mut(&mut self) -> &mut RequestParts<'r> {
398 &mut self.parts
399 }
400
401 #[inline]
403 pub fn into_parts_and_body(self) -> (RequestParts<'r>, B) {
404 let Self { parts, body } = self;
405 (parts, body)
406 }
407
408 #[inline]
410 pub fn from_parts_and_body(parts: RequestParts<'r>, body: B) -> Self {
411 Self { parts, body }
412 }
413}
414
415impl<'r, B: Send + Sync + 'r> Request<'r, B> {
416 #[allow(dead_code)]
417 fn ignore() {
418 assert_impl!(Send: Self);
419 assert_impl!(Sync: Self);
420 }
421}
422
423impl<'r, B: 'r> Deref for Request<'r, B> {
424 type Target = RequestParts<'r>;
425
426 #[inline]
427 fn deref(&self) -> &Self::Target {
428 &self.parts
429 }
430}
431
432impl<'r, B: 'r> DerefMut for Request<'r, B> {
433 #[inline]
434 fn deref_mut(&mut self) -> &mut Self::Target {
435 &mut self.parts
436 }
437}
438
439#[derive(Default, Debug)]
441pub struct RequestBuilder<'r, B> {
442 inner: Request<'r, B>,
443}
444
445impl<'r, B: Default + 'r> RequestBuilder<'r, B> {
446 #[inline]
448 pub fn new() -> Self {
449 Self {
450 inner: Default::default(),
451 }
452 }
453}
454
455impl<'r, B: 'r> RequestBuilder<'r, B> {
456 #[inline]
458 pub fn url(&mut self, url: Uri) -> &mut Self {
459 *self.inner.url_mut() = url;
460 self
461 }
462
463 #[inline]
465 pub fn method(&mut self, method: Method) -> &mut Self {
466 *self.inner.method_mut() = method;
467 self
468 }
469
470 #[inline]
472 pub fn version(&mut self, version: Version) -> &mut Self {
473 *self.inner.version_mut() = version;
474 self
475 }
476
477 #[inline]
479 pub fn headers(&mut self, headers: HeaderMap) -> &mut Self {
480 *self.inner.headers_mut() = headers;
481 self
482 }
483
484 #[inline]
486 pub fn header(&mut self, header_name: impl IntoHeaderName, header_value: impl Into<HeaderValue>) -> &mut Self {
487 self.inner.headers_mut().insert(header_name, header_value.into());
488 self
489 }
490
491 #[inline]
493 pub fn body(&mut self, body: B) -> &mut Self {
494 *self.inner.body_mut() = body;
495 self
496 }
497
498 #[inline]
500 pub fn extensions(&mut self, extensions: Extensions) -> &mut Self {
501 *self.inner.extensions_mut() = extensions;
502 self
503 }
504
505 #[inline]
507 pub fn add_extension<T: Sync + Send + 'static>(&mut self, val: T) -> &mut Self {
508 self.inner.extensions_mut().insert(val);
509 self
510 }
511
512 #[inline]
514 pub fn appended_user_agent(&mut self, user_agent: impl Into<UserAgent>) -> &mut Self {
515 *self.inner.appended_user_agent_mut() = user_agent.into();
516 self
517 }
518
519 #[inline]
521 pub fn resolved_ip_addrs(&mut self, resolved_ip_addrs: impl Into<Cow<'r, [IpAddr]>>) -> &mut Self {
522 *self.inner.resolved_ip_addrs_mut() = Some(resolved_ip_addrs.into());
523 self
524 }
525
526 #[inline]
528 pub fn on_uploading_progress(&mut self, f: impl Into<OnProgressCallback<'r>>) -> &mut Self {
529 *self.inner.on_uploading_progress_mut() = Some(f.into());
530 self
531 }
532
533 #[inline]
535 pub fn on_receive_response_status(&mut self, f: impl Into<OnStatusCodeCallback<'r>>) -> &mut Self {
536 *self.inner.on_receive_response_status_mut() = Some(f.into());
537 self
538 }
539
540 #[inline]
542 pub fn on_receive_response_header(&mut self, f: impl Into<OnHeaderCallback<'r>>) -> &mut Self {
543 *self.inner.on_receive_response_header_mut() = Some(f.into());
544 self
545 }
546}
547
548impl<'r, B: Default + 'r> RequestBuilder<'r, B> {
549 #[inline]
551 pub fn build(&mut self) -> Request<'r, B> {
552 take(&mut self.inner)
553 }
554
555 #[inline]
557 pub fn reset(&mut self) {
558 self.inner = Default::default();
559 }
560}
561
562mod body {
563 use super::super::Reset;
564 use assert_impl::assert_impl;
565 use std::{
566 default::Default,
567 fmt::Debug,
568 io::{Cursor, Read, Result as IoResult},
569 };
570
571 trait ReadDebug: Read + Reset + Debug + Send + Sync {}
572 impl<T: Read + Reset + Debug + Send + Sync> ReadDebug for T {}
573
574 #[derive(Debug)]
575 struct OwnedRequestBody(OwnedRequestBodyInner);
576
577 #[derive(Debug)]
578 enum OwnedRequestBodyInner {
579 Reader { reader: Box<dyn ReadDebug>, size: u64 },
580 Bytes(Cursor<Vec<u8>>),
581 }
582
583 impl OwnedRequestBody {
584 fn from_reader(reader: impl Read + Reset + Debug + Send + Sync + 'static, size: u64) -> Self {
585 Self(OwnedRequestBodyInner::Reader {
586 reader: Box::new(reader),
587 size,
588 })
589 }
590
591 fn from_bytes(bytes: Vec<u8>) -> Self {
592 Self(OwnedRequestBodyInner::Bytes(Cursor::new(bytes)))
593 }
594
595 fn size(&self) -> u64 {
596 match &self.0 {
597 OwnedRequestBodyInner::Reader { size, .. } => *size,
598 OwnedRequestBodyInner::Bytes(bytes) => bytes.get_ref().len() as u64,
599 }
600 }
601 }
602
603 impl Default for OwnedRequestBody {
604 #[inline]
605 fn default() -> Self {
606 Self::from_bytes(Default::default())
607 }
608 }
609
610 impl Read for OwnedRequestBody {
611 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
612 match &mut self.0 {
613 OwnedRequestBodyInner::Reader { reader, .. } => reader.read(buf),
614 OwnedRequestBodyInner::Bytes(bytes) => bytes.read(buf),
615 }
616 }
617 }
618
619 impl Reset for OwnedRequestBody {
620 #[inline]
621 fn reset(&mut self) -> IoResult<()> {
622 match &mut self.0 {
623 OwnedRequestBodyInner::Reader { reader, .. } => reader.reset(),
624 OwnedRequestBodyInner::Bytes(bytes) => bytes.reset(),
625 }
626 }
627 }
628
629 #[derive(Debug)]
631 pub struct RequestBody<'a>(RequestBodyInner<'a>);
632
633 #[derive(Debug)]
634 enum RequestBodyInner<'a> {
635 ReaderRef { reader: &'a mut dyn ReadDebug, size: u64 },
636 BytesRef(Cursor<&'a [u8]>),
637 Owned(OwnedRequestBody),
638 }
639
640 impl<'a> RequestBody<'a> {
641 #[inline]
643 pub fn from_referenced_reader<T: Read + Reset + Debug + Send + Sync + 'a>(
644 reader: &'a mut T,
645 size: u64,
646 ) -> Self {
647 Self(RequestBodyInner::ReaderRef { reader, size })
648 }
649
650 #[inline]
652 pub fn from_referenced_bytes(bytes: &'a [u8]) -> Self {
653 Self(RequestBodyInner::BytesRef(Cursor::new(bytes)))
654 }
655
656 #[inline]
658 pub fn from_reader(reader: impl Read + Reset + Debug + Send + Sync + 'static, size: u64) -> Self {
659 Self(RequestBodyInner::Owned(OwnedRequestBody::from_reader(reader, size)))
660 }
661
662 #[inline]
664 pub fn from_bytes(bytes: Vec<u8>) -> Self {
665 Self(RequestBodyInner::Owned(OwnedRequestBody::from_bytes(bytes)))
666 }
667
668 #[inline]
672 pub fn size(&self) -> u64 {
673 match &self.0 {
674 RequestBodyInner::ReaderRef { size, .. } => *size,
675 RequestBodyInner::BytesRef(bytes) => bytes.get_ref().len() as u64,
676 RequestBodyInner::Owned(owned) => owned.size(),
677 }
678 }
679
680 #[allow(dead_code)]
681 fn ignore() {
682 assert_impl!(Send: Self);
683 assert_impl!(Sync: Self);
684 }
685 }
686
687 impl Default for RequestBody<'_> {
688 #[inline]
689 fn default() -> Self {
690 Self::from_bytes(Default::default())
691 }
692 }
693
694 impl Read for RequestBody<'_> {
695 #[inline]
696 fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
697 match &mut self.0 {
698 RequestBodyInner::ReaderRef { reader, .. } => reader.read(buf),
699 RequestBodyInner::BytesRef(bytes) => bytes.read(buf),
700 RequestBodyInner::Owned(owned) => owned.read(buf),
701 }
702 }
703 }
704
705 impl Reset for RequestBody<'_> {
706 #[inline]
707 fn reset(&mut self) -> IoResult<()> {
708 match &mut self.0 {
709 RequestBodyInner::ReaderRef { reader, .. } => reader.reset(),
710 RequestBodyInner::BytesRef(bytes) => bytes.reset(),
711 RequestBodyInner::Owned(owned) => owned.reset(),
712 }
713 }
714 }
715
716 impl<'a> From<&'a mut RequestBody<'_>> for RequestBody<'a> {
717 #[inline]
718 fn from(body: &'a mut RequestBody<'_>) -> Self {
719 Self::from_referenced_reader(body, body.size())
720 }
721 }
722
723 impl<'a> From<&'a [u8]> for RequestBody<'a> {
724 #[inline]
725 fn from(body: &'a [u8]) -> Self {
726 Self::from_referenced_bytes(body)
727 }
728 }
729
730 impl<'a> From<&'a str> for RequestBody<'a> {
731 #[inline]
732 fn from(body: &'a str) -> Self {
733 Self::from_referenced_bytes(body.as_bytes())
734 }
735 }
736
737 impl From<Vec<u8>> for RequestBody<'_> {
738 #[inline]
739 fn from(body: Vec<u8>) -> Self {
740 Self::from_bytes(body)
741 }
742 }
743
744 impl From<String> for RequestBody<'_> {
745 #[inline]
746 fn from(body: String) -> Self {
747 Self::from_bytes(body.into_bytes())
748 }
749 }
750
751 #[cfg(feature = "async")]
752 mod async_body {
753 use super::super::super::{AsyncReset, BoxFuture};
754 use assert_impl::assert_impl;
755 use futures_lite::{
756 io::{AsyncRead, Cursor, Result as IoResult},
757 pin,
758 };
759 use std::{
760 fmt::Debug,
761 pin::Pin,
762 task::{Context, Poll},
763 };
764
765 trait AsyncReadDebug: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync {}
766 impl<T: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync> AsyncReadDebug for T {}
767
768 #[derive(Debug)]
769 #[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
770 struct OwnedAsyncRequestBody(OwnedAsyncRequestBodyInner);
771
772 #[derive(Debug)]
773 enum OwnedAsyncRequestBodyInner {
774 Reader { reader: Box<dyn AsyncReadDebug>, size: u64 },
775 Bytes(Cursor<Vec<u8>>),
776 }
777
778 impl OwnedAsyncRequestBody {
779 fn from_reader(
780 reader: impl AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'static,
781 size: u64,
782 ) -> Self {
783 Self(OwnedAsyncRequestBodyInner::Reader {
784 reader: Box::new(reader),
785 size,
786 })
787 }
788
789 fn from_bytes(bytes: Vec<u8>) -> Self {
790 Self(OwnedAsyncRequestBodyInner::Bytes(Cursor::new(bytes)))
791 }
792
793 #[inline]
794 fn size(&self) -> u64 {
795 match &self.0 {
796 OwnedAsyncRequestBodyInner::Reader { size, .. } => *size,
797 OwnedAsyncRequestBodyInner::Bytes(bytes) => bytes.get_ref().len() as u64,
798 }
799 }
800 }
801
802 impl Default for OwnedAsyncRequestBody {
803 #[inline]
804 fn default() -> Self {
805 Self::from_bytes(Default::default())
806 }
807 }
808
809 impl AsyncRead for OwnedAsyncRequestBody {
810 fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<IoResult<usize>> {
811 match &mut self.as_mut().0 {
812 OwnedAsyncRequestBodyInner::Reader { reader, .. } => {
813 pin!(reader);
814 reader.poll_read(cx, buf)
815 }
816 OwnedAsyncRequestBodyInner::Bytes(bytes) => {
817 pin!(bytes);
818 bytes.poll_read(cx, buf)
819 }
820 }
821 }
822 }
823
824 impl AsyncReset for OwnedAsyncRequestBody {
825 #[inline]
826 fn reset(&mut self) -> BoxFuture<IoResult<()>> {
827 Box::pin(async move {
828 match &mut self.0 {
829 OwnedAsyncRequestBodyInner::Reader { reader, .. } => reader.reset().await,
830 OwnedAsyncRequestBodyInner::Bytes(bytes) => bytes.reset().await,
831 }
832 })
833 }
834 }
835
836 #[derive(Debug)]
838 #[cfg_attr(feature = "docs", doc(cfg(feature = "async")))]
839 pub struct AsyncRequestBody<'a>(AsyncRequestBodyInner<'a>);
840
841 #[derive(Debug)]
842 enum AsyncRequestBodyInner<'a> {
843 ReaderRef {
844 reader: &'a mut dyn AsyncReadDebug,
845 size: u64,
846 },
847 BytesRef(Cursor<&'a [u8]>),
848 Owned(OwnedAsyncRequestBody),
849 }
850
851 impl<'a> AsyncRequestBody<'a> {
852 #[inline]
854 pub fn from_referenced_reader<T: AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'a>(
855 reader: &'a mut T,
856 size: u64,
857 ) -> Self {
858 Self(AsyncRequestBodyInner::ReaderRef { reader, size })
859 }
860
861 #[inline]
863 pub fn from_referenced_bytes(bytes: &'a [u8]) -> Self {
864 Self(AsyncRequestBodyInner::BytesRef(Cursor::new(bytes)))
865 }
866
867 #[inline]
869 pub fn from_reader(
870 reader: impl AsyncRead + AsyncReset + Unpin + Debug + Send + Sync + 'static,
871 size: u64,
872 ) -> Self {
873 Self(AsyncRequestBodyInner::Owned(OwnedAsyncRequestBody::from_reader(
874 reader, size,
875 )))
876 }
877
878 #[inline]
880 pub fn from_bytes(bytes: Vec<u8>) -> Self {
881 Self(AsyncRequestBodyInner::Owned(OwnedAsyncRequestBody::from_bytes(bytes)))
882 }
883
884 #[inline]
888 pub fn size(&self) -> u64 {
889 match &self.0 {
890 AsyncRequestBodyInner::ReaderRef { size, .. } => *size,
891 AsyncRequestBodyInner::BytesRef(bytes) => bytes.get_ref().len() as u64,
892 AsyncRequestBodyInner::Owned(owned) => owned.size(),
893 }
894 }
895
896 #[allow(dead_code)]
897 fn ignore() {
898 assert_impl!(Send: Self);
899 assert_impl!(Sync: Self);
900 }
901 }
902
903 impl Default for AsyncRequestBody<'_> {
904 #[inline]
905 fn default() -> Self {
906 Self::from_bytes(Default::default())
907 }
908 }
909
910 impl AsyncRead for AsyncRequestBody<'_> {
911 fn poll_read(mut self: Pin<&mut Self>, cx: &mut Context, buf: &mut [u8]) -> Poll<IoResult<usize>> {
912 match &mut self.as_mut().0 {
913 AsyncRequestBodyInner::ReaderRef { reader, .. } => {
914 pin!(reader);
915 reader.poll_read(cx, buf)
916 }
917 AsyncRequestBodyInner::BytesRef(bytes) => {
918 pin!(bytes);
919 bytes.poll_read(cx, buf)
920 }
921 AsyncRequestBodyInner::Owned(owned) => {
922 pin!(owned);
923 owned.poll_read(cx, buf)
924 }
925 }
926 }
927 }
928
929 impl AsyncReset for AsyncRequestBody<'_> {
930 #[inline]
931 fn reset(&mut self) -> BoxFuture<IoResult<()>> {
932 Box::pin(async move {
933 match &mut self.0 {
934 AsyncRequestBodyInner::ReaderRef { reader, .. } => reader.reset().await,
935 AsyncRequestBodyInner::BytesRef(bytes) => bytes.reset().await,
936 AsyncRequestBodyInner::Owned(owned) => owned.reset().await,
937 }
938 })
939 }
940 }
941
942 impl<'a> From<&'a mut AsyncRequestBody<'_>> for AsyncRequestBody<'a> {
943 #[inline]
944 fn from(body: &'a mut AsyncRequestBody<'_>) -> Self {
945 Self::from_referenced_reader(body, body.size())
946 }
947 }
948
949 impl<'a> From<&'a [u8]> for AsyncRequestBody<'a> {
950 #[inline]
951 fn from(body: &'a [u8]) -> Self {
952 Self::from_referenced_bytes(body)
953 }
954 }
955
956 impl<'a> From<&'a str> for AsyncRequestBody<'a> {
957 #[inline]
958 fn from(body: &'a str) -> Self {
959 Self::from_referenced_bytes(body.as_bytes())
960 }
961 }
962
963 impl From<Vec<u8>> for AsyncRequestBody<'_> {
964 #[inline]
965 fn from(body: Vec<u8>) -> Self {
966 Self::from_bytes(body)
967 }
968 }
969
970 impl From<String> for AsyncRequestBody<'_> {
971 #[inline]
972 fn from(body: String) -> Self {
973 Self::from_bytes(body.into_bytes())
974 }
975 }
976 }
977
978 #[cfg(feature = "async")]
979 pub use async_body::*;
980}
981
982pub use body::RequestBody;
983
984#[cfg(feature = "async")]
985pub use body::AsyncRequestBody;