set.rs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928
  1. //! # Set command handlers
  2. use crate::{connection::Connection, error::Error, value::bytes_to_number, value::Value};
  3. use bytes::Bytes;
  4. use rand::Rng;
  5. use std::{
  6. cmp::min,
  7. collections::{HashSet, VecDeque},
  8. };
  9. fn store_key_values(conn: &Connection, key: Bytes, values: Vec<Value>) -> i64 {
  10. #[allow(clippy::mutable_key_type)]
  11. let mut x = HashSet::new();
  12. let mut len = 0;
  13. for val in values.into_iter() {
  14. if let Value::Blob(blob) = val {
  15. if x.insert(blob) {
  16. len += 1;
  17. }
  18. }
  19. }
  20. conn.db().set(key, x.into(), None);
  21. len
  22. }
  23. async fn compare_sets<F1>(
  24. conn: &Connection,
  25. mut keys: VecDeque<Bytes>,
  26. op: F1,
  27. ) -> Result<Value, Error>
  28. where
  29. F1: Fn(&mut HashSet<Bytes>, &HashSet<Bytes>) -> bool,
  30. {
  31. let top_key = keys.pop_front().ok_or(Error::Syntax)?;
  32. conn.db()
  33. .get(&top_key)
  34. .map(|v| match v {
  35. Value::Set(x) => {
  36. #[allow(clippy::mutable_key_type)]
  37. let mut all_entries = x.clone();
  38. for key in keys.iter() {
  39. let mut do_break = false;
  40. let mut found = false;
  41. let _ = conn
  42. .db()
  43. .get(key)
  44. .map(|v| match v {
  45. Value::Set(x) => {
  46. found = true;
  47. if !op(&mut all_entries, x) {
  48. do_break = true;
  49. }
  50. Ok(Value::Null)
  51. }
  52. _ => Err(Error::WrongType),
  53. })
  54. .unwrap_or(Ok(Value::Null))?;
  55. if !found && !op(&mut all_entries, &HashSet::new()) {
  56. break;
  57. }
  58. if do_break {
  59. break;
  60. }
  61. }
  62. Ok(all_entries
  63. .iter()
  64. .map(|entry| Value::new(entry))
  65. .collect::<Vec<Value>>()
  66. .into())
  67. }
  68. _ => Err(Error::WrongType),
  69. })
  70. .unwrap_or_else(|| {
  71. #[allow(clippy::mutable_key_type)]
  72. let mut all_entries: HashSet<Bytes> = HashSet::new();
  73. for key in keys.iter() {
  74. let mut do_break = false;
  75. let _ = conn
  76. .db()
  77. .get(key)
  78. .map(|v| match v {
  79. Value::Set(x) => {
  80. if !op(&mut all_entries, x) {
  81. do_break = true;
  82. }
  83. Ok(Value::Null)
  84. }
  85. _ => Err(Error::WrongType),
  86. })
  87. .unwrap_or(Ok(Value::Null))?;
  88. if do_break {
  89. break;
  90. }
  91. }
  92. Ok(all_entries
  93. .iter()
  94. .map(|entry| Value::new(entry))
  95. .collect::<Vec<Value>>()
  96. .into())
  97. })
  98. }
  99. /// Add the specified members to the set stored at key. Specified members that are already a member
  100. /// of this set are ignored. If key does not exist, a new set is created before adding the
  101. /// specified members.
  102. pub async fn sadd(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  103. let key = args.pop_front().ok_or(Error::Syntax)?;
  104. let key_for_not_found = key.clone();
  105. let result = conn
  106. .db()
  107. .get(&key)
  108. .map_mut(|v| match v {
  109. Value::Set(x) => {
  110. let mut len = 0;
  111. for val in args.clone().into_iter() {
  112. if x.insert(val) {
  113. len += 1;
  114. }
  115. }
  116. Ok(len.into())
  117. }
  118. _ => Err(Error::WrongType),
  119. })
  120. .unwrap_or_else(|| {
  121. #[allow(clippy::mutable_key_type)]
  122. let mut x = HashSet::new();
  123. let mut len = 0;
  124. for val in args.into_iter() {
  125. if x.insert(val) {
  126. len += 1;
  127. }
  128. }
  129. conn.db().set(key_for_not_found, x.into(), None);
  130. Ok(len.into())
  131. })?;
  132. conn.db().bump_version(&key);
  133. Ok(result)
  134. }
  135. /// Returns the set cardinality (number of elements) of the set stored at key.
  136. pub async fn scard(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  137. conn.db()
  138. .get(&args[0])
  139. .map(|v| match v {
  140. Value::Set(x) => Ok(x.len().into()),
  141. _ => Err(Error::WrongType),
  142. })
  143. .unwrap_or(Ok(0.into()))
  144. }
  145. /// Returns the members of the set resulting from the difference between the first set and all the
  146. /// successive sets.
  147. ///
  148. /// Keys that do not exist are considered to be empty sets.
  149. pub async fn sdiff(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  150. compare_sets(conn, args, |all_entries, elements| {
  151. for element in elements.iter() {
  152. if all_entries.contains(element) {
  153. all_entries.remove(element);
  154. }
  155. }
  156. true
  157. })
  158. .await
  159. }
  160. /// This command is equal to SDIFF, but instead of returning the resulting set, it is stored in
  161. /// destination.
  162. ///
  163. /// If destination already exists, it is overwritten.
  164. pub async fn sdiffstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  165. let key_name = args.pop_front().ok_or(Error::Syntax)?;
  166. if let Value::Array(values) = sdiff(conn, args).await? {
  167. if !values.is_empty() {
  168. Ok(store_key_values(conn, key_name, values).into())
  169. } else {
  170. let _ = conn.db().del(&[key_name]);
  171. Ok(0.into())
  172. }
  173. } else {
  174. Ok(0.into())
  175. }
  176. }
  177. /// Returns the members of the set resulting from the intersection of all the given sets.
  178. ///
  179. /// Keys that do not exist are considered to be empty sets. With one of the keys being an empty
  180. /// set, the resulting set is also empty (since set intersection with an empty set always results
  181. /// in an empty set).
  182. pub async fn sinter(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  183. compare_sets(conn, args, |all_entries, elements| {
  184. all_entries.retain(|element| elements.contains(element));
  185. for element in elements.iter() {
  186. if !all_entries.contains(element) {
  187. all_entries.remove(element);
  188. }
  189. }
  190. !all_entries.is_empty()
  191. })
  192. .await
  193. }
  194. /// This command is similar to SINTER, but instead of returning the result set, it returns just the
  195. /// cardinality of the result. Returns the cardinality of the set which would result from the
  196. /// intersection of all the given sets.
  197. ///
  198. /// Keys that do not exist are considered to be empty sets. With one of the keys being an empty
  199. /// set, the resulting set is also empty (since set intersection with an empty set always results
  200. /// in an empty set).
  201. pub async fn sintercard(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  202. if let Ok(Value::Array(x)) = sinter(conn, args).await {
  203. Ok(x.len().into())
  204. } else {
  205. Ok(0.into())
  206. }
  207. }
  208. /// This command is equal to SINTER, but instead of returning the resulting set, it is stored in
  209. /// destination.
  210. ///
  211. /// If destination already exists, it is overwritten.
  212. pub async fn sinterstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  213. let key_name = args.pop_front().ok_or(Error::Syntax)?;
  214. if let Value::Array(values) = sinter(conn, args).await? {
  215. if !values.is_empty() {
  216. Ok(store_key_values(conn, key_name, values).into())
  217. } else {
  218. let _ = conn.db().del(&[key_name]);
  219. Ok(0.into())
  220. }
  221. } else {
  222. Ok(0.into())
  223. }
  224. }
  225. /// Returns if member is a member of the set stored at key.
  226. pub async fn sismember(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  227. conn.db()
  228. .get(&args[0])
  229. .map(|v| match v {
  230. Value::Set(x) => {
  231. if x.contains(&args[1]) {
  232. Ok(1.into())
  233. } else {
  234. Ok(0.into())
  235. }
  236. }
  237. _ => Err(Error::WrongType),
  238. })
  239. .unwrap_or(Ok(0.into()))
  240. }
  241. /// Returns all the members of the set value stored at key.
  242. ///
  243. /// This has the same effect as running SINTER with one argument key.
  244. pub async fn smembers(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  245. conn.db()
  246. .get(&args[0])
  247. .map(|v| match v {
  248. Value::Set(x) => Ok(x
  249. .iter()
  250. .map(|x| Value::new(x))
  251. .collect::<Vec<Value>>()
  252. .into()),
  253. _ => Err(Error::WrongType),
  254. })
  255. .unwrap_or(Ok(Value::Array(vec![])))
  256. }
  257. /// Returns whether each member is a member of the set stored at key.
  258. ///
  259. /// For every member, 1 is returned if the value is a member of the set, or 0 if the element is not
  260. /// a member of the set or if key does not exist.
  261. pub async fn smismember(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  262. let key = args.pop_front().ok_or(Error::Syntax)?;
  263. conn.db()
  264. .get(&key)
  265. .map(|v| match v {
  266. Value::Set(x) => Ok(args
  267. .iter()
  268. .map(|member| if x.contains(member) { 1 } else { 0 })
  269. .collect::<Vec<i32>>()
  270. .into()),
  271. _ => Err(Error::WrongType),
  272. })
  273. .unwrap_or_else(|| Ok(args.iter().map(|_| 0.into()).collect::<Vec<Value>>().into()))
  274. }
  275. /// Move member from the set at source to the set at destination. This operation is atomic. In
  276. /// every given moment the element will appear to be a member of source or destination for other
  277. /// clients.
  278. ///
  279. /// If the source set does not exist or does not contain the specified element, no operation is
  280. /// performed and 0 is returned. Otherwise, the element is removed from the source set and added to
  281. /// the destination set. When the specified element already exists in the destination set, it is
  282. /// only removed from the source set.
  283. ///
  284. /// TODO: FIXME: This implementation is flaky. It should be rewritten to use a new db
  285. /// method that allows to return multiple keys, even if they are stored in the
  286. /// same bucked. Right now, this can block a connection
  287. pub async fn smove(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  288. let source = args.pop_front().ok_or(Error::Syntax)?;
  289. let destination = args.pop_front().ok_or(Error::Syntax)?;
  290. let member = args.pop_front().ok_or(Error::Syntax)?;
  291. let mut to_insert = None;
  292. let result = conn
  293. .db()
  294. .get(&source)
  295. .map_mut(|v| match v {
  296. Value::Set(set1) => {
  297. if source == destination {
  298. return Ok(if set1.contains(&member) { 1 } else { 0 }.into());
  299. }
  300. conn.db()
  301. .get(&destination)
  302. .map_mut(|v| match v {
  303. Value::Set(set2) => {
  304. if !set1.contains(&member) {
  305. return Ok(0.into());
  306. }
  307. set1.remove(&member);
  308. if set2.insert(member.clone()) {
  309. Ok(1.into())
  310. } else {
  311. conn.db().bump_version(&source);
  312. Ok(0.into())
  313. }
  314. }
  315. _ => Err(Error::WrongType),
  316. })
  317. .unwrap_or_else(|| {
  318. set1.remove(&member);
  319. let mut x = HashSet::new();
  320. x.insert(member.clone());
  321. to_insert = Some(x);
  322. Ok(1.into())
  323. })
  324. }
  325. _ => Err(Error::WrongType),
  326. })
  327. .unwrap_or(Ok(0.into()))?;
  328. if let Some(x) = to_insert {
  329. conn.db().set(destination.clone(), x.into(), None);
  330. }
  331. if let Value::Integer(1) = result {
  332. conn.db().bump_version(&source);
  333. conn.db().bump_version(&destination);
  334. }
  335. Ok(result)
  336. }
  337. /// Removes and returns one or more random members from the set value store at key.
  338. ///
  339. /// This operation is similar to SRANDMEMBER, that returns one or more random elements from a set
  340. /// but does not remove it.
  341. ///
  342. /// By default, the command pops a single member from the set. When provided with the optional
  343. /// count argument, the reply will consist of up to count members, depending on the set's
  344. /// cardinality.
  345. pub async fn spop(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  346. let rand = srandmember(conn, args.clone()).await?;
  347. let key = args.pop_front().ok_or(Error::Syntax)?;
  348. let mut should_remove = false;
  349. let result = conn
  350. .db()
  351. .get(&key)
  352. .map_mut(|v| match v {
  353. Value::Set(x) => {
  354. match &rand {
  355. Value::Blob(value) => {
  356. x.remove(value.as_ref());
  357. }
  358. Value::Array(values) => {
  359. for value in values.iter() {
  360. if let Value::Blob(value) = value {
  361. x.remove(value.as_ref());
  362. }
  363. }
  364. }
  365. _ => unreachable!(),
  366. };
  367. should_remove = x.is_empty();
  368. Ok(rand)
  369. }
  370. _ => Err(Error::WrongType),
  371. })
  372. .unwrap_or(Ok(Value::Null))?;
  373. if should_remove {
  374. let _ = conn.db().del(&[key]);
  375. } else {
  376. conn.db().bump_version(&key);
  377. }
  378. Ok(result)
  379. }
  380. /// When called with just the key argument, return a random element from the set value stored at
  381. /// key.
  382. ///
  383. /// If the provided count argument is positive, return an array of distinct elements. The array's
  384. /// length is either count or the set's cardinality (SCARD), whichever is lower.
  385. ///
  386. /// If called with a negative count, the behavior changes and the command is allowed to return the
  387. /// same element multiple times. In this case, the number of returned elements is the absolute
  388. /// value of the specified count.
  389. pub async fn srandmember(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  390. conn.db()
  391. .get(&args[0])
  392. .map(|v| match v {
  393. Value::Set(set) => {
  394. let mut rng = rand::thread_rng();
  395. let mut items = set
  396. .iter()
  397. .map(|x| (x, rng.gen()))
  398. .collect::<Vec<(&Bytes, i128)>>();
  399. items.sort_by(|a, b| a.1.cmp(&b.1));
  400. if args.len() == 1 {
  401. // Two arguments provided, return the first element or null if the array is null
  402. if items.is_empty() {
  403. Ok(Value::Null)
  404. } else {
  405. let item = items[0].0.clone();
  406. Ok(Value::new(&item))
  407. }
  408. } else {
  409. if items.is_empty() {
  410. return Ok(Value::Array(vec![]));
  411. }
  412. let len = bytes_to_number::<i64>(&args[1])?;
  413. if len > 0 {
  414. // required length is positive, return *up* to the requested number and no duplicated allowed
  415. let len: usize = min(items.len(), len as usize);
  416. Ok(items[0..len]
  417. .iter()
  418. .map(|item| Value::new(item.0))
  419. .collect::<Vec<Value>>()
  420. .into())
  421. } else {
  422. // duplicated results are allowed and the requested number must be returned
  423. let len = -len as usize;
  424. let total = items.len() - 1;
  425. let mut i = 0;
  426. let items = (0..len)
  427. .map(|_| {
  428. let r = (items[i].0, rng.gen());
  429. i = if i >= total { 0 } else { i + 1 };
  430. r
  431. })
  432. .collect::<Vec<(&Bytes, i128)>>();
  433. Ok(items
  434. .iter()
  435. .map(|item| Value::new(item.0))
  436. .collect::<Vec<Value>>()
  437. .into())
  438. }
  439. }
  440. }
  441. _ => Err(Error::WrongType),
  442. })
  443. .unwrap_or(Ok(if args.len() == 1 {
  444. Value::Null
  445. } else {
  446. Value::Array(vec![])
  447. }))
  448. }
  449. /// Remove the specified members from the set stored at key. Specified members that are not a
  450. /// member of this set are ignored. If key does not exist, it is treated as an empty set and this
  451. /// command returns 0.
  452. pub async fn srem(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  453. let key = args.pop_front().ok_or(Error::Syntax)?;
  454. let result = conn
  455. .db()
  456. .get(&key)
  457. .map_mut(|v| match v {
  458. Value::Set(set) => {
  459. let mut i = 0;
  460. args.into_iter().for_each(|value| {
  461. if set.remove(&value) {
  462. i += 1;
  463. }
  464. });
  465. Ok(i.into())
  466. }
  467. _ => Err(Error::WrongType),
  468. })
  469. .unwrap_or(Ok(0.into()))?;
  470. conn.db().bump_version(&key);
  471. Ok(result)
  472. }
  473. /// Returns the members of the set resulting from the union of all the given sets.
  474. pub async fn sunion(conn: &Connection, args: VecDeque<Bytes>) -> Result<Value, Error> {
  475. compare_sets(conn, args, |all_entries, elements| {
  476. for element in elements.iter() {
  477. all_entries.insert(element.clone());
  478. }
  479. true
  480. })
  481. .await
  482. }
  483. /// This command is equal to SUNION, but instead of returning the resulting set, it is stored in
  484. /// destination.
  485. ///
  486. /// If destination already exists, it is overwritten.
  487. pub async fn sunionstore(conn: &Connection, mut args: VecDeque<Bytes>) -> Result<Value, Error> {
  488. let key_name = args.pop_front().ok_or(Error::Syntax)?;
  489. if let Value::Array(values) = sunion(conn, args).await? {
  490. if !values.is_empty() {
  491. Ok(store_key_values(conn, key_name, values).into())
  492. } else {
  493. let _ = conn.db().del(&[key_name]);
  494. Ok(0.into())
  495. }
  496. } else {
  497. Ok(0.into())
  498. }
  499. }
  500. #[cfg(test)]
  501. mod test {
  502. use crate::{
  503. cmd::test::{create_connection, run_command},
  504. error::Error,
  505. value::Value,
  506. };
  507. #[tokio::test]
  508. async fn test_set_wrong_type() {
  509. let c = create_connection();
  510. let _ = run_command(&c, &["set", "foo", "1"]).await;
  511. assert_eq!(
  512. Err(Error::WrongType),
  513. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "5"]).await,
  514. );
  515. }
  516. #[tokio::test]
  517. async fn sadd() {
  518. let c = create_connection();
  519. assert_eq!(
  520. Ok(Value::Integer(5)),
  521. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "5"]).await,
  522. );
  523. assert_eq!(
  524. Ok(Value::Integer(1)),
  525. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "6"]).await,
  526. );
  527. }
  528. #[tokio::test]
  529. async fn scard() {
  530. let c = create_connection();
  531. assert_eq!(
  532. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "5"]).await,
  533. run_command(&c, &["scard", "foo"]).await
  534. );
  535. }
  536. #[tokio::test]
  537. async fn sdiff() {
  538. let c = create_connection();
  539. assert_eq!(
  540. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  541. run_command(&c, &["scard", "1"]).await
  542. );
  543. assert_eq!(
  544. run_command(&c, &["sadd", "2", "c"]).await,
  545. run_command(&c, &["scard", "2"]).await
  546. );
  547. assert_eq!(
  548. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  549. run_command(&c, &["scard", "3"]).await
  550. );
  551. match run_command(&c, &["sdiff", "1", "2", "3"]).await {
  552. Ok(Value::Array(v)) => {
  553. assert_eq!(2, v.len());
  554. if v[0] == Value::Blob("b".into()) {
  555. assert_eq!(v[1], Value::Blob("d".into()));
  556. } else {
  557. assert_eq!(v[1], Value::Blob("b".into()));
  558. }
  559. }
  560. _ => unreachable!(),
  561. };
  562. }
  563. #[tokio::test]
  564. async fn sdiffstore() {
  565. let c = create_connection();
  566. assert_eq!(
  567. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  568. run_command(&c, &["scard", "1"]).await
  569. );
  570. assert_eq!(
  571. run_command(&c, &["sadd", "2", "c"]).await,
  572. run_command(&c, &["scard", "2"]).await
  573. );
  574. assert_eq!(
  575. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  576. run_command(&c, &["scard", "3"]).await
  577. );
  578. assert_eq!(
  579. Ok(Value::Integer(2)),
  580. run_command(&c, &["sdiffstore", "4", "1", "2", "3"]).await
  581. );
  582. match run_command(&c, &["smembers", "4"]).await {
  583. Ok(Value::Array(v)) => {
  584. assert_eq!(2, v.len());
  585. if v[0] == Value::Blob("b".into()) {
  586. assert_eq!(v[1], Value::Blob("d".into()));
  587. } else {
  588. assert_eq!(v[1], Value::Blob("b".into()));
  589. }
  590. }
  591. _ => unreachable!(),
  592. };
  593. }
  594. #[tokio::test]
  595. async fn sinter() {
  596. let c = create_connection();
  597. assert_eq!(
  598. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  599. run_command(&c, &["scard", "1"]).await
  600. );
  601. assert_eq!(
  602. run_command(&c, &["sadd", "2", "c", "x"]).await,
  603. run_command(&c, &["scard", "2"]).await
  604. );
  605. assert_eq!(
  606. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  607. run_command(&c, &["scard", "3"]).await
  608. );
  609. assert_eq!(
  610. Ok(Value::Array(vec![Value::Blob("c".into())])),
  611. run_command(&c, &["sinter", "1", "2", "3"]).await
  612. );
  613. }
  614. #[tokio::test]
  615. async fn sintercard() {
  616. let c = create_connection();
  617. assert_eq!(
  618. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  619. run_command(&c, &["scard", "1"]).await
  620. );
  621. assert_eq!(
  622. run_command(&c, &["sadd", "2", "c", "x"]).await,
  623. run_command(&c, &["scard", "2"]).await
  624. );
  625. assert_eq!(
  626. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  627. run_command(&c, &["scard", "3"]).await
  628. );
  629. assert_eq!(
  630. Ok(Value::Integer(1)),
  631. run_command(&c, &["sintercard", "1", "2", "3"]).await
  632. );
  633. }
  634. #[tokio::test]
  635. async fn sinterstore() {
  636. let c = create_connection();
  637. assert_eq!(
  638. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  639. run_command(&c, &["scard", "1"]).await
  640. );
  641. assert_eq!(
  642. run_command(&c, &["sadd", "2", "c", "x"]).await,
  643. run_command(&c, &["scard", "2"]).await
  644. );
  645. assert_eq!(
  646. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  647. run_command(&c, &["scard", "3"]).await
  648. );
  649. assert_eq!(
  650. Ok(Value::Integer(1)),
  651. run_command(&c, &["sinterstore", "foo", "1", "2", "3"]).await
  652. );
  653. assert_eq!(
  654. Ok(Value::Array(vec![Value::Blob("c".into())])),
  655. run_command(&c, &["smembers", "foo"]).await
  656. );
  657. }
  658. #[tokio::test]
  659. async fn sismember() {
  660. let c = create_connection();
  661. assert_eq!(
  662. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "5"]).await,
  663. run_command(&c, &["scard", "foo"]).await
  664. );
  665. assert_eq!(
  666. Ok(Value::Integer(1)),
  667. run_command(&c, &["sismember", "foo", "5"]).await
  668. );
  669. assert_eq!(
  670. Ok(Value::Integer(0)),
  671. run_command(&c, &["sismember", "foo", "6"]).await
  672. );
  673. assert_eq!(
  674. Ok(Value::Integer(0)),
  675. run_command(&c, &["sismember", "foobar", "5"]).await
  676. );
  677. }
  678. #[tokio::test]
  679. async fn smismember() {
  680. let c = create_connection();
  681. assert_eq!(
  682. run_command(&c, &["sadd", "foo", "1", "2", "3", "4", "5", "5"]).await,
  683. run_command(&c, &["scard", "foo"]).await
  684. );
  685. assert_eq!(
  686. Ok(Value::Array(vec![
  687. Value::Integer(1),
  688. Value::Integer(0),
  689. Value::Integer(1),
  690. ])),
  691. run_command(&c, &["smismember", "foo", "5", "6", "3"]).await
  692. );
  693. }
  694. #[tokio::test]
  695. async fn smove() {
  696. let c = create_connection();
  697. assert_eq!(
  698. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  699. run_command(&c, &["scard", "1"]).await
  700. );
  701. assert_eq!(
  702. Ok(Value::Integer(1)),
  703. run_command(&c, &["smove", "1", "2", "d"]).await
  704. );
  705. assert_eq!(
  706. Ok(Value::Integer(0)),
  707. run_command(&c, &["smove", "1", "2", "f"]).await
  708. );
  709. assert_eq!(
  710. Ok(Value::Integer(3)),
  711. run_command(&c, &["scard", "1"]).await
  712. );
  713. assert_eq!(
  714. Ok(Value::Integer(1)),
  715. run_command(&c, &["scard", "2"]).await
  716. );
  717. }
  718. #[tokio::test]
  719. async fn spop() {
  720. let c = create_connection();
  721. assert_eq!(
  722. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  723. run_command(&c, &["scard", "1"]).await
  724. );
  725. let _ = run_command(&c, &["spop", "1"]).await;
  726. assert_eq!(
  727. Ok(Value::Integer(3)),
  728. run_command(&c, &["scard", "1"]).await
  729. );
  730. if let Ok(Value::Array(x)) = run_command(&c, &["spop", "1", "2"]).await {
  731. assert_eq!(2, x.len());
  732. }
  733. assert_eq!(
  734. Ok(Value::Integer(1)),
  735. run_command(&c, &["scard", "1"]).await
  736. );
  737. }
  738. #[tokio::test]
  739. async fn srem() {
  740. let c = create_connection();
  741. assert_eq!(
  742. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  743. run_command(&c, &["scard", "1"]).await
  744. );
  745. assert_eq!(
  746. Ok(Value::Integer(1)),
  747. run_command(&c, &["srem", "1", "b"]).await
  748. );
  749. assert_eq!(
  750. Ok(Value::Integer(3)),
  751. run_command(&c, &["scard", "1"]).await
  752. );
  753. assert_eq!(
  754. Ok(Value::Integer(2)),
  755. run_command(&c, &["srem", "1", "a", "b", "c"]).await
  756. );
  757. assert_eq!(
  758. Ok(Value::Integer(1)),
  759. run_command(&c, &["scard", "1"]).await
  760. );
  761. }
  762. #[tokio::test]
  763. async fn sunion() {
  764. let c = create_connection();
  765. assert_eq!(
  766. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  767. run_command(&c, &["scard", "1"]).await
  768. );
  769. assert_eq!(
  770. run_command(&c, &["sadd", "2", "c", "x"]).await,
  771. run_command(&c, &["scard", "2"]).await
  772. );
  773. assert_eq!(
  774. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  775. run_command(&c, &["scard", "3"]).await
  776. );
  777. assert_eq!(
  778. 6,
  779. if let Ok(Value::Array(x)) = run_command(&c, &["sunion", "1", "2", "3"]).await {
  780. x.len()
  781. } else {
  782. 0
  783. }
  784. );
  785. }
  786. #[tokio::test]
  787. async fn sunion_first_key_do_not_exists() {
  788. let c = create_connection();
  789. assert_eq!(
  790. run_command(&c, &["sadd", "1", "a", "b", "c", "d"]).await,
  791. run_command(&c, &["scard", "1"]).await
  792. );
  793. assert_eq!(
  794. run_command(&c, &["sadd", "2", "c", "x"]).await,
  795. run_command(&c, &["scard", "2"]).await
  796. );
  797. assert_eq!(
  798. run_command(&c, &["sadd", "3", "a", "c", "e"]).await,
  799. run_command(&c, &["scard", "3"]).await
  800. );
  801. assert_eq!(
  802. 6,
  803. if let Ok(Value::Array(x)) = run_command(&c, &["sunion", "0", "1", "2", "3"]).await {
  804. x.len()
  805. } else {
  806. 0
  807. }
  808. );
  809. }
  810. }