1use crate::{
2 decode::Decode,
3 encode::Encode,
4 into_type::IntoType,
5 Error,
6};
7use std::{
8 borrow::Cow,
9 convert::{
10 TryFrom,
11 TryInto,
12 },
13};
14
15pub struct Function(pub [u8; 32]);
17
18impl TryFrom<&str> for Function {
19 type Error = Error;
20
21 fn try_from(value: &str) -> Result<Function, Self::Error> {
22 let s = match value.len() {
24 48 => value,
25 50 => value.split_at(2).1,
26 _ => value,
27 };
28
29 let slice = hex::decode(&s)?;
30 let slice: [u8; 24] = slice.as_slice().try_into()?;
31 let mut buf = [0u8; 32];
32 buf[0..24].copy_from_slice(&slice);
33 Ok(Function(buf))
34 }
35}
36
37impl TryFrom<&[u8]> for Function {
38 type Error = Error;
39
40 fn try_from(value: &[u8]) -> Result<Function, Self::Error> {
41 let slice: [u8; 24] = value.try_into()?;
42 let mut buf = [0u8; 32];
43 buf[0..24].copy_from_slice(&slice);
44 Ok(Function(buf))
45 }
46}
47
48impl TryFrom<&Vec<u8>> for Function {
49 type Error = Error;
50
51 fn try_from(value: &Vec<u8>) -> Result<Function, Self::Error> {
52 let slice: [u8; 24] = value.as_slice().try_into()?;
53 let mut buf = [0u8; 32];
54 buf[0..24].copy_from_slice(&slice);
55 Ok(Function(buf))
56 }
57}
58
59impl TryFrom<Vec<u8>> for Function {
60 type Error = Error;
61
62 fn try_from(value: Vec<u8>) -> Result<Function, Self::Error> {
63 let slice: [u8; 24] = value.as_slice().try_into()?;
64 let mut buf = [0u8; 32];
65 buf[0..24].copy_from_slice(&slice);
66 Ok(Function(buf))
67 }
68}
69
70impl Encode for Function {
71 fn encode(&self) -> Vec<u8> {
72 self.0.to_vec()
73 }
74}
75
76impl<'a> Decode<'a> for Function {
77 fn decode(buf: &'a [u8]) -> Self {
78 Function(buf[0..32].try_into().unwrap())
79 }
80}
81
82impl IntoType for Function {
83 fn into_type() -> Cow<'static, str> {
84 Cow::Borrowed("function")
85 }
86}