momento/cache/messages/data/set/set_remove_elements.rs
1use momento_protos::cache_client::{
2 set_difference_request::{
3 subtrahend::{Set, SubtrahendSet},
4 Difference, Subtrahend,
5 },
6 SetDifferenceRequest,
7};
8
9use crate::{
10 cache::MomentoRequest, utils::prep_request_with_timeout, CacheClient, IntoBytes, MomentoResult,
11};
12
13/// Removes multiple elements from an existing set. If the set is emptied as a result, the set is deleted.
14///
15/// # Arguments
16///
17/// * `cache_name` - The name of the cache containing the set.
18/// * `set_name` - The name of the set to remove elements from.
19/// * `elements` - The elements to remove. Must be able to be converted to a `Vec<u8>`.
20///
21/// # Examples
22/// Assumes that a CacheClient named `cache_client` has been created and is available.
23/// ```
24/// # fn main() -> anyhow::Result<()> {
25/// # use momento::MomentoResult;
26/// # use momento_test_util::create_doctest_cache_client;
27/// # tokio_test::block_on(async {
28/// use momento::cache::SetRemoveElementsRequest;
29/// # let (cache_client, cache_name) = create_doctest_cache_client();
30/// let set_name = "set";
31///
32/// let request = SetRemoveElementsRequest::new(cache_name, set_name, vec!["element1", "element2"]);
33///
34/// match cache_client.send_request(request).await {
35/// Ok(_) => println!("Elements removed from set"),
36/// Err(e) => eprintln!("Error removing elements from set: {}", e),
37/// }
38/// # Ok(())
39/// # })
40/// # }
41/// ```
42pub struct SetRemoveElementsRequest<S: IntoBytes, E: IntoBytes> {
43 cache_name: String,
44 set_name: S,
45 elements: Vec<E>,
46}
47
48impl<S: IntoBytes, E: IntoBytes> SetRemoveElementsRequest<S, E> {
49 /// Constructs a new SetRemoveElementsRequest.
50 pub fn new(cache_name: impl Into<String>, set_name: S, elements: Vec<E>) -> Self {
51 Self {
52 cache_name: cache_name.into(),
53 set_name,
54 elements,
55 }
56 }
57}
58
59impl<S: IntoBytes, E: IntoBytes> MomentoRequest for SetRemoveElementsRequest<S, E> {
60 type Response = SetRemoveElementsResponse;
61
62 async fn send(self, cache_client: &CacheClient) -> MomentoResult<SetRemoveElementsResponse> {
63 let elements = self.elements.into_iter().map(|e| e.into_bytes()).collect();
64 let set_name = self.set_name.into_bytes();
65 let cache_name = &self.cache_name;
66 let request = prep_request_with_timeout(
67 cache_name,
68 cache_client.deadline_millis(),
69 SetDifferenceRequest {
70 set_name,
71 difference: Some(Difference::Subtrahend(Subtrahend {
72 subtrahend_set: Some(SubtrahendSet::Set(Set { elements })),
73 })),
74 },
75 )?;
76
77 let _ = cache_client
78 .next_data_client()
79 .set_difference(request)
80 .await?;
81 Ok(SetRemoveElementsResponse {})
82 }
83}
84
85/// The response type for a successful set remove elements request.
86#[derive(Debug, PartialEq, Eq)]
87pub struct SetRemoveElementsResponse {}