1 use super::{param_type::*, *}; 2 3 use bytes::{Buf, BufMut, Bytes, BytesMut}; 4 use std::fmt; 5 6 #[derive(Debug, Clone, PartialEq)] 7 pub(crate) struct ParamHeader { 8 pub(crate) typ: ParamType, 9 pub(crate) value_length: u16, 10 } 11 12 pub(crate) const PARAM_HEADER_LENGTH: usize = 4; 13 14 /// String makes paramHeader printable 15 impl fmt::Display for ParamHeader { fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result16 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 17 write!(f, "{}", self.typ) 18 } 19 } 20 21 impl Param for ParamHeader { header(&self) -> ParamHeader22 fn header(&self) -> ParamHeader { 23 self.clone() 24 } 25 unmarshal(raw: &Bytes) -> Result<Self>26 fn unmarshal(raw: &Bytes) -> Result<Self> { 27 if raw.len() < PARAM_HEADER_LENGTH { 28 return Err(Error::ErrParamHeaderTooShort); 29 } 30 31 let reader = &mut raw.clone(); 32 33 let typ: ParamType = reader.get_u16().into(); 34 35 let len = reader.get_u16() as usize; 36 if len < PARAM_HEADER_LENGTH || raw.len() < len { 37 return Err(Error::ErrParamHeaderTooShort); 38 } 39 40 Ok(ParamHeader { 41 typ, 42 value_length: (len - PARAM_HEADER_LENGTH) as u16, 43 }) 44 } 45 marshal_to(&self, writer: &mut BytesMut) -> Result<usize>46 fn marshal_to(&self, writer: &mut BytesMut) -> Result<usize> { 47 writer.put_u16(self.typ.into()); 48 writer.put_u16(self.value_length + PARAM_HEADER_LENGTH as u16); 49 Ok(writer.len()) 50 } 51 value_length(&self) -> usize52 fn value_length(&self) -> usize { 53 self.value_length as usize 54 } 55 clone_to(&self) -> Box<dyn Param + Send + Sync>56 fn clone_to(&self) -> Box<dyn Param + Send + Sync> { 57 Box::new(self.clone()) 58 } 59 as_any(&self) -> &(dyn Any + Send + Sync)60 fn as_any(&self) -> &(dyn Any + Send + Sync) { 61 self 62 } 63 } 64