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
// Copyright 2022 - 2023 Wenmeng See the COPYRIGHT
// file at the top-level directory of this distribution.
// 
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// 
// Author: tickbh
// -----
// Created Date: 2023/08/17 04:39:49

use std::{
    any::{Any},
    sync::{Arc, RwLock}, fmt::Display,
};

use crate::{
    Binary, BinaryMut, Buf, BufMut, Extensions, HeaderMap, HeaderName, HeaderValue, Serialize, Version, WebError, WebResult, Helper,
};

use super::{
    http2::{HeaderIndex},
    StatusCode,
};

#[derive(Debug)]
pub struct Response<T>
where
    T: Serialize,
{
    parts: Parts,
    body: T,
    partial: bool,
}

#[derive(Debug)]
pub struct Parts {
    pub status: StatusCode,
    pub header: HeaderMap,
    pub version: Version,
    pub extensions: Extensions,
}

#[derive(Debug)]
pub struct Builder {
    inner: WebResult<Parts>,
}

impl Builder {
    /// Creates a new default instance of `Builder` to construct either a
    /// `Head` or a `Response`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    ///
    /// let response = Response::builder()
    ///     .status(200)
    ///     .body(())
    ///     .unwrap();
    /// ```
    #[inline]
    pub fn new() -> Builder {
        Builder::default()
    }

    /// Set the HTTP status for this response.
    ///
    /// By default this is `200`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    ///
    /// let response = Response::builder()
    ///     .status(200)
    ///     .body(())
    ///     .unwrap();
    /// ```
    pub fn status<T>(self, status: T) -> Builder
    where
        StatusCode: TryFrom<T>,
        <StatusCode as TryFrom<T>>::Error: Into<WebError>,
    {
        self.and_then(move |mut head| {
            head.status = TryFrom::try_from(status).map_err(Into::into)?;
            Ok(head)
        })
    }

    pub fn method(self, method: String) -> Builder
    {
        self.and_then(move |mut head| {
            head.header.insert(":method", method.to_string());
            Ok(head)
        })
    }

    /// Set the HTTP version for this response.
    ///
    /// By default this is HTTP/1.1
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    ///
    /// let response = Response::builder()
    ///     .version(Version::Http2)
    ///     .body(())
    ///     .unwrap();
    /// ```
    pub fn version(self, version: Version) -> Builder {
        self.and_then(move |mut head| {
            head.version = version;
            Ok(head)
        })
    }

    /// Appends a header to this response builder.
    ///
    /// This function will append the provided key/value as a header to the
    /// internal `HeaderMap` being constructed. Essentially this is equivalent
    /// to calling `HeaderMap::append`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response = Response::builder()
    ///     .header("Content-Type", "text/html")
    ///     .header("X-Custom-Foo", "bar")
    ///     .header("content-length", 0usize)
    ///     .body(())
    ///     .unwrap();
    /// ```
    pub fn header<K, V>(self, key: K, value: V) -> Builder
    where
        HeaderName: TryFrom<K>,
        <HeaderName as TryFrom<K>>::Error: Into<WebError>,
        HeaderValue: TryFrom<V>,
        <HeaderValue as TryFrom<V>>::Error: Into<WebError>,
    {
        self.and_then(move |mut head| {
            head.header.insert(key, value);
            Ok(head)
        })
    }

    /// 从另一个HeaderMap中进行header构建
    pub fn headers(self, header: HeaderMap) -> Builder {
        self.and_then(move |mut head| {
            for iter in header {
                head.header.insert(iter.0, iter.1);
            }
            Ok(head)
        })
    }

    /// Get header on this response builder.
    ///
    /// When builder has error returns None.
    ///
    /// # Example
    ///
    /// ```
    /// use webparse::Response;
    /// use webparse::HeaderValue;
    /// let res = Response::builder()
    ///     .header("Accept", "text/html")
    ///     .header("X-Custom-Foo", "bar");
    /// let headers = res.headers_ref().unwrap();
    /// assert_eq!( &headers["Accept"], &"text/html" );
    /// assert_eq!( &headers["X-Custom-Foo"], &"bar" );
    /// ```
    pub fn headers_ref(&self) -> Option<&HeaderMap> {
        self.inner.as_ref().ok().map(|h| &h.header)
    }

