Skip to main content

pubnub_util/
encoded_channels_list.rs

1//! Encoded channels list.
2
3use percent_encoding::{utf8_percent_encode, NON_ALPHANUMERIC};
4
5/// Newtype for an encoded list of channels.
6///
7/// Immutable.
8#[derive(Debug, Clone, PartialEq, Eq)]
9pub struct EncodedChannelsList(String);
10
11impl EncodedChannelsList {
12    /// Create a new [`EncodedChannelsList`] from an interator of [`String`]
13    /// values.
14    pub fn from_string_iter<T, I>(iter: I) -> Self
15    where
16        T: AsRef<String>,
17        I: IntoIterator<Item = T>,
18    {
19        Self(
20            iter.into_iter()
21                .map(|channel| {
22                    utf8_percent_encode(channel.as_ref().as_str(), NON_ALPHANUMERIC).to_string()
23                })
24                .collect::<Vec<_>>()
25                .as_slice()
26                .join("%2C"),
27        )
28    }
29}
30
31impl<T: AsRef<String>> From<Vec<T>> for EncodedChannelsList {
32    fn from(vec: Vec<T>) -> Self {
33        Self::from_string_iter(vec.into_iter())
34    }
35}
36
37impl AsRef<str> for EncodedChannelsList {
38    fn as_ref(&self) -> &str {
39        self.0.as_ref()
40    }
41}
42
43impl std::fmt::Display for EncodedChannelsList {
44    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45        f.write_str(self.as_ref())
46    }
47}