picoserve 0.18.0

An async no_std HTTP server suitable for bare-metal environments
Documentation
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
//! HTTP response types.
//!
//! Anything that implements [`IntoResponse`] can be returned from handlers, such as
//!
//! + [`Response`]
//! + [`Json`]
//! + [`Redirect`]
//! + `(("HeaderName", "HeaderValue"), impl Content)`
//! + `(("HeaderName0", "HeaderValue0"), ("HeaderName1", "HeaderValue1"), impl Content)`
//! + `([("HeaderName0", "HeaderValue0"), ("HeaderName1", "HeaderValue1")], impl Content)`
//! + `(StatusCode, impl Content)`
//! + `(StatusCode, ("HeaderName", "HeaderValue"), impl Content)`
//! + Tuples consisting of:
//!     1. Optionally, a status code. If not provided, a status code of [`StatusCode::OK`] is used
//!     2. A number of values which implement [`HeadersIter`], such as:
//!         + `(&str, impl Display)`
//!         + `Option<impl HeadersIter>`
//!         + `[impl HeadersIter; N]`
//!     3. A value which implements [`Content`]
//!
//! For a complete list, see [`IntoResponse`].

use core::fmt;

use crate::{
    io::{Read, Write},
    sync::oneshot_broadcast,
    KeepAlive, ResponseSent,
};

pub use picoserve_derive::ErrorWithStatusCode;

pub mod chunked;
pub mod custom;
pub mod fs;
pub mod sse;
pub mod status;
pub mod with_state;

#[cfg(feature = "json")]
pub mod json;

#[cfg(feature = "ws")]
pub mod ws;

pub(crate) mod response_stream;
pub(crate) use response_stream::ResponseStream;

pub use fs::{Directory, File};
pub use sse::EventStream;
pub use status::StatusCode;
pub use with_state::{ContentUsingState, IntoResponseWithState};

#[cfg(feature = "json")]
pub use json::Json;

#[cfg(feature = "ws")]
pub use ws::WebSocketUpgrade;

#[cfg(feature = "ws")] // Expand feature list if other features use this.
fn assert_implements_into_response<T: IntoResponse>(t: T) -> T {
    t
}

#[cfg(feature = "ws")] // Expand feature list if other features use this.
fn assert_implements_into_response_with_state<State, T: IntoResponseWithState<State>>(t: T) -> T {
    t
}

struct MeasureFormatSize<'a>(&'a mut usize);

impl fmt::Write for MeasureFormatSize<'_> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        *self.0 += s.len();

        Ok(())
    }
}

pub(crate) enum AfterBodyReadMode<'r> {
    ReadFromReader,
    ReadFromBuffer {
        remaining: &'r [u8],
    },
    SkipRemainingBodyFromReader {
        scratch_buffer: &'r mut [u8],
        body_bytes_remaining: usize,
    },
}

pub(crate) struct AfterBodyReader<'r, R: Read> {
    pub(crate) mode: AfterBodyReadMode<'r>,
    pub(crate) reader: R,
}

impl<R: Read> AfterBodyReader<'_, R> {
    async fn read_after_body(
        &mut self,
        buffer: &mut [u8],
        _upgrade_token: &crate::extract::UpgradeToken,
    ) -> Result<usize, R::Error> {
        loop {
            break match &mut self.mode {
                AfterBodyReadMode::ReadFromReader => self.reader.read(buffer).await,
                AfterBodyReadMode::ReadFromBuffer { remaining } => {
                    if remaining.is_empty() {
                        self.mode = AfterBodyReadMode::ReadFromReader;

                        continue;
                    }

                    let read_size = remaining.len().min(buffer.len());

                    buffer[..read_size].copy_from_slice(&remaining[..read_size]);

                    *remaining = &remaining[read_size..];

                    Ok(read_size)
                }
                AfterBodyReadMode::SkipRemainingBodyFromReader {
                    scratch_buffer,
                    body_bytes_remaining,
                } => {
                    if *body_bytes_remaining == 0 {
                        self.mode = AfterBodyReadMode::ReadFromReader;

                        continue;
                    }

                    let read_buffer_size = (*body_bytes_remaining).min(scratch_buffer.len());

                    let read_size = self
                        .reader
                        .read(&mut scratch_buffer[..read_buffer_size])
                        .await?;

                    *body_bytes_remaining -= read_size;

                    if read_size == 0 {
                        // EOF from reader while skipping, transition to reading directly from reader, which will again return EOF.
                        self.mode = AfterBodyReadMode::ReadFromReader;

                        Ok(0)
                    } else {
                        continue;
                    }
                }
            };
        }
    }
}

