Skip to main content

http_request/common/
impl.rs

1use super::*;
2
3impl Body {
4    /// Empty body.
5    pub const fn empty() -> Self {
6        Self { bytes: Vec::new() }
7    }
8
9    /// Construct from any `Into<Vec<u8>>`.
10    ///
11    /// # Arguments
12    ///
13    /// - `B` - The raw bytes to store, converted into the owned `Vec<u8>`.
14    pub fn from_bytes<B: Into<Vec<u8>>>(bytes: B) -> Self {
15        Self {
16            bytes: bytes.into(),
17        }
18    }
19
20    /// View body as `&[u8]`.
21    ///
22    /// # Returns
23    ///
24    /// - `&[u8]` - The raw body bytes.
25    pub fn get_bytes_ref(&self) -> &[u8] {
26        &self.bytes
27    }
28
29    /// View body as `&[u8]`.
30    ///
31    /// # Returns
32    ///
33    /// - `&[u8]` - The raw body bytes.
34    pub fn as_slice(&self) -> &[u8] {
35        self.get_bytes()
36    }
37
38    /// Try to view body as UTF-8 string.
39    ///
40    /// # Returns
41    ///
42    /// - `Option<&str>` - The body decoded as UTF-8, or `None` when the bytes
43    ///   are not valid UTF-8.
44    pub fn as_str(&self) -> Option<&str> {
45        std::str::from_utf8(self.get_bytes()).ok()
46    }
47}
48
49impl Display for Body {
50    /// Formats the `Body` as its UTF-8 text, falling back to the debug
51    /// representation of the raw bytes when the body is not valid UTF-8.
52    ///
53    /// # Arguments
54    ///
55    /// - `&mut Formatter<'_>` - A mutable reference to a `Formatter` used for
56    ///   writing the formatted string.
57    ///
58    /// # Returns
59    ///
60    /// - `fmt::Result` - A `fmt::Result` indicating whether the formatting was
61    ///   successful.
62    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
63        match self.as_str() {
64            Some(s) => f.write_str(s),
65            None => f.write_str(&format!("{:?}", self.bytes)),
66        }
67    }
68}