Skip to main content

base_http/body/
head.rs

1// Released under the MIT License.
2// Copyright, 2026, by Samuel Williams.
3
4use super::{BodyFrame, ReadableBody};
5use base_scheduler::{Cancellation, Cancelled};
6
7/// An empty body retaining the representation length for a HEAD response.
8#[derive(Clone, Copy, Debug, Default)]
9pub struct HeadBody {
10    length: Option<u64>,
11}
12
13impl HeadBody {
14    pub const fn new(length: Option<u64>) -> Self {
15        Self { length }
16    }
17
18    /// Capture the representation length and close the supplied body.
19    pub fn for_body<B: ReadableBody + ?Sized>(body: &mut B) -> Self {
20        let head = Self::new(body.length());
21        body.close(None);
22        head
23    }
24}
25
26impl ReadableBody for HeadBody {
27    type Data = Vec<u8>;
28    type Error = Cancelled;
29
30    fn may_have_trailers(&self) -> bool {
31        false
32    }
33
34    fn is_ready(&self) -> bool {
35        true
36    }
37
38    fn is_empty(&self) -> bool {
39        true
40    }
41
42    fn length(&self) -> Option<u64> {
43        self.length
44    }
45
46    fn close(&mut self, _error: Option<Self::Error>) {}
47
48    async fn read(
49        &mut self,
50        cancellation: &Cancellation,
51    ) -> Result<BodyFrame<Self::Data>, Self::Error> {
52        cancellation.check()?;
53        Ok(BodyFrame::End)
54    }
55}