/// A connection which has been upgraded, and is thus allowed to read arbitary data from the socket.
pub struct UpgradedConnection<'r, R: Read> {
    upgrade_token: crate::extract::UpgradeToken,
    reader: AfterBodyReader<'r, R>,
}

impl<R: Read> crate::io::ErrorType for UpgradedConnection<'_, R> {
    type Error = R::Error;
}

impl<R: Read> Read for UpgradedConnection<'_, R> {
    async fn read(&mut self, buffer: &mut [u8]) -> Result<usize, Self::Error> {
        self.reader
            .read_after_body(buffer, &self.upgrade_token)
            .await
    }
}

/// A handle to the current connection. Allows a long-lasting response to check if the client has disconnected.
pub struct Connection<'r, R: Read> {
    pub(crate) reader: AfterBodyReader<'r, R>,
    pub(crate) connection_flags: &'r mut crate::request::ConnectionFlags,
    pub(crate) shutdown_signal: oneshot_broadcast::Listener<'r, ()>,
}

impl<'r, R: Read> Connection<'r, R> {
    /// Upgrade the connection and get access to the inner reader
    pub fn upgrade(self, upgrade_token: crate::extract::UpgradeToken) -> UpgradedConnection<'r, R> {
        self.connection_flags.notify_connection_has_been_upgraded();

        UpgradedConnection {
            upgrade_token,
            reader: self.reader,
        }
    }

    /// Wait for the client to disconnect. This will discard any additional data sent by the client.
    pub async fn wait_for_disconnection(self) -> Result<(), R::Error> {
        crate::extract::UpgradeToken::discard_all_data(self).await
    }

    pub async fn run_until_disconnection<T>(
        self,
        default: T,
        action: impl core::future::Future<Output = Result<T, R::Error>>,
    ) -> Result<T, R::Error> {
        crate::futures::select(action, async {
            self.wait_for_disconnection().await?;
            Ok(default)
        })
        .await
    }
}

pub(crate) struct EmptyReader<E: crate::io::Error>(core::marker::PhantomData<E>);

impl<E: crate::io::Error> crate::io::ErrorType for EmptyReader<E> {
    type Error = E;
}

impl<E: crate::io::Error> crate::io::Read for EmptyReader<E> {
    async fn read(&mut self, _buf: &mut [u8]) -> Result<usize, Self::Error> {
        Ok(0)
    }
}

pub(crate) struct EmptyParts {
    connection_flags: crate::request::ConnectionFlags,
    shutdown_signal: oneshot_broadcast::SignalCore<()>,
}

impl Default for EmptyParts {
    fn default() -> Self {
        Self {
            connection_flags: crate::request::ConnectionFlags::new(),
            shutdown_signal: oneshot_broadcast::Signal::core(),
        }
    }
}

impl<'r, E: crate::io::Error> Connection<'r, EmptyReader<E>> {
    pub(crate) fn empty(
        EmptyParts {
            connection_flags,
            shutdown_signal,
        }: &'r mut EmptyParts,
    ) -> Self {
        Self {
            reader: AfterBodyReader {
                mode: AfterBodyReadMode::ReadFromReader,
                reader: EmptyReader(core::marker::PhantomData),
            },
            connection_flags,
            shutdown_signal: shutdown_signal.make_signal().listen(),
        }
    }
}

#[doc(hidden)]
pub trait ForEachHeader {
    type Output;
    type Error;

    async fn call<Value: fmt::Display>(
        &mut self,
        name: &str,
        value: Value,
    ) -> Result<(), Self::Error>;

    async fn finalize(self) -> Result<Self::Output, Self::Error>;
}

struct BorrowedForEachHeader<'a, F: ForEachHeader>(&'a mut F);

impl<F: ForEachHeader> ForEachHeader for BorrowedForEachHeader<'_, F> {
    type Output = ();
    type Error = F::Error;

    async fn call<Value: fmt::Display>(
        &mut self,
        name: &str,
        value: Value,
    ) -> Result<(), F::Error> {
        self.0.call(name, value).await
    }

    async fn finalize(self) -> Result<Self::Output, Self::Error> {
        Ok(())
    }
}

