Skip to content

Commit

Permalink
Rename SpecificType and impl serialize/encode
Browse files Browse the repository at this point in the history
  • Loading branch information
olanod committed Oct 28, 2021
1 parent 69b4d62 commit e8f1d1d
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 51 deletions.
4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
[package]
name = "scale-serialization"
description = "SCALE Serialization"
version = "0.7.5"
version = "0.8.0"
authors = ["Daniel Olano <[email protected]>"]
edition = "2018"
repository = "https://github.com/virto-network/scales"
license = "Apache-2.0"

[dependencies]
bytes = { version = "1.1.0", default-features = false }
scale-info = { version = "1.0.0", default-features = false }
scale-info = { version = "1.0.0", default-features = false, features = ["serde"] }
serde = { version = "1.0.130", default-features = false }
serde_json = { version = "1.0.68", default-features = false, optional = true }
codec = { version = "2.3.1", package = "parity-scale-codec", default-features = false, optional = true }
Expand Down
40 changes: 15 additions & 25 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,9 @@ macro_rules! is_tuple {
/// A convenient representation of the scale-info types to a format
/// that matches serde model more closely
#[rustfmt::skip]
#[derive(Debug, Clone)]
pub enum SerdeType {
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "codec", derive(codec::Encode))]
pub enum SpecificType {
Bool,
U8, U16, U32, U64, U128,
I8, I16, I32, I64, I128,
Expand All @@ -58,19 +59,7 @@ pub enum SerdeType {
Variant(String, Vec<Variant>, Option<u8>),
}

// impl From<&mut Type> for SerdeType {
// fn from(ty: &mut Type) -> Self {
// ty.clone().into()
// }
// }

// impl From<&Type> for SerdeType {
// fn from(ty: &Type) -> Self {
// ty.clone().into()
// }
// }

impl From<(&Type, &PortableRegistry)> for SerdeType {
impl From<(&Type, &PortableRegistry)> for SpecificType {
fn from((ty, registry): (&Type, &PortableRegistry)) -> Self {
use scale_info::{TypeDef, TypeDefComposite, TypeDefPrimitive};
type Def = TypeDef<Portable>;
Expand Down Expand Up @@ -160,13 +149,13 @@ impl From<(&Type, &PortableRegistry)> for SerdeType {
}

// Utilities for enum variants
impl SerdeType {
impl SpecificType {
fn pick(&self, index: u8) -> Self {
match self {
SerdeType::Variant(name, variant, Some(_)) => {
SpecificType::Variant(name, variant, Some(_)) => {
Self::Variant(name.to_string(), variant.to_vec(), Some(index))
}
SerdeType::Variant(name, variants, None) => {
SpecificType::Variant(name, variants, None) => {
let v = variants.iter().find(|v| v.index() == index).unwrap();
Self::Variant(name.clone(), vec![v.clone()], Some(index))
}
Expand All @@ -182,8 +171,8 @@ impl SerdeType {
B: AsRef<[u8]> + PartialEq + core::fmt::Debug,
{
match self {
SerdeType::Variant(_, _, Some(_)) => self,
SerdeType::Variant(_, ref mut variants, idx @ None) => {
SpecificType::Variant(_, _, Some(_)) => self,
SpecificType::Variant(_, ref mut variants, idx @ None) => {
let i = variants
.iter()
.map(|v| get_field(v))
Expand All @@ -200,7 +189,7 @@ impl SerdeType {
#[cfg(feature = "experimental-serializer")]
fn variant_id(&self) -> u8 {
match self {
SerdeType::Variant(_, _, Some(id)) => *id,
SpecificType::Variant(_, _, Some(id)) => *id,
_ => panic!("Only for enum variants"),
}
}
Expand All @@ -216,10 +205,10 @@ enum EnumVariant<'a> {
Struct(u8, &'a str, Vec<(&'a str, TypeId)>),
}

impl<'a> From<&'a SerdeType> for EnumVariant<'a> {
fn from(ty: &'a SerdeType) -> Self {
impl<'a> From<&'a SpecificType> for EnumVariant<'a> {
fn from(ty: &'a SpecificType) -> Self {
match ty {
SerdeType::Variant(name, variants, Some(idx)) => {
SpecificType::Variant(name, variants, Some(idx)) => {
let variant = variants.first().expect("single variant");
let fields = variant.fields();
let vname = variant.name().as_ref();
Expand Down Expand Up @@ -255,7 +244,8 @@ impl<'a> From<&'a SerdeType> for EnumVariant<'a> {
}
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, serde::Serialize)]
#[cfg_attr(feature = "codec", derive(codec::Encode))]
pub enum TupleOrArray {
Array(TypeId, u32),
Tuple(Vec<TypeId>),
Expand Down
44 changes: 22 additions & 22 deletions src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use core::fmt;
use scale_info::{PortableRegistry, TypeInfo};
use serde::{ser, Serialize};

use crate::{EnumVariant, SerdeType, TupleOrArray};
use crate::{EnumVariant, SpecificType, TupleOrArray};

type TypeId = u32;
type Result<T> = core::result::Result<T, Error>;
Expand Down Expand Up @@ -61,7 +61,7 @@ where
/// the output to an equivalent representation given by some type information.
pub struct Serializer<'reg, B> {
out: B,
ty: Option<SerdeType>,
ty: Option<SpecificType>,
registry: Option<&'reg PortableRegistry>,
}

Expand Down Expand Up @@ -121,9 +121,9 @@ where

fn serialize_i64(self, v: i64) -> Result<Self::Ok> {
match self.ty {
Some(SerdeType::I8) => self.serialize_i8(v as i8)?,
Some(SerdeType::I16) => self.serialize_i16(v as i16)?,
Some(SerdeType::I32) => self.serialize_i32(v as i32)?,
Some(SpecificType::I8) => self.serialize_i8(v as i8)?,
Some(SpecificType::I16) => self.serialize_i16(v as i16)?,
Some(SpecificType::I32) => self.serialize_i32(v as i32)?,
_ => {
self.maybe_some()?;
self.out.put_i64_le(v)
Expand Down Expand Up @@ -153,12 +153,12 @@ where
fn serialize_u64(self, v: u64) -> Result<Self::Ok> {
// all numbers in serde_json are the same
match self.ty {
Some(SerdeType::I8) => self.serialize_i8(v as i8)?,
Some(SerdeType::I16) => self.serialize_i16(v as i16)?,
Some(SerdeType::I32) => self.serialize_i32(v as i32)?,
Some(SerdeType::U8) => self.serialize_u8(v as u8)?,
Some(SerdeType::U16) => self.serialize_u16(v as u16)?,
Some(SerdeType::U32) => self.serialize_u32(v as u32)?,
Some(SpecificType::I8) => self.serialize_i8(v as i8)?,
Some(SpecificType::I16) => self.serialize_i16(v as i16)?,
Some(SpecificType::I32) => self.serialize_i32(v as i32)?,
Some(SpecificType::U8) => self.serialize_u8(v as u8)?,
Some(SpecificType::U16) => self.serialize_u16(v as u16)?,
Some(SpecificType::U32) => self.serialize_u32(v as u32)?,
_ => {
self.maybe_some()?;
self.out.put_u64_le(v);
Expand All @@ -181,7 +181,7 @@ where

fn serialize_str(self, v: &str) -> Result<Self::Ok> {
self.maybe_some()?;
if let Some(ref mut var @ SerdeType::Variant(_, _, None)) = &mut self.ty {
if let Some(ref mut var @ SpecificType::Variant(_, _, None)) = &mut self.ty {
var.pick_mut(to_vec(v)?, |k| to_vec(k.name()).unwrap());
self.out.put_u8(var.variant_id());
return Ok(());
Expand Down Expand Up @@ -255,7 +255,7 @@ where

fn serialize_seq(self, len: Option<usize>) -> Result<Self::SerializeSeq> {
self.maybe_some()?;
if matches!(self.ty, None | Some(SerdeType::Sequence(_))) {
if matches!(self.ty, None | Some(SpecificType::Sequence(_))) {
compact_number(len.expect("known length"), &mut self.out);
}
Ok(self.into())
Expand Down Expand Up @@ -289,7 +289,7 @@ where

fn serialize_map(self, len: Option<usize>) -> Result<Self::SerializeMap> {
self.maybe_some()?;
if matches!(self.ty, None | Some(SerdeType::Map(_, _))) {
if matches!(self.ty, None | Some(SpecificType::Map(_, _))) {
compact_number(len.expect("known length"), &mut self.out);
}
Ok(self.into())
Expand Down Expand Up @@ -321,7 +321,7 @@ where
// if the type info says its an Option assume its Some and extract the inner type
fn maybe_some(&mut self) -> Result<()> {
match &self.ty {
Some(SerdeType::Variant(ref name, v, _)) if name == "Option" => {
Some(SpecificType::Variant(ref name, v, _)) if name == "Option" => {
self.ty = v[1].fields().first().map(|f| self.resolve(f.ty().id()));
self.out.put_u8(0x01);
}
Expand All @@ -330,7 +330,7 @@ where
Ok(())
}

fn resolve(&self, ty_id: TypeId) -> SerdeType {
fn resolve(&self, ty_id: TypeId) -> SpecificType {
let reg = self.registry.expect("called heving type");
let ty = reg.resolve(ty_id).expect("in registry");
(ty, reg).into()
Expand All @@ -347,7 +347,7 @@ pub enum TypedSerializer<'a, 'reg, B> {

impl<'a, 'reg, B: 'a> From<&'a mut Serializer<'reg, B>> for TypedSerializer<'a, 'reg, B> {
fn from(ser: &'a mut Serializer<'reg, B>) -> Self {
use SerdeType::*;
use SpecificType::*;
match ser.ty.take() {
Some(Struct(fields)) => {
Self::Composite(ser, fields.iter().map(|(_, ty)| *ty).collect())
Expand Down Expand Up @@ -397,7 +397,7 @@ where
{
match self {
TypedSerializer::Enum(ser) => {
if let Some(ref mut var @ SerdeType::Variant(_, _, None)) = ser.ty {
if let Some(ref mut var @ SpecificType::Variant(_, _, None)) = ser.ty {
let key_data = to_vec(key)?;
// assume the key is the name of the variant
var.pick_mut(key_data, |v| to_vec(v.name()).unwrap())
Expand All @@ -419,13 +419,13 @@ where
TypedSerializer::Composite(ser, types) => {
let mut ty = ser.resolve(types.remove(0));
// serde_json unwraps newtypes
if let SerdeType::StructNewType(ty_id) = ty {
if let SpecificType::StructNewType(ty_id) = ty {
ty = ser.resolve(ty_id)
}
ser.ty = Some(ty);
}
TypedSerializer::Enum(ser) => {
if let Some(var @ SerdeType::Variant(_, _, Some(_))) = &ser.ty {
if let Some(var @ SpecificType::Variant(_, _, Some(_))) = &ser.ty {
if let EnumVariant::NewType(_, _, ty_id) = var.into() {
ser.ty = Some(ser.resolve(ty_id));
}
Expand Down Expand Up @@ -455,15 +455,15 @@ where
match self {
TypedSerializer::Composite(ser, types) => {
let mut ty = ser.resolve(types.remove(0));
if let SerdeType::StructNewType(ty_id) = ty {
if let SpecificType::StructNewType(ty_id) = ty {
ty = ser.resolve(ty_id);
}
ser.ty = Some(ty);
}
TypedSerializer::Sequence(ser, ty_id) => {
let ty = ser.resolve(*ty_id);
ser.ty = Some(match ty {
SerdeType::StructNewType(ty_id) => ser.resolve(ty_id),
SpecificType::StructNewType(ty_id) => ser.resolve(ty_id),
_ => ty,
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/value.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{EnumVariant, SerdeType};
use crate::{EnumVariant, SpecificType};
use alloc::{collections::BTreeMap, vec::Vec};
use bytes::{Buf, Bytes};
use core::{convert::TryInto, str};
Expand Down Expand Up @@ -98,7 +98,7 @@ impl<'a> Serialize for Value<'a> {
let mut data = self.data.clone();
let ty = self.resolve(self.ty_id);

use SerdeType::*;
use SpecificType::*;
match (ty, self.registry).into() {
Bool => ser.serialize_bool(data.get_u8() != 0),
U8 => ser.serialize_u8(data.get_u8()),
Expand Down

0 comments on commit e8f1d1d

Please sign in to comment.