    /// Get header on this response builder.
    /// when builder has error returns None
    ///
    /// # Example
    ///
    /// ```
    /// use webparse::*;
    /// let mut res = Response::builder();
    /// {
    ///   let headers = res.headers_mut().unwrap();
    ///   headers.insert("Accept", HeaderValue::from_static("text/html"));
    ///   headers.insert("X-Custom-Foo", HeaderValue::from_static("bar"));
    /// }
    /// let headers = res.headers_ref().unwrap();
    /// assert_eq!( &headers["Accept"], &"text/html" );
    /// assert_eq!( &headers["X-Custom-Foo"], &"bar" );
    /// ```
    pub fn headers_mut(&mut self) -> Option<&mut HeaderMap> {
        self.inner.as_mut().ok().map(|h| &mut h.header)
    }

    /// Adds an extension to this builder
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    ///
    /// let response = Response::builder()
    ///     .extension("My Extension")
    ///     .body(())
    ///     .unwrap();
    ///
    /// assert_eq!(response.extensions().get::<&'static str>(),
    ///            Some(&"My Extension"));
    /// ```
    pub fn extension<T>(self, extension: T) -> Builder
    where
        T: Any + Send + Sync + 'static,
    {
        self.and_then(move |mut head| {
            head.extensions.insert(extension);
            Ok(head)
        })
    }

    /// Get a reference to the extensions for this response builder.
    ///
    /// If the builder has an error, this returns `None`.
    ///
    /// # Example
    ///
    /// ```
    /// use webparse::Response;
    /// let res = Response::builder().extension("My Extension").extension(5u32);
    /// let extensions = res.extensions_ref().unwrap();
    /// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
    /// assert_eq!(extensions.get::<u32>(), Some(&5u32));
    /// ```
    pub fn extensions_ref(&self) -> Option<&Extensions> {
        self.inner.as_ref().ok().map(|h| &h.extensions)
    }

    // /// Get a mutable reference to the extensions for this response builder.
    // ///
    // /// If the builder has an error, this returns `None`.
    // ///
    // /// # Example
    // ///
    // /// ```
    // /// use webparse::Response;
    // /// let mut res = Response::builder().extension("My Extension");
    // /// let mut extensions = res.extensions_mut().unwrap();
    // /// assert_eq!(extensions.get::<&'static str>(), Some(&"My Extension"));
    // /// extensions.insert(5u32);
    // /// assert_eq!(extensions.get::<u32>(), Some(&5u32));
    // /// ```
    // pub fn extensions_mut(&mut self) -> Option<&mut Extensions> {
    //     self.inner.as_mut().ok().map(|h| &mut h.extensions)
    // }

    /// "Consumes" this builder, using the provided `body` to return a
    /// constructed `Response`.
    ///
    /// # Errors
    ///
    /// This function may return an error if any previously configured argument
    /// failed to parse or get converted to the internal representation. For
    /// example if an invalid `head` was specified via `header("Foo",
    /// "Bar\r\n")` the error will be returned when this function is called
    /// rather than when `header` was called.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    ///
    /// let response = Response::builder()
    ///     .body(())
    ///     .unwrap();
    /// ```
    pub fn body<T: Serialize>(self, body: T) -> WebResult<Response<T>> {
        self.inner.map(move |mut parts: Parts| {
            let server = HeaderName::from_static("Server");
            if !parts.header.contains(&server) {
                parts.header.insert(server, "wenmeng");
            };
            Response {
                parts,
                body,
                partial: false,
            }
        }
        )
    }


    /// 获取返回的body长度, 如果为0则表示未写入信息
    pub fn get_body_len(&self) -> isize {
        if let Ok(inner) = &self.inner {
            inner.header.get_body_len()
        } else {
            0
        }
    }

