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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
use codec::{Compact, Decode, Input};
use serde_json::{json, Map, Value};

use crate::error::*;
use crate::schema::*;
use crate::type_def::*;

#[derive(Clone)]
pub struct TypeCodec {
  type_lookup: TypeLookup,
  ty: Type,
}

impl TypeCodec {
  pub fn new(type_lookup: &TypeLookup, type_ref: TypeRef) -> Option<Self> {
    type_ref.ty.map(|ty| Self {
      type_lookup: type_lookup.clone(),
      ty,
    })
  }

  pub fn decode_value<I: Input>(&self, input: &mut I, is_compact: bool) -> Result<Value> {
    self.ty.decode_value(&self.type_lookup, input, is_compact)
  }

  pub fn decode(&self, data: Vec<u8>) -> Result<Value> {
    self.decode_value(&mut &data[..], false)
  }
}

impl TypeLookup {
  pub fn decode_value<I: Input>(
    &self,
    type_id: TypeId,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    let ty = self
      .get_type(type_id)
      .ok_or_else(|| Error::DecodeTypeFailed(format!("Missing type_id: {type_id:?}")))?;
    if ty.path().is_empty() {
      log::trace!("decode type[{type_id:?}]");
    } else {
      log::trace!("decode type[{type_id:?}]: {}", ty.path());
    }
    ty.decode_value(self, input, is_compact)
  }
}

impl Type {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    if !self.path().is_empty() {
      log::trace!("decode type: {}", self.path());
    }
    self.type_def.decode_value(type_lookup, input, is_compact)
  }
}

impl TypeDef {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    match self {
      TypeDef::Composite(def) => def.decode_value(type_lookup, input, is_compact),
      TypeDef::Variant(def) => def.decode_value(type_lookup, input, is_compact),
      TypeDef::Sequence(def) => def.decode_value(type_lookup, input, is_compact),
      TypeDef::Array(def) => def.decode_value(type_lookup, input, is_compact),
      TypeDef::Tuple(def) => def.decode_value(type_lookup, input, is_compact),
      TypeDef::Primitive(prim) => {
        log::trace!("decode Primitive: {prim:?}, is_compact: {is_compact}");
        match prim {
          TypeDefPrimitive::Bool => match input.read_byte()? {
            0 => Ok(json!(false)),
            1 => Ok(json!(true)),
            num => Err(Error::DecodeTypeFailed(format!(
              "Invalid bool byte: {num:?}"
            ))),
          },
          TypeDefPrimitive::Char => {
            let ch = input.read_byte()? as char;
            Ok(json!(ch))
          }
          TypeDefPrimitive::Str => {
            let s = String::decode(input)?;
            Ok(json!(s))
          }
          TypeDefPrimitive::U8 => {
            let num = u8::decode(input)?;
            Ok(json!(num))
          }
          TypeDefPrimitive::U16 => {
            let num = if is_compact {
              Compact::<u16>::decode(input)?.0
            } else {
              u16::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::U32 => {
            let num = if is_compact {
              Compact::<u32>::decode(input)?.0
            } else {
              u32::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::U64 => {
            let num = if is_compact {
              Compact::<u64>::decode(input)?.0
            } else {
              u64::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::U128 => {
            let num = if is_compact {
              Compact::<u128>::decode(input)?.0
            } else {
              u128::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::U256 => {
            unimplemented!();
          }
          TypeDefPrimitive::I8 => {
            let num = i8::decode(input)?;
            Ok(json!(num))
          }
          TypeDefPrimitive::I16 => {
            let num = if is_compact {
              Compact::<u16>::decode(input)?.0 as i16
            } else {
              i16::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::I32 => {
            let num = if is_compact {
              Compact::<u32>::decode(input)?.0 as i32
            } else {
              i32::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::I64 => {
            let num = if is_compact {
              Compact::<u64>::decode(input)?.0 as i64
            } else {
              i64::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::I128 => {
            let num = if is_compact {
              Compact::<u128>::decode(input)?.0 as i128
            } else {
              i128::decode(input)?
            };
            Ok(json!(num))
          }
          TypeDefPrimitive::I256 => {
            unimplemented!();
          }
        }
      },
      TypeDef::Compact(def) => def.decode_value(type_lookup, input, is_compact),
    }
  }
}

fn decode_fields<I: Input>(
  fields: &Vec<Field>,
  type_lookup: &TypeLookup,
  input: &mut I,
  is_compact: bool,
) -> Result<Value> {
  let len = fields.len();
  if len == 0 {
    return Ok(Value::Null);
  }
  match fields.len() {
    0 => Ok(Value::Null),
    1 if fields[0].name.is_none() => {
      Ok(type_lookup.decode_value(fields[0].ty, input, is_compact)?)
    }
    len => {
      let mut m = Map::with_capacity(len);
      for (idx, field) in fields.iter().enumerate() {
        let name = field
          .name
          .as_ref()
          .cloned()
          .unwrap_or_else(|| format!("{idx}"));
        log::trace!("decode Composite field: {name}");
        m.insert(name, type_lookup.decode_value(field.ty, input, is_compact)?);
      }
      Ok(m.into())
    }
  }
}

impl TypeDefComposite {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    decode_fields(&self.fields, type_lookup, input, is_compact)
  }
}

impl TypeDefVariant {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    let val = input.read_byte()?;
    match self.get_by_idx(val) {
      Some(variant) if variant.fields.len() == 0 => Ok(json!(variant.name)),
      Some(variant) => {
        let mut m = Map::new();
        let name = variant.name.clone();
        m.insert(
          name,
          decode_fields(&variant.fields, type_lookup, input, is_compact)?,
        );
        Ok(m.into())
      }
      None if val == 0 => Ok(Value::Null),
      None => {
        log::debug!(
          "Invalid variant: {}, bytes remaining: {:?}, variants: {:?}",
          val,
          input.remaining_len()?,
          self.variants
        );
        Err(Error::DecodeTypeFailed(format!("Invalid variant: {val}")))
      }
    }
  }
}

impl TypeDefSequence {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    let len = Compact::<u64>::decode(input)?.0 as usize;
    let mut vec = Vec::with_capacity(len.max(256));
    for _ in 0..len {
      vec.push(type_lookup.decode_value(self.type_param, input, is_compact)?);
    }
    Ok(vec.into())
  }
}

impl TypeDefArray {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    let len = self.len as usize;
    let mut vec = Vec::with_capacity(len);
    for _ in 0..len {
      vec.push(type_lookup.decode_value(self.type_param, input, is_compact)?);
    }
    Ok(vec.into())
  }
}

impl TypeDefTuple {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    is_compact: bool,
  ) -> Result<Value> {
    match self.fields.len() {
      0 => Ok(Value::Null),
      1 => Ok(type_lookup.decode_value(self.fields[0], input, is_compact)?),
      len => {
        let mut vec = Vec::with_capacity(len);
        for field in &self.fields {
          vec.push(type_lookup.decode_value(*field, input, is_compact)?);
        }
        Ok(vec.into())
      }
    }
  }
}

impl TypeDefCompact {
  pub fn decode_value<I: Input>(
    &self,
    type_lookup: &TypeLookup,
    input: &mut I,
    _is_compact: bool,
  ) -> Result<Value> {
    type_lookup.decode_value(self.type_param, input, true)
  }
}