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
use crate::{ decode::Decode, encode::Encode, into_type::IntoType, }; impl Encode for String { fn encode(&self) -> Vec<u8> { let len = self.required_len(); let mut buf = vec![0u8; len as usize]; buf[24..32].copy_from_slice(&(self.len() as u64).to_be_bytes()); buf[32..32 + self.len()].copy_from_slice(self.as_bytes()); buf } fn required_len(&self) -> u64 { (if self.len() / 32 == 0 { 32 + 32 } else { (self.len() / 32 + 1) * 32 + 32 }) as u64 } fn is_dynamic() -> bool { true } } impl<'a> Decode<'a> for String { fn decode(buf: &'a [u8]) -> Self { let len = u64::decode(&buf[0..32]); String::from_utf8(buf[32..32 + len as usize].to_vec()).unwrap() } } impl IntoType for String { fn into_type() -> String { "string".to_string() } } impl Encode for &str { fn encode(&self) -> Vec<u8> { let len = self.required_len(); let mut buf = vec![0u8; len as usize]; buf[24..32].copy_from_slice(&(self.len() as u64).to_be_bytes()); buf[32..32 + self.len()].copy_from_slice(self.as_bytes()); buf } fn required_len(&self) -> u64 { (if self.len() / 32 == 0 { 32 + 32 } else { (self.len() / 32 + 1) * 32 + 32 }) as u64 } fn is_dynamic() -> bool { true } } impl IntoType for &str { fn into_type() -> String { "string".to_string() } } impl<'a> Decode<'a> for &'a str { fn decode(buf: &'a [u8]) -> Self { let len = u64::decode(&buf[0..32]); std::str::from_utf8(&buf[32..32 + len as usize]).unwrap() } }