    // private

    fn and_then<F>(self, func: F) -> Self
    where
        F: FnOnce(Parts) -> WebResult<Parts>,
    {
        Builder {
            inner: self.inner.and_then(func),
        }
    }
}

impl Default for Builder {
    #[inline]
    fn default() -> Builder {
        Builder {
            inner: Ok(Parts::default()),
        }
    }
}

impl Response<()> {
    /// Creates a new builder-style object to manufacture a `Response`
    ///
    /// This method returns an instance of `Builder` which can be used to
    /// create a `Response`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response = Response::builder()
    ///     .status(200)
    ///     .header("X-Custom-Foo", "Bar")
    ///     .body(())
    ///     .unwrap();
    /// ```
    #[inline]
    pub fn builder() -> Builder {
        Builder::new()
    }

    pub fn text() -> Builder {
        Response::builder()
        .status(200)
        .header(HeaderName::CONTENT_TYPE, "text/plain; charset=utf-8")
    }
    
    pub fn json() -> Builder {
        Response::builder()
        .status(200)
        .header(HeaderName::CONTENT_TYPE, "application/json; charset=utf-8")
    }

    pub fn status404() -> Builder {
        Response::builder()
        .status(404)
        .header(HeaderName::CONTENT_TYPE, "text/html; charset=utf-8")
    }
    
    pub fn status503() -> Builder {
        Response::builder()
        .status(503)
        .header(HeaderName::CONTENT_TYPE, "text/html; charset=utf-8")
    }

    pub fn status502() -> Builder {
        Response::builder()
        .status(502)
        .header(HeaderName::CONTENT_TYPE, "text/html; charset=utf-8")
    }

    pub fn status500() -> Builder {
        Response::builder()
        .status(500)
        .header(HeaderName::CONTENT_TYPE, "text/html; charset=utf-8")
    }
}

impl<T: Serialize> Response<T> {
    /// Creates a new blank `Response` with the body
    ///
    /// The component ports of this response will be set to their default, e.g.
    /// the ok status, no headers, etc.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response = Response::new("hello world");
    ///
    /// assert_eq!(response.status(), StatusCode::OK);
    /// assert_eq!(*response.body(), "hello world");
    /// ```
    #[inline]
    pub fn new(body: T) -> Response<T> {
        Response {
            parts: Parts::default(),
            body: body,
            partial: false,
        }
    }

    /// Creates a new `Response` with the given head and body
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response = Response::new("hello world");
    /// let (mut parts, body) = response.into_parts();
    ///
    /// parts.status = StatusCode::BAD_REQUEST;
    /// let response = Response::from_parts(parts, body);
    ///
    /// assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    /// assert_eq!(*response.body(), "hello world");
    /// ```
    #[inline]
    pub fn from_parts(parts: Parts, body: T) -> Response<T> {
        Response {
            parts: parts,
            body: body,
            partial: false,
        }
    }

    pub fn is_partial(&self) -> bool {
        self.partial
    }

    /// Returns the `StatusCode`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<()> = Response::default();
    /// assert_eq!(response.status(), StatusCode::OK);
    /// ```
    #[inline]
    pub fn status(&self) -> StatusCode {
        self.parts.status
    }

    /// Returns a mutable reference to the associated `StatusCode`.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let mut response: Response<()> = Response::default();
    /// *response.status_mut() = StatusCode::CREATED;
    /// assert_eq!(response.status(), StatusCode::CREATED);
    /// ```
    #[inline]
    pub fn status_mut(&mut self) -> &mut StatusCode {
        &mut self.parts.status
    }

    /// Returns a reference to the associated version.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<()> = Response::default();
    /// assert_eq!(response.version(), Version::HTTP11);
    /// ```
    #[inline]
    pub fn version(&self) -> Version {
        self.parts.version
    }

