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