frame_decode/methods/
mod.rs

1// Copyright (C) 2022-2025 Parity Technologies (UK) Ltd. (admin@parity.io)
2// This file is a part of the frame-decode crate.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//         http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16pub mod constant_decoder;
17pub mod constant_type_info;
18pub mod custom_value_decoder;
19pub mod custom_value_type_info;
20pub mod extrinsic_decoder;
21pub mod extrinsic_type_info;
22pub mod runtime_api_decoder;
23pub mod runtime_api_encoder;
24pub mod runtime_api_type_info;
25pub mod storage_decoder;
26pub mod storage_encoder;
27pub mod storage_type_info;
28pub mod view_function_decoder;
29pub mod view_function_encoder;
30pub mod view_function_type_info;
31
32/// This represents either an entry name, or the name of the thing that the entry is
33/// in (for instance the name of a pallet or of a Runtime API trait).
34///
35/// Iterators returning this will iterate containers in order, first returning
36/// [`Entry::In`] to communicate which container (eg pallet or Runtime API trait) is being
37/// iterated over next, and then a [`Entry::Name`]s for the name of each of the entries in
38/// the given container.
39///
40/// A container name will not be handed back more than once.
41#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
42pub enum Entry<In, Name> {
43    /// The name of the thing that the following entries are in/under.
44    In(In),
45    /// The name of the entry in/under the last given [`Entry::In`].
46    Name(Name),
47}
48
49impl<T> Entry<T, T> {
50    /// Map the values in the entry, assuming they are the same.
51    pub fn map<R, F: FnOnce(T) -> R>(self, f: F) -> Entry<R, R> {
52        match self {
53            Entry::In(t) => Entry::In(f(t)),
54            Entry::Name(t) => Entry::Name(f(t)),
55        }
56    }
57}
58
59impl<In, Name> Entry<In, Name> {
60    /// Iterate over all of the entries in a specific container (ie all of the entries
61    /// which follow a specific [`Entry::In`]).
62    pub fn entries_in(
63        entries: impl Iterator<Item = Entry<In, Name>>,
64        container: impl PartialEq<In>,
65    ) -> impl Iterator<Item = Name>
66    where
67        In: PartialEq,
68        Name: PartialEq,
69    {
70        entries
71            .skip_while(move |c| !matches!(c, Entry::In(c) if &container == c))
72            .skip(1)
73            .take_while(|c| matches!(c, Entry::Name(_)))
74            .filter_map(|c| match c {
75                Entry::In(_) => None,
76                Entry::Name(name) => Some(name),
77            })
78    }
79
80    /// Iterate over all of the entries, returning tuples of `(entry_in, entry_name)`.
81    /// This can be easier to work with in some cases.
82    pub fn tuples_of(
83        entries: impl Iterator<Item = Entry<In, Name>>,
84    ) -> impl Iterator<Item = (In, Name)>
85    where
86        In: Clone,
87    {
88        let mut entry_in = None;
89        entries.filter_map(move |entry| match entry {
90            Entry::In(e_in) => {
91                entry_in = Some(e_in);
92                None
93            }
94            Entry::Name(e_name) => {
95                let e_in = entry_in.as_ref().unwrap().clone();
96                Some((e_in, e_name))
97            }
98        })
99    }
100}
101
102#[cfg(test)]
103mod test {
104    use super::*;
105
106    #[test]
107    fn test_entries_in() {
108        fn entries() -> impl Iterator<Item = Entry<&'static str, &'static str>> {
109            [
110                Entry::In("Baz"),
111                Entry::In("Foo"),
112                Entry::Name("foo_a"),
113                Entry::Name("foo_b"),
114                Entry::Name("foo_c"),
115                Entry::In("Bar"),
116                Entry::Name("bar_a"),
117                Entry::In("Wibble"),
118            ]
119            .into_iter()
120        }
121
122        assert!(Entry::entries_in(entries(), "Baz").next().is_none());
123        assert!(Entry::entries_in(entries(), "Wibble").next().is_none());
124
125        let foos: Vec<String> = Entry::entries_in(entries(), "Foo")
126            .map(|s| s.to_owned())
127            .collect();
128        assert_eq!(
129            foos,
130            Vec::from_iter(["foo_a".to_owned(), "foo_b".to_owned(), "foo_c".to_owned(),])
131        );
132
133        let bars: Vec<String> = Entry::entries_in(entries(), "Bar")
134            .map(|s| s.to_owned())
135            .collect();
136        assert_eq!(bars, Vec::from_iter(["bar_a".to_owned(),]));
137    }
138}