/// The HTTP response headers.
pub trait HeadersIter {
    /// Perform the following action for each header.
    async fn for_each_header<F: ForEachHeader>(self, f: F) -> Result<F::Output, F::Error>;
}

impl<V: fmt::Display> HeadersIter for (&str, V) {
    async fn for_each_header<F: ForEachHeader>(self, mut f: F) -> Result<F::Output, F::Error> {
        let (name, value) = self;
        f.call(name, value).await?;
        f.finalize().await
    }
}

impl<V: fmt::Display> HeadersIter for &[(&str, V)] {
    async fn for_each_header<F: ForEachHeader>(self, mut f: F) -> Result<F::Output, F::Error> {
        for (name, value) in self {
            f.call(name, value).await?;
        }
        f.finalize().await
    }
}

impl<H: HeadersIter, const N: usize> HeadersIter for [H; N] {
    async fn for_each_header<F: ForEachHeader>(self, mut f: F) -> Result<F::Output, F::Error> {
        for headers in self {
            headers
                .for_each_header(BorrowedForEachHeader(&mut f))
                .await?;
        }
        f.finalize().await
    }
}

impl<T: HeadersIter> HeadersIter for Option<T> {
    async fn for_each_header<F: ForEachHeader>(self, f: F) -> Result<F::Output, F::Error> {
        if let Some(headers) = self {
            headers.for_each_header(f).await
        } else {
            f.finalize().await
        }
    }
}

struct HeadersChain<A: HeadersIter, B: HeadersIter>(A, B);

impl<A: HeadersIter, B: HeadersIter> HeadersIter for HeadersChain<A, B> {
    async fn for_each_header<F: ForEachHeader>(self, mut f: F) -> Result<F::Output, F::Error> {
        let Self(a, b) = self;
        a.for_each_header(BorrowedForEachHeader(&mut f)).await?;
        b.for_each_header(BorrowedForEachHeader(&mut f)).await?;
        f.finalize().await
    }
}

/// The HTTP response body.
pub trait Body {
    /// Write the response body to the socket.
    async fn write_response_body<R: Read, W: Write<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        writer: W,
    ) -> Result<(), W::Error>;
}

#[doc(hidden)]
pub struct NoBody;

impl Body for NoBody {
    async fn write_response_body<R: Read, W: Write<Error = R::Error>>(
        self,
        _connection: Connection<'_, R>,
        _writer: W,
    ) -> Result<(), W::Error> {
        Ok(())
    }
}

/// Indicates that a [`Response`] has no content.
///
/// Tuples where the first element is a [`StatusCode`], the last element is [`NoContent`] and the others implement [`HeadersIter`] implement [`IntoResponse`].
pub struct NoContent;

/// A [`Response`] body containing data with a known type and length.
pub trait Content {
    /// The value of the "Content-Type" header.
    fn content_type(&self) -> &'static str;

    /// The value of the "Content-Length" header.
    fn content_length(&self) -> usize;

    /// Write the content data.
    async fn write_content<W: Write>(self, writer: W) -> Result<(), W::Error>;
}

macro_rules! content_methods {
    ($as:ident) => {
        fn content_type(&self) -> &'static str {
            self.$as().content_type()
        }

        fn content_length(&self) -> usize {
            self.$as().content_length()
        }

        async fn write_content<W: Write>(self, writer: W) -> Result<(), W::Error> {
            self.$as().write_content(writer).await
        }
    };
}

#[doc(hidden)]
pub struct ContentBody<C: Content> {
    content: C,
}

impl<C: Content> Body for ContentBody<C> {
    async fn write_response_body<R: Read, W: Write<Error = R::Error>>(
        self,
        _connection: Connection<'_, R>,
        mut writer: W,
    ) -> Result<(), W::Error> {
        self.content.write_content(&mut writer).await?;
        writer.flush().await?;
        Ok(())
    }
}

impl Content for &[u8] {
    fn content_type(&self) -> &'static str {
        "application/octet-stream"
    }

    fn content_length(&self) -> usize {
        self.len()
    }

    async fn write_content<W: Write>(self, mut writer: W) -> Result<(), W::Error> {
        writer.write_all(self).await
    }
}

impl<const N: usize> Content for heapless::Vec<u8, N> {
    content_methods!(as_slice);
}

