1 use super::{param_header::*, param_type::*, *}; 2 3 use bytes::{Bytes, BytesMut}; 4 use rand::Rng; 5 use std::fmt; 6 7 #[derive(Default, Debug, Clone, PartialEq)] 8 pub(crate) struct ParamStateCookie { 9 pub(crate) cookie: Bytes, 10 } 11 12 /// String makes paramStateCookie printable 13 impl fmt::Display for ParamStateCookie { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result14 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 15 write!(f, "{}: {:?}", self.header(), self.cookie) 16 } 17 } 18 19 impl Param for ParamStateCookie { header(&self) -> ParamHeader20 fn header(&self) -> ParamHeader { 21 ParamHeader { 22 typ: ParamType::StateCookie, 23 value_length: self.value_length() as u16, 24 } 25 } 26 unmarshal(raw: &Bytes) -> Result<Self>27 fn unmarshal(raw: &Bytes) -> Result<Self> { 28 let header = ParamHeader::unmarshal(raw)?; 29 let cookie = raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); 30 Ok(ParamStateCookie { cookie }) 31 } 32 marshal_to(&self, buf: &mut BytesMut) -> Result<usize>33 fn marshal_to(&self, buf: &mut BytesMut) -> Result<usize> { 34 self.header().marshal_to(buf)?; 35 buf.extend(self.cookie.clone()); 36 Ok(buf.len()) 37 } 38 value_length(&self) -> usize39 fn value_length(&self) -> usize { 40 self.cookie.len() 41 } 42 clone_to(&self) -> Box<dyn Param + Send + Sync>43 fn clone_to(&self) -> Box<dyn Param + Send + Sync> { 44 Box::new(self.clone()) 45 } 46 as_any(&self) -> &(dyn Any + Send + Sync)47 fn as_any(&self) -> &(dyn Any + Send + Sync) { 48 self 49 } 50 } 51 52 impl ParamStateCookie { new() -> Self53 pub(crate) fn new() -> Self { 54 let mut cookie = BytesMut::new(); 55 cookie.resize(32, 0); 56 rand::thread_rng().fill(cookie.as_mut()); 57 58 ParamStateCookie { 59 cookie: cookie.freeze(), 60 } 61 } 62 } 63