jsonrpsee_core/
id_providers.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27//! Subscription ID providers.
28
29use rand::distributions::Alphanumeric;
30use rand::Rng;
31
32use crate::traits::IdProvider;
33use jsonrpsee_types::SubscriptionId;
34
35/// Generates random integers as subscription ID.
36#[derive(Debug, Copy, Clone)]
37pub struct RandomIntegerIdProvider;
38
39impl IdProvider for RandomIntegerIdProvider {
40	fn next_id(&self) -> SubscriptionId<'static> {
41		const JS_NUM_MASK: u64 = !0 >> 11;
42		(rand::random::<u64>() & JS_NUM_MASK).into()
43	}
44}
45
46/// Generates random strings of length `len` as subscription ID.
47#[derive(Debug, Copy, Clone)]
48pub struct RandomStringIdProvider {
49	len: usize,
50}
51
52impl RandomStringIdProvider {
53	/// Create a new random string provider.
54	pub fn new(len: usize) -> Self {
55		Self { len }
56	}
57}
58
59impl IdProvider for RandomStringIdProvider {
60	fn next_id(&self) -> SubscriptionId<'static> {
61		let mut rng = rand::thread_rng();
62		(&mut rng).sample_iter(Alphanumeric).take(self.len).map(char::from).collect::<String>().into()
63	}
64}
65
66/// No-op implementation to be used for servers that don't support subscriptions.
67#[derive(Debug, Copy, Clone)]
68pub struct NoopIdProvider;
69
70impl IdProvider for NoopIdProvider {
71	fn next_id(&self) -> SubscriptionId<'static> {
72		0.into()
73	}
74}