#[cfg(any(test, feature = "alloc"))]
impl Content for alloc::vec::Vec<u8> {
    content_methods!(as_slice);
}

impl Content for &str {
    fn content_type(&self) -> &'static str {
        "text/plain; charset=utf-8"
    }

    fn content_length(&self) -> usize {
        self.len()
    }

    async fn write_content<W: Write>(self, writer: W) -> Result<(), W::Error> {
        self.as_bytes().write_content(writer).await
    }
}

impl<const N: usize> Content for heapless::String<N> {
    content_methods!(as_str);
}

#[cfg(any(test, feature = "alloc"))]
impl Content for alloc::string::String {
    content_methods!(as_str);
}

impl Content for fmt::Arguments<'_> {
    fn content_type(&self) -> &'static str {
        "".content_type()
    }

    fn content_length(&self) -> usize {
        use fmt::Write;
        let mut size = 0;
        write!(MeasureFormatSize(&mut size), "{self}").map_or(0, |()| size)
    }

    async fn write_content<W: Write>(self, mut writer: W) -> Result<(), W::Error> {
        use crate::io::WriteExt;
        write!(writer, "{}", self).await
    }
}

#[doc(hidden)]
pub struct NoHeaders;

impl HeadersIter for NoHeaders {
    async fn for_each_header<F: ForEachHeader>(self, f: F) -> Result<F::Output, F::Error> {
        f.finalize().await
    }
}

#[doc(hidden)]
pub struct ContentHeaders {
    content_type: &'static str,
    content_length: usize,
}

impl HeadersIter for ContentHeaders {
    async fn for_each_header<F: ForEachHeader>(self, mut f: F) -> Result<F::Output, F::Error> {
        f.call("Content-Type", self.content_type).await?;
        f.call("Content-Length", self.content_length).await?;
        f.finalize().await
    }
}

/// Represents a HTTP response.
pub struct Response<H: HeadersIter, B: Body> {
    pub(crate) status_code: StatusCode,
    pub(crate) headers: H,
    pub(crate) body: B,
}

impl<C: Content> Response<ContentHeaders, ContentBody<C>> {
    /// Creates a response from a HTTP status code and body with content. The Content-Type and Content-Length headers are generated from the values returned by the Body.
    pub fn new(status_code: StatusCode, content: C) -> Self {
        Self {
            status_code,
            headers: ContentHeaders {
                content_type: content.content_type(),
                content_length: content.content_length(),
            },
            body: ContentBody { content },
        }
    }

    /// A response with a status of 200 "OK".
    pub fn ok(body: C) -> Self {
        Self::new(StatusCode::OK, body)
    }
}

impl Response<NoHeaders, NoBody> {
    pub fn empty(status_code: StatusCode) -> Self {
        Self {
            status_code,
            headers: NoHeaders,
            body: NoBody,
        }
    }
}

impl<H: HeadersIter, B: Body> Response<H, B> {
    /// Get the status code of the response.
    pub fn status_code(&self) -> StatusCode {
        self.status_code
    }

    /// Return a new response with the given status code.
    pub fn with_status_code(self, status_code: StatusCode) -> Self {
        let Self {
            status_code: _,
            headers,
            body,
        } = self;

        Self {
            status_code,
            headers,
            body,
        }
    }

    /// Add additional headers to a response.
    pub fn with_headers<HH: HeadersIter>(self, headers: HH) -> Response<impl HeadersIter, B> {
        let Response {
            status_code,
            headers: current_headers,
            body,
        } = self;

        Response {
            status_code,
            headers: HeadersChain(current_headers, headers),
            body,
        }
    }

    /// Add an additional header to a response.
    pub fn with_header<V: fmt::Display>(
        self,
        name: &'static str,
        value: V,
    ) -> Response<impl HeadersIter, B> {
        self.with_headers((name, value))
    }
}

/// Types which a HTTP response can be written to.
pub trait ResponseWriter: Sized {
    /// Errors arising while writing the response.
    type Error;

    /// Write the given response to the socket, which may include the upgraded data, which thus may read from the provided connenction.
    async fn write_response<R: Read<Error = Self::Error>, H: HeadersIter, B: Body>(
        self,
        connection: Connection<'_, R>,
        response: Response<H, B>,
    ) -> Result<ResponseSent, Self::Error>;
}

/// Trait for generating responses.
///
/// Types that implement `IntoResponse` can be returned from handlers.
pub trait IntoResponse: Sized {
    /// Write the generated response into the given [`ResponseWriter`].
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error>;
}

