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 as_slice(&self) -> &[u8] {
26 self.get_bytes()
27 }
28
29 /// Try to view body as UTF-8 string.
30 ///
31 /// # Returns
32 ///
33 /// - `Option<&str>` - The body decoded as UTF-8, or `None` when the bytes
34 /// are not valid UTF-8.
35 pub fn as_str(&self) -> Option<&str> {
36 from_utf8(self.get_bytes()).ok()
37 }
38}
39
40impl Display for Body {
41 /// Formats the `Body` as its UTF-8 text, falling back to the debug
42 /// representation of the raw bytes when the body is not valid UTF-8.
43 ///
44 /// # Arguments
45 ///
46 /// - `&mut Formatter<'_>` - A mutable reference to a `Formatter` used for
47 /// writing the formatted string.
48 ///
49 /// # Returns
50 ///
51 /// - `fmt::Result` - A `fmt::Result` indicating whether the formatting was
52 /// successful.
53 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
54 match self.as_str() {
55 Some(s) => f.write_str(s),
56 None => f.write_str(&format!("{:?}", self.get_bytes())),
57 }
58 }
59}