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
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
pub mod account;
pub mod contract;

use crate::bytesrepr::{Error, FromBytes, ToBytes};
use crate::key::{Key, UREF_SIZE};
use alloc::string::String;
use alloc::vec::Vec;
use core::convert::TryFrom;
use core::iter;

pub use self::account::Account;
pub use self::contract::Contract;

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Value {
    Int32(i32),
    ByteArray(Vec<u8>),
    ListInt32(Vec<i32>),
    String(String),
    ListString(Vec<String>),
    NamedKey(String, Key),
    Account(account::Account),
    Contract(contract::Contract),
}

const INT32_ID: u8 = 0;
const BYTEARRAY_ID: u8 = 1;
const LISTINT32_ID: u8 = 2;
const STRING_ID: u8 = 3;
const ACCT_ID: u8 = 4;
const CONTRACT_ID: u8 = 5;
const NAMEDKEY_ID: u8 = 6;
const LISTSTRING_ID: u8 = 7;

use self::Value::*;

impl ToBytes for Value {
    fn to_bytes(&self) -> Vec<u8> {
        match self {
            Int32(i) => {
                let mut result = Vec::with_capacity(5);
                result.push(INT32_ID);
                result.append(&mut i.to_bytes());
                result
            }
            ByteArray(arr) => {
                let mut result = Vec::with_capacity(5 + arr.len());
                result.push(BYTEARRAY_ID);
                result.append(&mut arr.to_bytes());
                result
            }
            ListInt32(arr) => {
                let mut result = Vec::with_capacity(5 + 4 * arr.len());
                result.push(LISTINT32_ID);
                result.append(&mut arr.to_bytes());
                result
            }
            String(s) => {
                let mut result = Vec::with_capacity(5 + s.len());
                result.push(STRING_ID);
                result.append(&mut s.to_bytes());
                result
            }
            Account(a) => {
                let mut result = Vec::new();
                result.push(ACCT_ID);
                result.append(&mut a.to_bytes());
                result
            }
            Contract(c) => iter::once(CONTRACT_ID).chain(c.to_bytes()).collect(),
            NamedKey(n, k) => {
                let size: usize = 1 + //size for ID
                  4 +                 //size for length of String
                  n.len() +           //size of String
                  UREF_SIZE; //size of urefs
                let mut result = Vec::with_capacity(size);
                result.push(NAMEDKEY_ID);
                result.append(&mut n.to_bytes());
                result.append(&mut k.to_bytes());
                result
            }
            ListString(arr) => {
                let mut result = Vec::with_capacity(5 + arr.len());
                result.push(LISTSTRING_ID);
                result.append(&mut arr.to_bytes());
                result
            }
        }
    }
}
impl FromBytes for Value {
    fn from_bytes(bytes: &[u8]) -> Result<(Self, &[u8]), Error> {
        let (id, rest): (u8, &[u8]) = FromBytes::from_bytes(bytes)?;
        match id {
            INT32_ID => {
                let (i, rem): (i32, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((Int32(i), rem))
            }
            BYTEARRAY_ID => {
                let (arr, rem): (Vec<u8>, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((ByteArray(arr), rem))
            }
            LISTINT32_ID => {
                let (arr, rem): (Vec<i32>, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((ListInt32(arr), rem))
            }
            STRING_ID => {
                let (s, rem): (String, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((String(s), rem))
            }
            ACCT_ID => {
                let (a, rem): (account::Account, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((Account(a), rem))
            }
            CONTRACT_ID => {
                let (c, rem): (contract::Contract, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((Contract(c), rem))
            }
            NAMEDKEY_ID => {
                let (name, rem1): (String, &[u8]) = FromBytes::from_bytes(rest)?;
                let (key, rem2): (Key, &[u8]) = FromBytes::from_bytes(rem1)?;
                Ok((NamedKey(name, key), rem2))
            }
            LISTSTRING_ID => {
                let (arr, rem): (Vec<String>, &[u8]) = FromBytes::from_bytes(rest)?;
                Ok((ListString(arr), rem))
            }
            _ => Err(Error::FormattingError),
        }
    }
}

impl Value {
    pub fn type_string(&self) -> String {
        match self {
            Int32(_) => String::from("Int32"),
            ListInt32(_) => String::from("List[Int32]"),
            String(_) => String::from("String"),
            ByteArray(_) => String::from("ByteArray"),
            Account(_) => String::from("Account"),
            Contract(_) => String::from("Contract"),
            NamedKey(_, _) => String::from("NamedKey"),
            ListString(_) => String::from("List[String]"),
        }
    }

    pub fn as_account(&self) -> &account::Account {
        match self {
            Account(a) => a,
            _ => panic!("Not an account: {:?}", self),
        }
    }
}

macro_rules! from_try_from_impl {
    ($type:ty, $variant:ident) => {
        impl From<$type> for Value {
            fn from(x: $type) -> Self {
                Value::$variant(x)
            }
        }

        impl TryFrom<Value> for $type {
            type Error = ();

            fn try_from(v: Value) -> Result<$type, ()> {
                if let Value::$variant(x) = v {
                    Ok(x)
                } else {
                    Err(())
                }
            }
        }
    };
}

from_try_from_impl!(i32, Int32);
from_try_from_impl!(Vec<u8>, ByteArray);
from_try_from_impl!(Vec<i32>, ListInt32);
from_try_from_impl!(Vec<String>, ListString);
from_try_from_impl!(String, String);
from_try_from_impl!(account::Account, Account);
from_try_from_impl!(contract::Contract, Contract);

impl From<(String, Key)> for Value {
    fn from(tuple: (String, Key)) -> Self {
        Value::NamedKey(tuple.0, tuple.1)
    }
}

impl TryFrom<Value> for (String, Key) {
    type Error = ();
    
    fn try_from(v: Value) -> Result<(String, Key), ()> {
        if let Value::NamedKey(name, key) = v {
            Ok((name, key))
        } else {
            Err(())
        }
    }
}