sp_rpc/list.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! RPC a lenient list or value type.
19
20use serde::{Deserialize, Serialize};
21
22/// RPC list or value wrapper.
23///
24/// For some RPCs it's convenient to call them with either
25/// a single value or a whole list of values to get a proper response.
26/// In theory you could do a batch query, but it's:
27/// 1. Less convenient in client libraries
28/// 2. If the response value is small, the protocol overhead might be dominant.
29///
30/// Also it's nice to be able to maintain backward compatibility for methods that
31/// were initially taking a value and now we want to expand them to take a list.
32#[derive(Serialize, Deserialize, Debug, PartialEq, Clone)]
33#[serde(untagged)]
34pub enum ListOrValue<T> {
35 /// A list of values of given type.
36 List(Vec<T>),
37 /// A single value of given type.
38 Value(T),
39}
40
41impl<T> ListOrValue<T> {
42 /// Map every contained value using function `F`.
43 ///
44 /// This allows to easily convert all values in any of the variants.
45 pub fn map<F: Fn(T) -> X, X>(self, f: F) -> ListOrValue<X> {
46 match self {
47 ListOrValue::List(v) => ListOrValue::List(v.into_iter().map(f).collect()),
48 ListOrValue::Value(v) => ListOrValue::Value(f(v)),
49 }
50 }
51}
52
53impl<T> From<T> for ListOrValue<T> {
54 fn from(n: T) -> Self {
55 ListOrValue::Value(n)
56 }
57}
58
59impl<T> From<Vec<T>> for ListOrValue<T> {
60 fn from(n: Vec<T>) -> Self {
61 ListOrValue::List(n)
62 }
63}
64
65#[cfg(test)]
66mod tests {
67 use super::*;
68 use crate::assert_deser;
69
70 #[test]
71 fn should_serialize_and_deserialize() {
72 assert_deser(r#"5"#, ListOrValue::Value(5_u64));
73 assert_deser(r#""str""#, ListOrValue::Value("str".to_string()));
74 assert_deser(r#"[1,2,3]"#, ListOrValue::List(vec![1_u64, 2_u64, 3_u64]));
75 }
76}