Skip to content

Commit

Permalink
Fix warnings about use of deprecated methods
Browse files Browse the repository at this point in the history
  • Loading branch information
olanod committed Apr 23, 2024
1 parent 07d0030 commit 401d322
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 81 deletions.
94 changes: 43 additions & 51 deletions scales/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
#![cfg_attr(not(feature = "std"), no_std)]
///!
///! # Scales
///!
///! Dynamic SCALE Serialization using `scale-info` type information.
//!
//! # Scales
//!
//! Dynamic SCALE Serialization using `scale-info` type information.

#[macro_use]
extern crate alloc;

Expand All @@ -23,22 +24,16 @@ use prelude::*;
use scale_info::{form::PortableForm as Portable, PortableRegistry};

mod prelude {
pub use alloc::{
collections::BTreeMap,
string::{String, ToString},
vec::Vec,
};
pub use core::ops::Deref;
}

type Type = scale_info::Type<Portable>;
type Field = scale_info::Field<Portable>;
type Variant = scale_info::Variant<Portable>;
type TypeId = u32;

macro_rules! is_tuple {
($it:ident) => {
$it.fields().first().and_then(Field::name).is_none()
$it.fields.first().and_then(|f| f.name.as_ref()).is_none()
};
}

Expand Down Expand Up @@ -69,69 +64,66 @@ impl From<(&Type, &PortableRegistry)> for SpecificType {

macro_rules! resolve {
($ty:expr) => {
registry.resolve($ty.id()).unwrap()
registry.resolve($ty.id).unwrap()
};
}
let is_map = |ty: &Type| -> bool { ty.path().segments() == ["BTreeMap"] };
let is_map = |ty: &Type| -> bool { ty.path.segments == ["BTreeMap"] };
let map_types = |ty: &TypeDefComposite<Portable>| -> (TypeId, TypeId) {
let field = ty.fields().first().expect("map");
let field = ty.fields.first().expect("map");
// Type information of BTreeMap is weirdly packed
if let Def::Sequence(s) = resolve!(field.ty()).type_def() {
if let Def::Tuple(t) = resolve!(s.type_param()).type_def() {
assert_eq!(t.fields().len(), 2);
let key_ty = t.fields().first().expect("key").id();
let val_ty = t.fields().last().expect("val").id();
if let Def::Sequence(s) = &resolve!(field.ty).type_def {
if let Def::Tuple(t) = &resolve!(s.type_param).type_def {
assert_eq!(t.fields.len(), 2);
let key_ty = t.fields.first().expect("key").id;
let val_ty = t.fields.last().expect("val").id;
return (key_ty, val_ty);
}
}
unreachable!()
};

let name = ty
.path()
.segments()
.path
.segments
.last()
.cloned()
.unwrap_or_else(|| "".into());

match ty.type_def() {
Def::Composite(c) => {
let fields = c.fields();
match ty.type_def {
Def::Composite(ref c) => {
let fields = &c.fields;
if fields.is_empty() {
Self::StructUnit
} else if is_map(ty) {
let (k, v) = map_types(c);
Self::Map(k, v)
} else if fields.len() == 1 && fields.first().unwrap().name().is_none() {
Self::StructNewType(fields.first().unwrap().ty().id())
} else if fields.len() == 1 && fields.first().unwrap().name.is_none() {
Self::StructNewType(fields.first().unwrap().ty.id)
} else if is_tuple!(c) {
Self::StructTuple(fields.iter().map(|f| f.ty().id()).collect())
Self::StructTuple(fields.iter().map(|f| f.ty.id).collect())
} else {
Self::Struct(
fields
.iter()
.map(|f| (f.name().unwrap().deref().into(), f.ty().id()))
.map(|f| (f.name.as_ref().unwrap().deref().into(), f.ty.id))
.collect(),
)
}
}
Def::Variant(v) => Self::Variant(name, v.variants().into(), None),
Def::Sequence(s) => {
let ty = s.type_param();
if matches!(
resolve!(ty).type_def(),
Def::Primitive(TypeDefPrimitive::U8)
) {
Self::Bytes(ty.id())
Def::Variant(ref v) => Self::Variant(name, v.variants.clone(), None),
Def::Sequence(ref s) => {
let ty = s.type_param;
if matches!(resolve!(ty).type_def, Def::Primitive(TypeDefPrimitive::U8)) {
Self::Bytes(ty.id)
} else {
Self::Sequence(ty.id())
Self::Sequence(ty.id)
}
}
Def::Array(a) => Self::Tuple(TupleOrArray::Array(a.type_param().id(), a.len())),
Def::Tuple(t) => Self::Tuple(TupleOrArray::Tuple(
t.fields().iter().map(|ty| ty.id()).collect(),
Def::Array(ref a) => Self::Tuple(TupleOrArray::Array(a.type_param.id, a.len)),
Def::Tuple(ref t) => Self::Tuple(TupleOrArray::Tuple(
t.fields.iter().map(|ty| ty.id).collect(),
)),
Def::Primitive(p) => match p {
Def::Primitive(ref p) => match p {
TypeDefPrimitive::U8 => Self::U8,
TypeDefPrimitive::U16 => Self::U16,
TypeDefPrimitive::U32 => Self::U32,
Expand All @@ -148,8 +140,8 @@ impl From<(&Type, &PortableRegistry)> for SpecificType {
TypeDefPrimitive::U256 => unimplemented!(),
TypeDefPrimitive::I256 => unimplemented!(),
},
Def::Compact(c) => Self::Compact(c.type_param().id()),
Def::BitSequence(_b) => todo!(),
Def::Compact(ref c) => Self::Compact(c.type_param.id),
Def::BitSequence(ref _b) => todo!(),
}
}
}
Expand All @@ -162,7 +154,7 @@ impl SpecificType {
Self::Variant(name.to_string(), variant.to_vec(), Some(index))
}
SpecificType::Variant(name, variants, None) => {
let v = variants.iter().find(|v| v.index() == index).unwrap();
let v = variants.iter().find(|v| v.index == index).unwrap();
Self::Variant(name.clone(), vec![v.clone()], Some(index))
}
_ => panic!("Only for enum variants"),
Expand All @@ -183,7 +175,7 @@ impl SpecificType {
.iter()
.map(get_field)
.position(|f| f.as_ref() == selection.as_ref())? as u8;
variants.retain(|v| v.index() == i);
variants.retain(|v| v.index == i);
*idx = Some(i);
Some(self)
}
Expand Down Expand Up @@ -215,8 +207,8 @@ impl<'a> From<&'a SpecificType> for EnumVariant<'a> {
match ty {
SpecificType::Variant(name, variants, Some(idx)) => {
let variant = variants.first().expect("single variant");
let fields = variant.fields();
let vname = variant.name().as_ref();
let fields = &variant.fields;
let vname = variant.name.as_ref();

if fields.is_empty() {
if name == "Option" && vname == "None" {
Expand All @@ -226,20 +218,20 @@ impl<'a> From<&'a SpecificType> for EnumVariant<'a> {
}
} else if is_tuple!(variant) {
if fields.len() == 1 {
let ty = fields.first().map(|f| f.ty().id()).unwrap();
return if name == "Option" && variant.name() == "Some" {
let ty = fields.first().map(|f| f.ty.id).unwrap();
return if name == "Option" && variant.name == "Some" {
Self::OptionSome(ty)
} else {
Self::NewType(*idx, vname, ty)
};
} else {
let fields = fields.iter().map(|f| f.ty().id()).collect();
let fields = fields.iter().map(|f| f.ty.id).collect();
Self::Tuple(*idx, vname, fields)
}
} else {
let fields = fields
.iter()
.map(|f| (f.name().unwrap().deref(), f.ty().id()))
.map(|f| (f.name.as_deref().unwrap(), f.ty.id))
.collect();
Self::Struct(*idx, vname, fields)
}
Expand Down
26 changes: 13 additions & 13 deletions scales/src/serializer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,13 @@ where
}

#[cfg(feature = "json")]
pub fn to_bytes_from_iter<B, I, K, V>(
pub fn to_bytes_from_iter<B, K, V>(
bytes: B,
iter: I,
iter: impl IntoIterator<Item = (K, V)>,
registry_type: (&PortableRegistry, TypeId),
) -> Result<()>
where
B: BufMut + Debug,
I: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<crate::JsonValue>,
{
Expand All @@ -75,11 +74,11 @@ where
.resolve(registry_type.1)
.ok_or_else(|| Error::BadInput("Type not in registry".into()))?;
let obj = iter.into_iter().collect::<crate::JsonValue>();
let val: crate::JsonValue = if let scale_info::TypeDef::Composite(ty) = ty.type_def() {
ty.fields()
let val: crate::JsonValue = if let scale_info::TypeDef::Composite(ref ty) = ty.type_def {
ty.fields
.iter()
.map(|f| {
let name = f.name().expect("named field");
let name = f.name.as_ref().expect("named field");
Ok((
name.deref(),
obj.get(name)
Expand Down Expand Up @@ -418,7 +417,7 @@ where
fn maybe_some(&mut self) -> Result<()> {
match &self.ty {
Some(SpecificType::Variant(ref name, v, _)) if name == "Option" => {
self.ty = v[1].fields().first().map(|f| self.resolve(f.ty().id()));
self.ty = v[1].fields.first().map(|f| self.resolve(f.ty.id));
self.out.put_u8(0x01);
}
_ => (),
Expand All @@ -438,7 +437,7 @@ where
Some(SpecificType::Str) | None => Ok(None),
// { "foo": "Bar" } => "Bar" might be an enum variant
Some(ref mut var @ SpecificType::Variant(_, _, None)) => {
var.pick_mut(to_vec(val)?, |k| to_vec(k.name()).unwrap())
var.pick_mut(to_vec(val)?, |k| to_vec(&k.name).unwrap())
.ok_or_else(|| Error::BadInput("Invalid variant".into()))?;
self.out.put_u8(var.variant_id());
Ok(Some(()))
Expand Down Expand Up @@ -592,7 +591,7 @@ where
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())
var.pick_mut(key_data, |v| to_vec(&v.name).unwrap())
.ok_or_else(|| Error::BadInput("Invalid variant".into()))?
.variant_id()
.serialize(&mut **ser)?;
Expand Down Expand Up @@ -787,7 +786,7 @@ impl fmt::Display for Error {
Error::Type(ty) => write!(
f,
"Unexpected type: {}",
ty.path().ident().unwrap_or_else(|| "Unknown".into())
ty.path.ident().unwrap_or_else(|| "Unknown".into())
),
Error::NotSupported(from, to) => {
write!(f, "Serializing {} as {} is not supported", from, to)
Expand Down Expand Up @@ -842,6 +841,7 @@ fn type_name_of_val<T: ?Sized>(_val: &T) -> &'static str {
#[cfg(test)]
mod tests {
use super::*;
use alloc::collections::BTreeMap;
use codec::Encode;
use core::mem::size_of;
use scale_info::{meta_type, Registry, TypeInfo};
Expand Down Expand Up @@ -884,7 +884,7 @@ mod tests {

#[test]
fn primitive_u64() -> Result<()> {
const INPUT: u64 = 0xFF_EE_DD_CC__BB_AA_99_88;
const INPUT: u64 = 0xFFEE_DDCC_BBAA_9988;
let mut out = [0u8; size_of::<u64>()];
let expected = INPUT.encode();

Expand All @@ -896,7 +896,7 @@ mod tests {

#[test]
fn primitive_u128() -> Result<()> {
const INPUT: u128 = 0xFF_EE_DD_CC__BB_AA_99_88__77_66_55_44__33_22_11_00;
const INPUT: u128 = 0xFFEE_DDCC_BBAA_9988_7766_5544_3322_1100;
let mut out = [0u8; size_of::<u128>()];
let expected = INPUT.encode();

Expand Down Expand Up @@ -1109,7 +1109,7 @@ mod tests {
{
let mut reg = Registry::new();
let sym = reg.register_type(&meta_type::<T>());
(sym.id(), reg.into())
(sym.id, reg.into())
}

#[test]
Expand Down
34 changes: 17 additions & 17 deletions scales/src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,8 @@ impl<'a> Value<'a> {
}

fn ty_len(&self, data: &[u8], ty: TypeId) -> usize {
match self.resolve(ty).type_def() {
TypeDef::Primitive(p) => match p {
match &self.resolve(ty).type_def {
TypeDef::Primitive(ref p) => match p {
Primitive::U8 => mem::size_of::<u8>(),
Primitive::U16 => mem::size_of::<u16>(),
Primitive::U32 => mem::size_of::<u32>(),
Expand All @@ -60,34 +60,34 @@ impl<'a> Value<'a> {
_ => unimplemented!(),
},
TypeDef::Composite(c) => c
.fields()
.fields
.iter()
.fold(0, |c, f| c + self.ty_len(&data[c..], f.ty().id())),
.fold(0, |c, f| c + self.ty_len(&data[c..], f.ty.id)),
TypeDef::Variant(e) => {
let var = e
.variants()
.variants
.iter()
.find(|v| v.index() == data[0])
.find(|v| v.index == data[0])
.expect("variant");

if var.fields().is_empty() {
if var.fields.is_empty() {
1 // unit variant
} else {
var.fields()
var.fields
.iter()
.fold(1, |c, f| c + self.ty_len(&data[c..], f.ty().id()))
.fold(1, |c, f| c + self.ty_len(&data[c..], f.ty.id))
}
}
TypeDef::Sequence(s) => {
let (len, prefix_size) = sequence_len(data);
let ty_id = s.type_param().id();
let ty_id = s.type_param.id;
(0..len).fold(prefix_size, |c, _| c + self.ty_len(&data[c..], ty_id))
}
TypeDef::Array(a) => a.len().try_into().unwrap(),
TypeDef::Array(a) => a.len.try_into().unwrap(),
TypeDef::Tuple(t) => t
.fields()
.fields
.iter()
.fold(0, |c, f| c + self.ty_len(&data[c..], f.id())),
.fold(0, |c, f| c + self.ty_len(&data[c..], f.id)),
TypeDef::Compact(_) => compact_len(data),
TypeDef::BitSequence(_) => unimplemented!(),
}
Expand Down Expand Up @@ -116,11 +116,11 @@ impl<'a> Serialize for Value<'a> {
I64 => ser.serialize_i64(data.get_i64_le()),
I128 => ser.serialize_i128(data.get_i128_le()),
Compact(ty) => {
let type_def = self
let type_def = &self
.registry
.resolve(ty)
.expect("not found in registry")
.type_def();
.type_def;

use codec::Compact;
match type_def {
Expand Down Expand Up @@ -289,7 +289,7 @@ impl<'reg> core::fmt::Debug for Value<'reg> {
"Value {{ data: {:?}, type({}): {:?} }}",
self.data,
self.ty_id,
self.registry.resolve(self.ty_id).unwrap().type_def()
self.registry.resolve(self.ty_id).unwrap().type_def
)
}
}
Expand Down Expand Up @@ -332,7 +332,7 @@ mod tests {
{
let mut reg = Registry::new();
let sym = reg.register_type(&meta_type::<T>());
(sym.id(), reg.into())
(sym.id, reg.into())
}

#[cfg(feature = "json")]
Expand Down

0 comments on commit 401d322

Please sign in to comment.