parsec_interface/requests/response/
response_body.rs

1// Copyright 2019 Contributors to the Parsec project.
2// SPDX-License-Identifier: Apache-2.0
3use super::Result;
4use serde::{Deserialize, Serialize};
5use std::io::{Read, Write};
6use std::ops::{Deref, DerefMut};
7use zeroize::Zeroize;
8
9/// Wrapper around the body of a response.
10///
11/// Hides the contents and keeps them immutable.
12#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Zeroize)]
13#[zeroize(drop)]
14pub struct ResponseBody {
15    buffer: Vec<u8>,
16}
17
18impl Deref for ResponseBody {
19    type Target = [u8];
20
21    fn deref(&self) -> &Self::Target {
22        &self.buffer
23    }
24}
25
26impl DerefMut for ResponseBody {
27    fn deref_mut(&mut self) -> &mut Self::Target {
28        &mut self.buffer
29    }
30}
31
32impl ResponseBody {
33    /// Create a new empty response body.
34    pub(crate) fn new() -> ResponseBody {
35        ResponseBody { buffer: Vec::new() }
36    }
37
38    /// Read a response body from a stream, given the number of bytes it contains.
39    pub(super) fn read_from_stream(mut stream: &mut impl Read, len: usize) -> Result<ResponseBody> {
40        let buffer = get_from_stream!(stream; len);
41        Ok(ResponseBody { buffer })
42    }
43
44    /// Write a response body to a stream.
45    pub(super) fn write_to_stream(&self, stream: &mut impl Write) -> Result<()> {
46        stream.write_all(&self.buffer)?;
47        Ok(())
48    }
49
50    /// Create a `ResponseBody` from a vector of bytes.
51    pub(crate) fn from_bytes(buffer: Vec<u8>) -> ResponseBody {
52        ResponseBody { buffer }
53    }
54
55    /// Get the body as a slice of bytes.
56    pub fn bytes(&self) -> &[u8] {
57        &self.buffer
58    }
59
60    /// Get the size of the body.
61    pub fn len(&self) -> usize {
62        self.buffer.len()
63    }
64
65    /// Check if body is empty.
66    pub fn is_empty(&self) -> bool {
67        self.buffer.is_empty()
68    }
69}