Skip to main content

base_http/body/
head.rs

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