    /// Returns a mutable reference to the associated version.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let mut response: Response<()> = Response::default();
    /// *response.version_mut() = Version::HTTP2;
    /// assert_eq!(response.version(), Version::HTTP2);
    /// ```
    #[inline]
    pub fn version_mut(&mut self) -> &mut Version {
        &mut self.parts.version
    }

    /// Returns a reference to the associated header field map.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<()> = Response::default();
    /// assert!(response.headers().is_empty());
    /// ```
    #[inline]
    pub fn headers(&self) -> &HeaderMap {
        &self.parts.header
    }

    /// Returns a mutable reference to the associated header field map.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let mut response: Response<()> = Response::default();
    /// response.headers_mut().insert(HeaderName::HOST, HeaderValue::from_static("world"));
    /// assert!(!response.headers().is_empty());
    /// ```
    #[inline]
    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.parts.header
    }

    /// Returns a reference to the associated extensions.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<()> = Response::default();
    /// assert!(response.extensions().get::<i32>().is_none());
    /// ```
    #[inline]
    pub fn extensions(&self) -> &Extensions {
        &self.parts.extensions
    }

    #[inline]
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.parts.extensions
    }

    // /// Returns a mutable reference to the associated extensions.
    // ///
    // /// # Examples
    // ///
    // /// ```
    // /// use webparse::*;
    // /// use webparse::header::*;
    // /// let mut response: Response<()> = Response::default();
    // /// response.extensions_mut().insert("hello");
    // /// assert_eq!(response.extensions().get(), Some(&"hello"));
    // /// ```
    // #[inline]
    // pub fn extensions_mut(&mut self) -> &mut Extensions {
    //     &mut self.parts.extensions
    // }

    /// Returns a reference to the associated HTTP body.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<String> = Response::default();
    /// assert!(response.body().is_empty());
    /// ```
    #[inline]
    pub fn body(&self) -> &T {
        &self.body
    }

    /// Returns a mutable reference to the associated HTTP body.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let mut response: Response<String> = Response::default();
    /// response.body_mut().push_str("hello world");
    /// assert!(!response.body().is_empty());
    /// ```
    #[inline]
    pub fn body_mut(&mut self) -> &mut T {
        &mut self.body
    }

    pub fn headers_body(&mut self) -> (&HeaderMap, &T) {
        (&self.parts.header, &self.body)
    }

    pub fn headers_body_mut(&mut self) -> (&mut HeaderMap, &mut T) {
        (&mut self.parts.header, &mut self.body)
    }

    /// Consumes the response, returning just the body.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::Response;
    /// let response = Response::new("hello");
    /// let body = response.into_body();
    /// assert_eq!(body, "hello");
    /// ```
    #[inline]
    pub fn into_body(self) -> T {
        self.body
    }

    /// Consumes the response returning the head and body parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response: Response<()> = Response::default();
    /// let (parts, body) = response.into_parts();
    /// assert_eq!(parts.status, StatusCode::OK);
    /// ```
    #[inline]
    pub fn into_parts(self) -> (Parts, T) {
        (self.parts, self.body)
    }

    /// Consumes the response returning a new response with body mapped to the
    /// return type of the passed in function.
    ///
    /// # Examples
    ///
    /// ```
    /// use webparse::*;
    /// let response = Response::builder().body("some string").unwrap();
    /// let mapped_response: Response<&[u8]> = response.map(|b| {
    ///   assert_eq!(b, "some string");
    ///   b.as_bytes()
    /// });
    /// assert_eq!(mapped_response.body(), &"some string".as_bytes());
    /// ```
    #[inline]
    pub fn map<F, U: Serialize>(self, f: F) -> Response<U>
    where
        F: FnOnce(T) -> U,
    {
        Response {
            body: f(self.body),
            parts: self.parts,
            partial: self.partial,
        }
    }

    pub fn httpdata(&mut self) -> WebResult<Vec<u8>> {
        let mut buffer = BinaryMut::new();
        self.serialize(&mut buffer)?;
        return Ok(buffer.into_slice_all());
    }

    pub fn into<B: Serialize>(self, body: B) -> (Response<B>, T) {
        let new = Response {
            body,
            parts: self.parts,
            partial: self.partial,
        };
        (new, self.body)
    }

    pub fn into_type<B: From<T> + Serialize>(self) -> Response<B> {
        let new = Response {
            body: From::from(self.body),
            parts: self.parts,
            partial: self.partial,
        };
        new
    }

    pub fn into_binary(mut self) -> Response<Binary> {
        let mut binary = BinaryMut::new();
        let _ = self.body.serialize(&mut binary);
        let new = Response {
            body: binary.freeze(),
            parts: self.parts,
            partial: self.partial,
        };
        new
    }

    
    /// 获取返回的body长度, 如果为0则表示未写入信息
    pub fn get_body_len(&self) -> isize {
        self.parts.header.get_body_len()
    }

    pub fn encode_header<B: Buf + BufMut>(&mut self, buffer: &mut B) -> WebResult<usize> {
        let mut size = 0;
        size += self.parts.version.encode(buffer)?;
        size += buffer.put_slice(" ".as_bytes());
        size += self.parts.status.encode(buffer)?;
        size += self.parts.header.encode(buffer)?;
        Ok(size)
    }


    pub fn parse_buffer<B: Buf>(&mut self, buffer: &mut B) -> WebResult<usize> {
        let len = buffer.remaining();
        self.partial = true;
        // println!("===={:?}", String::from_utf8_lossy(buffer.chunk()));
        Helper::skip_empty_lines(buffer)?;
        self.parts.version = Helper::parse_version(buffer)?;
        Helper::skip_spaces(buffer)?;
        self.parts.status = Helper::parse_status(buffer)?;
        Helper::skip_spaces(buffer)?;
        let _reason = Helper::parse_status_token(buffer)?;
        Helper::skip_new_line(buffer)?;
        Helper::parse_header(buffer, &mut self.parts.header)?;
        self.partial = false;
        Ok(len - buffer.remaining())
    }
    
    pub fn replace_body(&mut self, mut body: T) {
        std::mem::swap(&mut self.body, &mut body);
    }

    pub fn replace_clone(&mut self, mut body: T) -> Response<T> {
        let parts = self.parts.clone();
        let partial = self.partial;
        std::mem::swap(&mut self.body, &mut body);
        Response {
            parts,
            body,
            partial,
        }
    }
}

