1use crate::{
2 decode::Decode,
3 encode::Encode,
4 into_type::IntoType,
5};
6use std::borrow::Cow;
7
8impl Encode for String {
9 fn encode(&self) -> Vec<u8> {
10 let len = self.required_len();
11 let mut buf = vec![0u8; len as usize];
12 buf[24..32].copy_from_slice(&(self.len() as u64).to_be_bytes());
13 buf[32..32 + self.len()].copy_from_slice(self.as_bytes());
14 buf
15 }
16
17 fn required_len(&self) -> u64 {
18 (if self.len() / 32 == 0 {
19 32 + 32
20 } else {
21 (self.len() / 32 + 1) * 32 + 32
22 }) as u64
23 }
24
25 fn is_dynamic() -> bool {
26 true
27 }
28}
29
30impl<'a> Decode<'a> for String {
31 fn decode(buf: &'a [u8]) -> Self {
32 let len = u64::decode(&buf[0..32]);
33 String::from_utf8(buf[32..32 + len as usize].to_vec()).unwrap()
34 }
35}
36
37impl IntoType for String {
38 fn into_type() -> Cow<'static, str> {
39 Cow::Borrowed("string")
40 }
41}
42
43impl Encode for &str {
44 fn encode(&self) -> Vec<u8> {
45 let len = self.required_len();
46 let mut buf = vec![0u8; len as usize];
47 buf[24..32].copy_from_slice(&(self.len() as u64).to_be_bytes());
48 buf[32..32 + self.len()].copy_from_slice(self.as_bytes());
49 buf
50 }
51
52 fn required_len(&self) -> u64 {
53 (if self.len() / 32 == 0 {
54 32 + 32
55 } else {
56 (self.len() / 32 + 1) * 32 + 32
57 }) as u64
58 }
59
60 fn is_dynamic() -> bool {
61 true
62 }
63}
64
65impl IntoType for &str {
66 fn into_type() -> Cow<'static, str> {
67 Cow::Borrowed("string")
68 }
69}
70
71impl<'a> Decode<'a> for &'a str {
72 fn decode(buf: &'a [u8]) -> Self {
73 let len = u64::decode(&buf[0..32]);
74 std::str::from_utf8(&buf[32..32 + len as usize]).unwrap()
75 }
76}