impl<C: Content> IntoResponse for C {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        response_writer
            .write_response(connection, Response::ok(self))
            .await
    }
}

impl<H: HeadersIter, B: Body> IntoResponse for Response<H, B> {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        response_writer.write_response(connection, self).await
    }
}

impl IntoResponse for core::convert::Infallible {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        _connection: Connection<'_, R>,
        _response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        match self {}
    }
}

impl IntoResponse for () {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        "OK\n".write_to(connection, response_writer).await
    }
}

impl<T: IntoResponse, E: IntoResponse> IntoResponse for Result<T, E> {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        match self {
            Ok(value) => value.write_to(connection, response_writer).await,
            Err(err) => err.write_to(connection, response_writer).await,
        }
    }
}

macro_rules! declare_tuple_into_response {
    ($($($name:ident)*;)*) => {
        $(
            impl<$($name: HeadersIter,)* C: Content> IntoResponse for (StatusCode, $($name,)* C,) {
                #[allow(non_snake_case)]
                async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(self, connection: Connection<'_, R>, response_writer: W) -> Result<ResponseSent, W::Error> {
                    let (status_code, $($name,)* body) = self;

                    response_writer.write_response(
                        connection,
                        Response::new(status_code, body)
                        $(.with_headers($name,))*
                    ).await
                }
            }

            impl<$($name: HeadersIter,)* C: Content> IntoResponse for ($($name,)* C,) {
                #[allow(non_snake_case)]
                async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(self, connection: Connection<'_, R>, response_writer: W) -> Result<ResponseSent, W::Error> {
                    let ($($name,)* body,) = self;

                    response_writer.write_response(
                        connection,
                        Response::new(StatusCode::OK, body)
                        $(.with_headers($name,))*
                    ).await
                }
            }

            impl<$($name: HeadersIter,)*> IntoResponse for (StatusCode, $($name,)* NoContent,) {
                #[allow(non_snake_case)]
                async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(self, connection: Connection<'_, R>, response_writer: W) -> Result<ResponseSent, W::Error> {
                    let (status_code, $($name,)* NoContent,) = self;

                    response_writer.write_response(
                        connection,
                        Response::empty(status_code)
                        $(.with_headers($name,))*
                    ).await
                }
            }
        )*
    };
}

declare_tuple_into_response!(
    ;
    H1;
    H1 H2;
    H1 H2 H3;
    H1 H2 H3 H4;
    H1 H2 H3 H4 H5;
    H1 H2 H3 H4 H5 H6;
    H1 H2 H3 H4 H5 H6 H7;
    H1 H2 H3 H4 H5 H6 H7 H8;
    H1 H2 H3 H4 H5 H6 H7 H8 H9;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15;
    H1 H2 H3 H4 H5 H6 H7 H8 H9 H10 H11 H12 H13 H14 H15 H16;
);

/// Returns a value in [`core::fmt::Debug`] form as text.
pub struct DebugValue<D>(pub D);

impl<D: fmt::Debug> IntoResponse for DebugValue<D> {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        response_writer
            .write_response(connection, Response::ok(format_args!("{:?}\r\n", self.0)))
            .await
    }
}

/// Response that redirects the request to another location.
pub struct Redirect {
    status_code: StatusCode,
    location: &'static str,
}

impl Redirect {
    /// Create a new [`Redirect`] that uses a 303 "See Other" status code.
    pub fn to(location: &'static str) -> Self {
        Self {
            status_code: StatusCode::SEE_OTHER,
            location,
        }
    }
}

impl IntoResponse for Redirect {
    async fn write_to<R: Read, W: ResponseWriter<Error = R::Error>>(
        self,
        connection: Connection<'_, R>,
        response_writer: W,
    ) -> Result<ResponseSent, W::Error> {
        (
            self.status_code,
            ("Location", self.location),
            format_args!("{}\n", self.location),
        )
            .write_to(connection, response_writer)
            .await
    }
}

/// Error Responses consisting of a `text/plain` message and a [`StatusCode`].
///
/// This trait is derivable. See [`picoserve_derive::ErrorWithStatusCode`].
pub trait ErrorWithStatusCode: fmt::Display + IntoResponse {
    /// The [`StatusCode`] to return for this error.
    fn status_code(&self) -> StatusCode;
}