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
// Copyright (C) 2020 Stephane Raux. Distributed under the zlib license.

//! # Overview
//! - [📦 crates.io](https://crates.io/crates/serde-scale-wrap)
//! - [📖 Documentation](https://docs.rs/serde-scale-wrap)
//! - [⚖ zlib license](https://opensource.org/licenses/Zlib)
//!
//! Wrapper for types implementing [`Serialize`/`Deserialize`](https://docs.rs/serde) to implement
//! [`Encode`/`Decode`](https://docs.rs/parity-scale-codec) automatically.
//!
//! ⚠ The `Error` type exposed by this crate is meant to disappear if/when `parity-scale-codec`'s
//! `Error` implements `Display` unconditionally.
//!
//! # Example
//! ```rust
//! extern crate alloc;
//!
//! use alloc::string::String;
//! use parity_scale_codec::{Decode, Encode};
//! use serde::{Deserialize, Serialize};
//! use serde_scale_wrap::Wrap;
//!
//! #[derive(Debug, Deserialize, PartialEq, Serialize)]
//! struct Foo {
//!     x: i32,
//!     s: String,
//! }
//!
//! let original = Foo { x: 3, s: "foo".into() };
//! let serialized = Wrap(&original).encode();
//! let Wrap(deserialized) = Wrap::<Foo>::decode(&mut &*serialized).unwrap();
//! assert_eq!(original, deserialized);
//! ```
//!
//! # Conformance
//! ⚠ `Option<bool>` is serialized as a single byte according to the SCALE encoding, which differs
//! from the result of `Encode::encode` -- `Encode` expects `OptionBool` to be used instead.
//!
//! # Features
//! `no_std` is supported by disabling default features.
//!
//! - `std`: Support for `std`. It is enabled by default.
//!
//! # Contribute
//! All contributions shall be licensed under the [zlib license](https://opensource.org/licenses/Zlib).
//!
//! # Related projects
//! - [parity-scale-codec](https://crates.io/crates/parity-scale-codec): Reference Rust implementation
//! - [serde-scale](https://crates.io/crates/serde-scale): SCALE encoding with `serde`

#![deny(warnings)]
#![cfg_attr(not(feature = "std"), no_std)]

extern crate alloc;

use alloc::vec::Vec;
use core::{
    convert::Infallible,
    fmt::{self, Display},
};
use parity_scale_codec::{Decode, Encode, EncodeLike, Input, Output};
use serde::{Deserialize, Serialize};
use serde_scale::{Bytes, Read, Write};

/// Wrapper for types serializable with `serde` to support serialization with `Encode`/`Decode`
///
/// This can help to pass instances of types implementing `Serialize`/`Deserialize` to `substrate`
/// functions expecting types implementing `Encode`/`Decode`.
///
/// ⚠ The `Encode` implementation panics if the serializer returns an error (e.g. when attempting
/// to serialize a floating point number) because `Encode` methods do not return `Result`.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Hash, Ord, PartialEq, PartialOrd, Serialize)]
pub struct Wrap<T>(pub T);

impl<T: Serialize> Encode for Wrap<T> {
    /// # Panics
    /// Panics if the serializer returns an error (e.g. when attempting to serialize a floating
    /// point number).
    fn encode_to<O: Output>(&self, dst: &mut O) {
        let mut serializer = serde_scale::Serializer::new(OutputToWrite(dst));
        self.0.serialize(&mut serializer).unwrap();
    }
}

impl<T: Serialize> EncodeLike for Wrap<T> {}

impl<'de, T: Deserialize<'de>> Decode for Wrap<T> {
    fn decode<I: Input>(input: &mut I) -> Result<Self, parity_scale_codec::Error> {
        let mut deserializer = serde_scale::Deserializer::new(InputToRead::new(input));
        match T::deserialize(&mut deserializer) {
            Ok(x) => Ok(Wrap(x)),
            Err(serde_scale::Error::Io(Error(s))) => Err(s.into()),
            Err(_) => Err("Deserialization failed".into()),
        }
    }
}

struct OutputToWrite<'a, O: ?Sized>(&'a mut O);

impl<O: Output + ?Sized> Write for OutputToWrite<'_, O> {
    type Error = Infallible;

    fn write(&mut self, bytes: &[u8]) -> Result<(), Infallible> {
        self.0.write(bytes);
        Ok(())
    }
}

struct InputToRead<'a, I: ?Sized> {
    input: &'a mut I,
    buffer: Vec<u8>,
}

impl<'a, I: Input + ?Sized> InputToRead<'a, I> {
    fn new(input: &'a mut I) -> Self {
        InputToRead {
            input,
            buffer: Vec::new(),
        }
    }
}

impl<'a, 'de, I: Input + ?Sized> Read<'de> for InputToRead<'a, I> {
    type Error = Error;

    fn read_map<R, F>(&mut self, n: usize, f: F) -> Result<R, Self::Error>
    where
        F: FnOnce(Bytes<'de, '_>) -> R,
    {
        self.buffer.resize(n, 0);
        self.input.read(&mut self.buffer).map_err(|e| Error(e.what()))?;
        Ok(f(Bytes::Temporary(&self.buffer)))
    }
}

/// Unstable error type meant to disappear if/when `parity-scale-codec`'s `Error` implements
/// `Display` unconditionally.
#[derive(Debug)]
pub struct Error(pub &'static str);

impl Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.0)
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

#[cfg(test)]
mod tests {
    use alloc::string::String;
    use crate::Wrap;
    use parity_scale_codec::{Decode, Encode};
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Deserialize, PartialEq, Serialize)]
    struct Foo {
        x: i32,
        s: String,
    }

    #[test]
    fn foo_roundtrips() {
        let original = Foo { x: 3, s: "foo".into() };
        let serialized = Wrap(&original).encode();
        let Wrap(deserialized) = Wrap::<Foo>::decode(&mut &*serialized).unwrap();
        assert_eq!(original, deserialized);
    }

    #[test]
    fn foo_is_correctly_serialized() {
        let original = Foo { x: 3, s: "foo".into() };
        let wrapped_serialized = Wrap(&original).encode();
        let serialized = serde_scale::to_vec(&original).unwrap();
        assert_eq!(wrapped_serialized, serialized);
    }
}