1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
use std::fmt; use async_std::io::{Read, Write}; use crate::{Error}; use crate::utils::{read_chunked_stream, read_sized_stream}; pub struct Body { bytes: Vec<u8>, length: usize, length_limit: Option<usize>, } impl Body { pub fn new() -> Self { Self { bytes: Vec::new(), length: 0, length_limit: None, } } pub fn bytes(&self) -> &Vec<u8> { &self.bytes } pub fn length(&self) -> usize { self.length } pub fn length_limit(&self) -> Option<usize> { self.length_limit } pub fn has_length_limit(&self) -> bool { self.length_limit.is_some() } pub fn set_length_limit(&mut self, limit: usize) { self.length_limit = Some(limit); } pub fn remove_length_limit(&mut self) { self.length_limit = None; } pub async fn read_chunked_stream<I>(&mut self, stream: &mut I) -> Result<usize, Error> where I: Write + Read + Unpin, { let limit = match self.length_limit { Some(limit) => match limit == 0 { true => return Err(Error::SizeLimitExceeded(limit)), false => Some(limit - self.length), }, None => None, }; let length = read_chunked_stream(stream, &mut self.bytes, limit).await?; self.length += length; Ok(length) } pub async fn read_sized_stream<I>(&mut self, stream: &mut I, length: usize) -> Result<usize, Error> where I: Write + Read + Unpin, { match self.length_limit { Some(limit) => match length + self.length > limit { true => return Err(Error::SizeLimitExceeded(limit)), false => (), }, None => (), }; let length = read_sized_stream(stream, &mut self.bytes, length).await?; self.length += length; Ok(length) } pub async fn read_string<V: Into<String>>(&mut self, value: V) -> Result<usize, Error> { let mut bytes = value.into().as_bytes().to_vec(); let length = bytes.len(); match self.length_limit { Some(limit) => match length + self.length > limit { true => return Err(Error::SizeLimitExceeded(limit)), false => (), }, None => (), }; self.bytes.append(&mut bytes); self.length += length; Ok(length) } pub fn clear(&mut self) { self.bytes.clear(); self.length = 0; self.length_limit = None; } } impl fmt::Display for Body { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "{:?}", self.bytes()) } }