impl<T: Default + Serialize> Default for Response<T> {
    fn default() -> Self {
        Self {
            parts: Default::default(),
            body: Default::default(),
            partial: Default::default(),
        }
    }
}

impl Default for Parts {
    fn default() -> Self {
        Self {
            status: StatusCode::OK,
            header: HeaderMap::new(),
            version: Version::Http11,
            extensions: Extensions::new(),
        }
    }
}

impl Clone for Parts {
    fn clone(&self) -> Self {
        let mut value = Self {
            status: self.status.clone(),
            header: self.header.clone(),
            version: self.version.clone(),
            extensions: Extensions::new(),
        };

        match self.extensions.get::<Arc<RwLock<HeaderIndex>>>() {
            Some(index) => {
                value.extensions.insert(index.clone());
            }
            _ => (),
        }
        value
    }
}

impl<T> Serialize for Response<T>
where
    T: Serialize,
{
    fn serialize<B: Buf + BufMut>(&mut self, buffer: &mut B) -> WebResult<usize> {
        let mut size = 0;
        size += self.parts.version.encode(buffer)?;
        size += buffer.put_slice(" ".as_bytes());
        size += self.parts.status.encode(buffer)?;
        size += self.parts.header.encode(buffer)?;
        size += self.body.serialize(buffer)?;
        Ok(size)
    }
}

impl<T> Display for Response<T>
where T: Serialize + Display {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.parts.version.fmt(f)?;
        f.write_str(" ")?;
        self.parts.status.fmt(f)?;
        f.write_str("\r\n")?;
        self.parts.header.fmt(f)?;
        self.body.fmt(f)
        // "".fmt(f)
    }
}