1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
use frame_support::traits::Get;
18
use parity_scale_codec::{Decode, Encode};
19
use scale_info::TypeInfo;
20
#[cfg(feature = "std")]
21
use serde::{Deserialize, Serialize};
22
use sp_runtime::{BoundedVec, RuntimeDebug};
23
use sp_std::prelude::*;
24

            
25
/// An ordered set backed by `Vec`
26
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
27
20
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Default, Clone, TypeInfo)]
28
pub struct OrderedSet<T>(pub Vec<T>);
29

            
30
impl<T: Ord> OrderedSet<T> {
31
	/// Create a new empty set
32
	pub fn new() -> Self {
33
		Self(Vec::new())
34
	}
35

            
36
	/// Create a set from a `Vec`.
37
	/// `v` will be sorted and dedup first.
38
9052
	pub fn from(mut v: Vec<T>) -> Self {
39
9052
		v.sort();
40
9052
		v.dedup();
41
9052
		Self::from_sorted_set(v)
42
9052
	}
43

            
44
	/// Create a set from a `Vec`.
45
	/// Assume `v` is sorted and contain unique elements.
46
9052
	pub fn from_sorted_set(v: Vec<T>) -> Self {
47
9052
		Self(v)
48
9052
	}
49

            
50
	/// Insert an element.
51
	/// Return true if insertion happened.
52
65
	pub fn insert(&mut self, value: T) -> bool {
53
65
		match self.0.binary_search(&value) {
54
2
			Ok(_) => false,
55
63
			Err(loc) => {
56
63
				self.0.insert(loc, value);
57
63
				true
58
			}
59
		}
60
65
	}
61

            
62
	/// Remove an element.
63
	/// Return true if removal happened.
64
	pub fn remove(&mut self, value: &T) -> bool {
65
		match self.0.binary_search(value) {
66
			Ok(loc) => {
67
				self.0.remove(loc);
68
				true
69
			}
70
			Err(_) => false,
71
		}
72
	}
73

            
74
	/// Return if the set contains `value`
75
	pub fn contains(&self, value: &T) -> bool {
76
		self.0.binary_search(value).is_ok()
77
	}
78

            
79
	/// Clear the set
80
	pub fn clear(&mut self) {
81
		self.0.clear();
82
	}
83
}
84

            
85
impl<T: Ord> From<Vec<T>> for OrderedSet<T> {
86
	fn from(v: Vec<T>) -> Self {
87
		Self::from(v)
88
	}
89
}
90

            
91
/// An ordered set backed by `BoundedVec`
92
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
93
20
#[derive(RuntimeDebug, PartialEq, Eq, Encode, Decode, Clone, TypeInfo)]
94
#[scale_info(skip_type_params(S))]
95
pub struct BoundedOrderedSet<T, S: Get<u32>>(pub BoundedVec<T, S>);
96

            
97
impl<T, S: Get<u32>> sp_std::default::Default for BoundedOrderedSet<T, S> {
98
573
	fn default() -> Self {
99
573
		BoundedOrderedSet(BoundedVec::default())
100
573
	}
101
}
102

            
103
impl<T: Ord, S: Get<u32>> BoundedOrderedSet<T, S> {
104
	/// Create a new empty set
105
	pub fn new() -> Self {
106
		Self(BoundedVec::default())
107
	}
108

            
109
	/// Create a set from a `Vec`.
110
	/// `v` will be sorted and dedup first.
111
	pub fn from(mut v: BoundedVec<T, S>) -> Self {
112
		v.sort();
113
		let v = v.try_mutate(|inner| inner.dedup()).expect(
114
			"input is a valid BoundedVec and deduping can only reduce the number of entires; qed",
115
		);
116
		Self::from_sorted_set(v)
117
	}
118

            
119
	/// Create a set from a `Vec`.
120
	/// Assume `v` is sorted and contain unique elements.
121
	pub fn from_sorted_set(v: BoundedVec<T, S>) -> Self {
122
		Self(v)
123
	}
124

            
125
	/// Insert an element.
126
	/// Return true if insertion happened.
127
1179
	pub fn try_insert(&mut self, value: T) -> Result<bool, ()> {
128
1179
		match self.0.binary_search(&value) {
129
			Ok(_) => Ok(false),
130
1179
			Err(loc) => self.0.try_insert(loc, value).map(|_| true).map_err(|_| ()),
131
		}
132
1179
	}
133

            
134
	/// Remove an element.
135
	/// Return true if removal happened.
136
568
	pub fn remove(&mut self, value: &T) -> bool {
137
568
		match self.0.binary_search(value) {
138
568
			Ok(loc) => {
139
568
				self.0.remove(loc);
140
568
				true
141
			}
142
			Err(_) => false,
143
		}
144
568
	}
145

            
146
	/// Return if the set contains `value`
147
	pub fn contains(&self, value: &T) -> bool {
148
		self.0.binary_search(value).is_ok()
149
	}
150

            
151
	/// Clear the set
152
	pub fn clear(mut self) {
153
		let v = self.0.try_mutate(|inner| inner.clear()).expect(
154
			"input is a valid BoundedVec and clearing can only reduce the number of entires; qed",
155
		);
156
		self.0 = v;
157
	}
158
}
159

            
160
impl<T: Ord, S: Get<u32>> From<BoundedVec<T, S>> for BoundedOrderedSet<T, S> {
161
	fn from(v: BoundedVec<T, S>) -> Self {
162
		Self::from(v)
163
	}
164
}