list.rs 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975
  1. //! # List command handlers
  2. use crate::{
  3. check_arg,
  4. connection::{Connection, ConnectionStatus, UnblockReason},
  5. db::utils::far_future,
  6. error::Error,
  7. try_get_arg, try_get_arg_str,
  8. value::bytes_to_number,
  9. value::checksum,
  10. value::Value,
  11. };
  12. use bytes::Bytes;
  13. use std::collections::VecDeque;
  14. use tokio::time::{sleep, Duration, Instant};
  15. #[allow(clippy::needless_range_loop)]
  16. /// Removes an element from a list
  17. #[inline]
  18. fn remove_element(
  19. conn: &Connection,
  20. key: &Bytes,
  21. limit: Option<usize>,
  22. front: bool,
  23. ) -> Result<Value, Error> {
  24. let db = conn.db();
  25. let mut new_len = 0;
  26. let result = db.get_map_or(
  27. key,
  28. |v| match v {
  29. Value::List(x) => {
  30. let mut x = x.write();
  31. let limit = if let Some(limit) = limit {
  32. limit
  33. } else {
  34. // Return a single element
  35. let ret = Ok((if front { x.pop_front() } else { x.pop_back() })
  36. .map_or(Value::Null, |x| x.clone_value()));
  37. new_len = x.len();
  38. return ret;
  39. };
  40. let mut ret = vec![None; limit];
  41. for i in 0..limit {
  42. if front {
  43. ret[i] = x.pop_front();
  44. } else {
  45. ret[i] = x.pop_back();
  46. }
  47. }
  48. new_len = x.len();
  49. Ok(ret
  50. .iter()
  51. .flatten()
  52. .map(|m| m.clone_value())
  53. .collect::<Vec<Value>>()
  54. .into())
  55. }
  56. _ => Err(Error::WrongType),
  57. },
  58. || Ok(Value::Null),
  59. )?;
  60. if new_len == 0 {
  61. let _ = db.del(&[key.clone()]);
  62. } else {
  63. db.bump_version(key);
  64. }
  65. Ok(result)
  66. }
  67. #[inline]
  68. /// Handles the timeout/sleep logic for all blocking commands.
  69. async fn handle_timeout(conn: &Connection, timeout: Option<Instant>) -> Result<bool, Error> {
  70. if let Some(timeout) = timeout {
  71. if Instant::now() >= timeout {
  72. conn.unblock(UnblockReason::Timeout);
  73. return Ok(true);
  74. }
  75. }
  76. if let Some(reason) = conn.has_been_unblocked_externally() {
  77. match reason {
  78. UnblockReason::Error => Err(Error::UnblockByError),
  79. _ => Ok(true),
  80. }
  81. } else {
  82. sleep(Duration::from_millis(100)).await;
  83. Ok(false)
  84. }
  85. }
  86. /// Parses timeout and returns an instant or none if it should wait forever.
  87. #[inline]
  88. fn parse_timeout(arg: &Bytes) -> Result<Option<Instant>, Error> {
  89. let raw_timeout = bytes_to_number::<f64>(arg)?;
  90. if raw_timeout < 0f64 {
  91. return Err(Error::NegativeNumber("timeout".to_owned()));
  92. }
  93. if raw_timeout == 0.0 {
  94. return Ok(None);
  95. }
  96. Ok(Some(
  97. Instant::now()
  98. .checked_add(Duration::from_millis(
  99. (raw_timeout * 1_000f64).round() as u64
  100. ))
  101. .unwrap_or_else(far_future),
  102. ))
  103. }
  104. /// BLPOP is a blocking list pop primitive. It is the blocking version of LPOP because it blocks
  105. /// the connection when there are no elements to pop from any of the given lists. An element is
  106. /// popped from the head of the first list that is non-empty, with the given keys being checked in
  107. /// the order that they are given.
  108. pub async fn blpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  109. let blpop_task = |conn: &Connection, args: &[Bytes]| -> Result<Value, Error> {
  110. for key in (1..args.len() - 1) {
  111. let key = &args[key];
  112. match remove_element(&conn, key, None, true)? {
  113. Value::Null => (),
  114. n => return Ok(vec![Value::new(&key), n].into()),
  115. };
  116. }
  117. Ok(Value::Null)
  118. };
  119. if conn.is_executing_tx() {
  120. return blpop_task(conn, args);
  121. }
  122. let timeout = parse_timeout(&args[args.len() - 1])?;
  123. let conn = conn.clone();
  124. let args = args.to_vec();
  125. conn.block();
  126. tokio::spawn(async move {
  127. loop {
  128. match blpop_task(&conn, &args) {
  129. Ok(Value::Null) => {}
  130. Ok(x) => {
  131. conn.append_response(x);
  132. conn.unblock(UnblockReason::Finished);
  133. break;
  134. }
  135. Err(x) => {
  136. conn.append_response(x.into());
  137. conn.unblock(UnblockReason::Finished);
  138. break;
  139. }
  140. }
  141. match handle_timeout(&conn, timeout).await {
  142. Ok(true) => {
  143. conn.append_response(Value::Null);
  144. break;
  145. }
  146. Err(x) => {
  147. conn.append_response(x.into());
  148. break;
  149. }
  150. _ => {}
  151. }
  152. }
  153. });
  154. Ok(Value::Ignore)
  155. }
  156. /// BLMOVE is the blocking variant of LMOVE. When source contains elements, this
  157. /// command behaves exactly like LMOVE. When used inside a MULTI/EXEC block,
  158. /// this command behaves exactly like LMOVE. When source is empty, Redis will
  159. /// block the connection until another client pushes to it or until timeout (a
  160. /// double value specifying the maximum number of seconds to block) is reached.
  161. /// A timeout of zero can be used to block indefinitely.
  162. ///
  163. /// This command comes in place of the now deprecated BRPOPLPUSH. Doing BLMOVE
  164. /// RIGHT LEFT is equivalent.
  165. ///
  166. /// See LMOVE for more information.
  167. pub async fn blmove(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  168. if conn.is_executing_tx() {
  169. return lmove(&conn, &args).await;
  170. }
  171. let timeout = parse_timeout(&args[5])?;
  172. conn.block();
  173. let conn = conn.clone();
  174. let args = args.to_vec();
  175. tokio::spawn(async move {
  176. loop {
  177. match lmove(&conn, &args).await {
  178. Ok(Value::Null) => (),
  179. Ok(n) => {
  180. conn.append_response(n);
  181. conn.unblock(UnblockReason::Finished);
  182. break;
  183. }
  184. Err(x) => {
  185. conn.append_response(x.into());
  186. conn.unblock(UnblockReason::Finished);
  187. break;
  188. }
  189. };
  190. match handle_timeout(&conn, timeout).await {
  191. Ok(true) => {
  192. conn.append_response(Value::Null);
  193. break;
  194. }
  195. Err(x) => {
  196. conn.append_response(x.into());
  197. break;
  198. }
  199. _ => {}
  200. }
  201. }
  202. });
  203. Ok(Value::Ignore)
  204. }
  205. /// BRPOPLPUSH is the blocking variant of RPOPLPUSH. When source contains
  206. /// elements, this command behaves exactly like RPOPLPUSH. When used inside a
  207. /// MULTI/EXEC block, this command behaves exactly like RPOPLPUSH. When source
  208. /// is empty, Redis will block the connection until another client pushes to it
  209. /// or until timeout is reached. A timeout of zero can be used to block
  210. /// indefinitely.
  211. pub async fn brpoplpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  212. blmove(
  213. conn,
  214. &[
  215. "blmove".into(),
  216. args[1].clone(),
  217. args[2].clone(),
  218. "RIGHT".into(),
  219. "LEFT".into(),
  220. args[3].clone(),
  221. ],
  222. )
  223. .await
  224. }
  225. /// BRPOP is a blocking list pop primitive. It is the blocking version of RPOP because it blocks
  226. /// the connection when there are no elements to pop from any of the given lists. An element is
  227. /// popped from the tail of the first list that is non-empty, with the given keys being checked in
  228. /// the order that they are given.
  229. pub async fn brpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  230. let brpop_task = |conn: &Connection, args: &[Bytes]| -> Result<Value, Error> {
  231. for key in (1..args.len() - 1) {
  232. let key = &args[key];
  233. match remove_element(&conn, key, None, false)? {
  234. Value::Null => (),
  235. n => return Ok(vec![Value::new(&key), n].into()),
  236. };
  237. }
  238. Ok(Value::Null)
  239. };
  240. if conn.is_executing_tx() {
  241. return brpop_task(conn, args);
  242. }
  243. let timeout = parse_timeout(&args[args.len() - 1])?;
  244. let conn = conn.clone();
  245. let args = args.to_vec();
  246. conn.block();
  247. tokio::spawn(async move {
  248. loop {
  249. match brpop_task(&conn, &args) {
  250. Ok(Value::Null) => {}
  251. Ok(x) => {
  252. conn.append_response(x);
  253. conn.unblock(UnblockReason::Finished);
  254. break;
  255. }
  256. Err(x) => {
  257. conn.append_response(x.into());
  258. conn.unblock(UnblockReason::Finished);
  259. break;
  260. }
  261. }
  262. match handle_timeout(&conn, timeout).await {
  263. Ok(true) => {
  264. conn.append_response(Value::Null);
  265. break;
  266. }
  267. Err(x) => {
  268. conn.append_response(x.into());
  269. break;
  270. }
  271. _ => {}
  272. }
  273. }
  274. });
  275. Ok(Value::Ignore)
  276. }
  277. /// Returns the element at index index in the list stored at key. The index is zero-based, so 0
  278. /// means the first element, 1 the second element and so on. Negative indices can be used to
  279. /// designate elements starting at the tail of the list. Here, -1 means the last element, -2 means
  280. /// the penultimate and so forth.
  281. pub async fn lindex(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  282. conn.db().get_map_or(
  283. &args[1],
  284. |v| match v {
  285. Value::List(x) => {
  286. let mut index: i64 = bytes_to_number(&args[2])?;
  287. let x = x.read();
  288. let index = if index < 0 {
  289. x.len()
  290. .checked_sub((index * -1) as usize)
  291. .unwrap_or(x.len())
  292. } else {
  293. index as usize
  294. };
  295. Ok(x.get(index).map_or(Value::Null, |x| x.clone_value()))
  296. }
  297. _ => Err(Error::WrongType),
  298. },
  299. || Ok(Value::Null),
  300. )
  301. }
  302. /// Inserts element in the list stored at key either before or after the reference value pivot.
  303. ///
  304. /// When key does not exist, it is considered an empty list and no operation is performed.
  305. pub async fn linsert(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  306. let is_before = if check_arg!(args, 2, "BEFORE") {
  307. true
  308. } else if check_arg!(args, 2, "AFTER") {
  309. false
  310. } else {
  311. return Err(Error::Syntax);
  312. };
  313. let result = conn.db().get_map_or(
  314. &args[1],
  315. |v| match v {
  316. Value::List(x) => {
  317. let pivot = checksum::Ref::new(&args[3]);
  318. let mut x = x.write();
  319. let mut found = false;
  320. for (key, val) in x.iter().enumerate() {
  321. if *val == pivot {
  322. let id = if is_before { key } else { key + 1 };
  323. let value = checksum::Value::new(args[4].clone());
  324. if id > x.len() {
  325. x.push_back(value);
  326. } else {
  327. x.insert(id as usize, value);
  328. }
  329. found = true;
  330. break;
  331. }
  332. }
  333. if found {
  334. Ok(x.len().into())
  335. } else {
  336. Ok((-1).into())
  337. }
  338. }
  339. _ => Err(Error::WrongType),
  340. },
  341. || Ok(0.into()),
  342. )?;
  343. conn.db().bump_version(&args[1]);
  344. Ok(result)
  345. }
  346. /// Returns the length of the list stored at key. If key does not exist, it is interpreted as an
  347. /// empty list and 0 is returned. An error is returned when the value stored at key is not a list.
  348. pub async fn llen(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  349. conn.db().get_map_or(
  350. &args[1],
  351. |v| match v {
  352. Value::List(x) => Ok(x.read().len().into()),
  353. _ => Err(Error::WrongType),
  354. },
  355. || Ok(0.into()),
  356. )
  357. }
  358. /// Atomically returns and removes the first/last element (head/tail depending on the wherefrom
  359. /// argument) of the list stored at source, and pushes the element at the first/last element
  360. /// (head/tail depending on the whereto argument) of the list stored at destination.
  361. pub async fn lmove(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  362. let source_is_left = if check_arg!(args, 3, "LEFT") {
  363. true
  364. } else if check_arg!(args, 3, "RIGHT") {
  365. false
  366. } else {
  367. return Err(Error::Syntax);
  368. };
  369. let target_is_left = if check_arg!(args, 4, "LEFT") {
  370. true
  371. } else if check_arg!(args, 4, "RIGHT") {
  372. false
  373. } else {
  374. return Err(Error::Syntax);
  375. };
  376. let result = conn.db().get_map_or(
  377. &args[1],
  378. |v| match v {
  379. Value::List(source) => conn.db().get_map_or(
  380. &args[2],
  381. |v| match v {
  382. Value::List(target) => {
  383. let element = if source_is_left {
  384. source.write().pop_front()
  385. } else {
  386. source.write().pop_back()
  387. };
  388. if let Some(element) = element {
  389. let ret = element.clone_value();
  390. if target_is_left {
  391. target.write().push_front(element);
  392. } else {
  393. target.write().push_back(element);
  394. }
  395. Ok(ret)
  396. } else {
  397. Ok(Value::Null)
  398. }
  399. }
  400. _ => Err(Error::WrongType),
  401. },
  402. || {
  403. let element = if source_is_left {
  404. source.write().pop_front()
  405. } else {
  406. source.write().pop_back()
  407. };
  408. if let Some(element) = element {
  409. let ret = element.clone_value();
  410. let mut h = VecDeque::new();
  411. h.push_front(element);
  412. conn.db().set(&args[2], h.into(), None);
  413. Ok(ret)
  414. } else {
  415. Ok(Value::Null)
  416. }
  417. },
  418. ),
  419. _ => Err(Error::WrongType),
  420. },
  421. || Ok(Value::Null),
  422. )?;
  423. conn.db().bump_version(&args[1]);
  424. Ok(result)
  425. }
  426. /// Removes and returns the first elements of the list stored at key.
  427. ///
  428. /// By default, the command pops a single element from the beginning of the list. When provided
  429. /// with the optional count argument, the reply will consist of up to count elements, depending on
  430. /// the list's length.
  431. pub async fn lpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  432. let count = match args.get(2) {
  433. Some(v) => Some(bytes_to_number(&v)?),
  434. None => None,
  435. };
  436. remove_element(conn, &args[1], count, true)
  437. }
  438. /// The command returns the index of matching elements inside a Redis list. By default, when no
  439. /// options are given, it will scan the list from head to tail, looking for the first match of
  440. /// "element". If the element is found, its index (the zero-based position in the list) is
  441. /// returned. Otherwise, if no match is found, nil is returned.
  442. pub async fn lpos(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  443. let element = checksum::Ref::new(&args[2]);
  444. let mut rank = None;
  445. let mut count = None;
  446. let mut max_len = None;
  447. let mut index = 3;
  448. loop {
  449. if args.len() <= index {
  450. break;
  451. }
  452. let next = try_get_arg!(args, index + 1);
  453. match try_get_arg_str!(args, index).to_uppercase().as_str() {
  454. "RANK" => rank = Some(bytes_to_number::<i64>(&next)?),
  455. "COUNT" => count = Some(bytes_to_number::<usize>(&next)?),
  456. "MAXLEN" => max_len = Some(bytes_to_number::<usize>(&next)?),
  457. _ => return Err(Error::Syntax),
  458. }
  459. index += 2;
  460. }
  461. let (must_reverse, rank) = if let Some(rank) = rank {
  462. if rank == 0 {
  463. return Err(Error::InvalidRank("RANK".to_owned()));
  464. }
  465. if rank < 0 {
  466. (true, Some((rank * -1) as usize))
  467. } else {
  468. (false, Some(rank as usize))
  469. }
  470. } else {
  471. (false, None)
  472. };
  473. let max_len = max_len.unwrap_or_default();
  474. conn.db().get_map_or(
  475. &args[1],
  476. |v| match v {
  477. Value::List(x) => {
  478. let x = x.read();
  479. let mut result: Vec<Value> = vec![];
  480. let mut values = x
  481. .iter()
  482. .enumerate()
  483. .collect::<Vec<(usize, &checksum::Value)>>();
  484. if must_reverse {
  485. values.reverse();
  486. }
  487. let mut checks = 1;
  488. for (id, val) in values.iter() {
  489. if **val == element {
  490. // Match!
  491. if let Some(count) = count {
  492. result.push((*id).into());
  493. if result.len() == count && count != 0 && rank.is_none() {
  494. // There is no point in keep looping. No RANK provided, COUNT is not 0
  495. // therefore we can return the vector of result as IS
  496. return Ok(result.into());
  497. }
  498. } else if let Some(rank) = rank {
  499. result.push((*id).into());
  500. if result.len() == rank {
  501. return Ok((*id).into());
  502. }
  503. } else {
  504. // return first match!
  505. return Ok((*id).into());
  506. }
  507. }
  508. if checks == max_len {
  509. break;
  510. }
  511. checks += 1;
  512. }
  513. if let Some(rank) = rank {
  514. let rank = rank - 1;
  515. let result = if rank < result.len() {
  516. (&result[rank..]).to_vec()
  517. } else {
  518. vec![]
  519. };
  520. return Ok(if let Some(count) = count {
  521. if count > 0 && count < result.len() {
  522. (&result[0..count]).to_vec().into()
  523. } else {
  524. result.to_vec().into()
  525. }
  526. } else {
  527. result
  528. .to_vec()
  529. .get(0)
  530. .map(|c| c.clone())
  531. .unwrap_or_default()
  532. });
  533. }
  534. if count.is_some() {
  535. Ok(result.into())
  536. } else {
  537. Ok(Value::Null)
  538. }
  539. }
  540. _ => Err(Error::WrongType),
  541. },
  542. || {
  543. Ok(if count.is_some() {
  544. Value::Array(vec![])
  545. } else {
  546. Value::Null
  547. })
  548. },
  549. )
  550. }
  551. /// Insert all the specified values at the head of the list stored at key. If key does not exist,
  552. /// it is created as empty list before performing the push operations. When key holds a value that
  553. /// is not a list, an error is returned.
  554. ///
  555. /// It is possible to push multiple elements using a single command call just specifying multiple
  556. /// arguments at the end of the command. Elements are inserted one after the other to the head of
  557. /// the list, from the leftmost element to the rightmost element. So for instance the command LPUSH
  558. /// mylist a b c will result into a list containing c as first element, b as second element and a
  559. /// as third element.
  560. pub async fn lpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  561. let is_push_x = check_arg!(args, 0, "LPUSHX");
  562. let result = conn.db().get_map_or(
  563. &args[1],
  564. |v| match v {
  565. Value::List(x) => {
  566. let mut x = x.write();
  567. for val in args.iter().skip(2) {
  568. x.push_front(checksum::Value::new(val.clone()));
  569. }
  570. Ok(x.len().into())
  571. }
  572. _ => Err(Error::WrongType),
  573. },
  574. || {
  575. if is_push_x {
  576. return Ok(0.into());
  577. }
  578. let mut h = VecDeque::new();
  579. for val in args.iter().skip(2) {
  580. h.push_front(checksum::Value::new(val.clone()));
  581. }
  582. let len = h.len();
  583. conn.db().set(&args[1], h.into(), None);
  584. Ok(len.into())
  585. },
  586. )?;
  587. conn.db().bump_version(&args[1]);
  588. Ok(result)
  589. }
  590. /// Returns the specified elements of the list stored at key. The offsets start and stop are
  591. /// zero-based indexes, with 0 being the first element of the list (the head of the list), 1 being
  592. /// the next element and so on.
  593. ///
  594. /// These offsets can also be negative numbers indicating offsets starting at the end of the list.
  595. /// For example, -1 is the last element of the list, -2 the penultimate, and so on.
  596. pub async fn lrange(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  597. conn.db().get_map_or(
  598. &args[1],
  599. |v| match v {
  600. Value::List(x) => {
  601. let start: i64 = bytes_to_number(&args[2])?;
  602. let end: i64 = bytes_to_number(&args[3])?;
  603. let mut ret = vec![];
  604. let x = x.read();
  605. let start = if start < 0 {
  606. x.len()
  607. .checked_sub((start * -1) as usize)
  608. .unwrap_or_default()
  609. } else {
  610. (start as usize)
  611. };
  612. let end = if end < 0 {
  613. if let Some(x) = x.len().checked_sub((end * -1) as usize) {
  614. x
  615. } else {
  616. return Ok(Value::Array((vec![])));
  617. }
  618. } else {
  619. end as usize
  620. };
  621. for (i, val) in x.iter().enumerate().skip(start) {
  622. if i > end {
  623. break;
  624. }
  625. ret.push(val.clone_value());
  626. }
  627. Ok(ret.into())
  628. }
  629. _ => Err(Error::WrongType),
  630. },
  631. || Ok(Value::Array(vec![])),
  632. )
  633. }
  634. /// Removes the first count occurrences of elements equal to element from the list stored at key
  635. pub async fn lrem(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  636. let result = conn.db().get_map_or(
  637. &args[1],
  638. |v| match v {
  639. Value::List(x) => {
  640. let element = checksum::Ref::new(&args[3]);
  641. let limit: i64 = bytes_to_number(&args[2])?;
  642. let mut x = x.write();
  643. let (is_reverse, limit) = if limit < 0 {
  644. (true, -limit)
  645. } else {
  646. (false, limit)
  647. };
  648. let mut keep = vec![true; x.len()];
  649. let mut removed = 0;
  650. let len = x.len();
  651. for i in 0..len {
  652. let i = if is_reverse { len - 1 - i } else { i };
  653. if let Some(value) = x.get(i) {
  654. if *value == element {
  655. keep[i] = false;
  656. removed += 1;
  657. if removed == limit {
  658. break;
  659. }
  660. }
  661. }
  662. }
  663. let mut i = 0;
  664. x.retain(|_| {
  665. i += 1;
  666. keep[i - 1]
  667. });
  668. Ok(removed.into())
  669. }
  670. _ => Err(Error::WrongType),
  671. },
  672. || Ok(0.into()),
  673. )?;
  674. conn.db().bump_version(&args[1]);
  675. Ok(result)
  676. }
  677. /// Sets the list element at index to element. For more information on the index argument, see
  678. /// LINDEX.
  679. ///
  680. /// An error is returned for out of range indexes.
  681. pub async fn lset(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  682. let result = conn.db().get_map_or(
  683. &args[1],
  684. |v| match v {
  685. Value::List(x) => {
  686. let mut index: i64 = bytes_to_number(&args[2])?;
  687. let mut x = x.write();
  688. if index < 0 {
  689. index += x.len() as i64;
  690. }
  691. if let Some(x) = x.get_mut(index as usize) {
  692. *x = checksum::Value::new(args[3].clone());
  693. Ok(Value::Ok)
  694. } else {
  695. Err(Error::OutOfRange)
  696. }
  697. }
  698. _ => Err(Error::WrongType),
  699. },
  700. || Err(Error::NotFound),
  701. )?;
  702. conn.db().bump_version(&args[1]);
  703. Ok(result)
  704. }
  705. /// Trim an existing list so that it will contain only the specified range of elements specified.
  706. /// Both start and stop are zero-based indexes, where 0 is the first element of the list (the
  707. /// head), 1 the next element and so on.
  708. pub async fn ltrim(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  709. let result = conn.db().get_map_or(
  710. &args[1],
  711. |v| match v {
  712. Value::List(x) => {
  713. let mut start: i64 = bytes_to_number(&args[2])?;
  714. let mut end: i64 = bytes_to_number(&args[3])?;
  715. let mut x = x.write();
  716. if start < 0 {
  717. start += x.len() as i64;
  718. }
  719. if end < 0 {
  720. end += x.len() as i64;
  721. }
  722. let mut i = 0;
  723. x.retain(|_| {
  724. let retain = i >= start && i <= end;
  725. i += 1;
  726. retain
  727. });
  728. Ok(Value::Ok)
  729. }
  730. _ => Err(Error::WrongType),
  731. },
  732. || Ok(Value::Ok),
  733. )?;
  734. conn.db().bump_version(&args[1]);
  735. Ok(result)
  736. }
  737. /// Removes and returns the last elements of the list stored at key.
  738. ///
  739. /// By default, the command pops a single element from the end of the list. When provided with the
  740. /// optional count argument, the reply will consist of up to count elements, depending on the
  741. /// list's length.
  742. pub async fn rpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  743. let count = match args.get(2) {
  744. Some(v) => Some(bytes_to_number(&v)?),
  745. None => None,
  746. };
  747. remove_element(conn, &args[1], count, false)
  748. }
  749. /// Atomically returns and removes the last element (tail) of the list stored at source, and pushes
  750. /// the element at the first element (head) of the list stored at destination.
  751. pub async fn rpoplpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  752. lmove(
  753. conn,
  754. &[
  755. "lmove".into(),
  756. args[1].clone(),
  757. args[2].clone(),
  758. "RIGHT".into(),
  759. "LEFT".into(),
  760. ],
  761. )
  762. .await
  763. }
  764. /// Insert all the specified values at the tail of the list stored at key. If key does not exist,
  765. /// it is created as empty list before performing the push operation. When key holds a value that
  766. /// is not a list, an error is returned.
  767. pub async fn rpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
  768. let is_push_x = check_arg!(args, 0, "RPUSHX");
  769. let result = conn.db().get_map_or(
  770. &args[1],
  771. |v| match v {
  772. Value::List(x) => {
  773. let mut x = x.write();
  774. for val in args.iter().skip(2) {
  775. x.push_back(checksum::Value::new(val.clone()));
  776. }
  777. Ok(x.len().into())
  778. }
  779. _ => Err(Error::WrongType),
  780. },
  781. || {
  782. if is_push_x {
  783. return Ok(0.into());
  784. }
  785. let mut h = VecDeque::new();
  786. for val in args.iter().skip(2) {
  787. h.push_back(checksum::Value::new(val.clone()));
  788. }
  789. let len = h.len();
  790. conn.db().set(&args[1], h.into(), None);
  791. Ok(len.into())
  792. },
  793. )?;
  794. conn.db().bump_version(&args[1]);
  795. Ok(result)
  796. }
  797. #[cfg(test)]
  798. mod test {
  799. use crate::{
  800. cmd::test::{create_connection, run_command},
  801. error::Error,
  802. value::Value,
  803. };
  804. use tokio::time::{sleep, Duration, Instant};
  805. #[tokio::test]
  806. async fn blpop_no_waiting() {
  807. let c = create_connection();
  808. assert_eq!(
  809. Ok(Value::Integer(5)),
  810. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
  811. );
  812. assert_eq!(
  813. Ok(Value::Array(vec![
  814. Value::Blob("foo".into()),
  815. Value::Blob("5".into()),
  816. ])),
  817. run_command(&c, &["blpop", "foo", "1"]).await
  818. );
  819. }
  820. #[tokio::test]
  821. async fn blpop_timeout() {
  822. let c = create_connection();
  823. let x = Instant::now();
  824. assert_eq!(
  825. Ok(Value::Null),
  826. run_command(&c, &["blpop", "foobar", "1"]).await
  827. );
  828. assert!(Instant::now() - x <= Duration::from_millis(1000));
  829. }
  830. #[tokio::test]
  831. async fn blpop_wait_insert() {
  832. let c = create_connection();
  833. let x = Instant::now();
  834. // Query command that will block connection until some data is inserted
  835. // to foobar, foo, bar or the 5 seconds timeout happens.
  836. //
  837. // We are issuing the command, sleeping a little bit then adding data to
  838. // foobar, before actually waiting on the result.
  839. let waiting = run_command(&c, &["blpop", "foobar", "foo", "bar", "5"]);
  840. // Sleep 1 second before inserting new data
  841. sleep(Duration::from_millis(1000)).await;
  842. assert_eq!(
  843. Ok(Value::Integer(5)),
  844. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
  845. );
  846. // Read the output of the first blpop command now.
  847. assert_eq!(
  848. Ok(Value::Array(vec![
  849. Value::Blob("foo".into()),
  850. Value::Blob("5".into()),
  851. ])),
  852. waiting.await
  853. );
  854. assert!(Instant::now() - x > Duration::from_millis(1000));
  855. assert!(Instant::now() - x < Duration::from_millis(5000));
  856. }
  857. #[tokio::test]
  858. async fn lrem_1() {
  859. let c = create_connection();
  860. assert_eq!(
  861. Ok(Value::Integer(5)),
  862. run_command(
  863. &c,
  864. &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
  865. )
  866. .await
  867. );
  868. assert_eq!(
  869. Ok(Value::Integer(3)),
  870. run_command(&c, &["lrem", "mylist", "3", "hello"]).await
  871. );
  872. assert_eq!(
  873. Ok(Value::Array(vec![
  874. Value::Blob("world".into()),
  875. Value::Blob("hello".into()),
  876. ])),
  877. run_command(&c, &["lrange", "mylist", "0", "-1"]).await
  878. );
  879. }
  880. #[tokio::test]
  881. async fn lrem_2() {
  882. let c = create_connection();
  883. assert_eq!(
  884. Ok(Value::Integer(5)),
  885. run_command(
  886. &c,
  887. &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
  888. )
  889. .await
  890. );
  891. assert_eq!(
  892. Ok(Value::Integer(2)),
  893. run_command(&c, &["lrem", "mylist", "-2", "hello"]).await
  894. );
  895. assert_eq!(
  896. Ok(Value::Array(vec![
  897. Value::Blob("hello".into()),
  898. Value::Blob("hello".into()),
  899. Value::Blob("world".into()),
  900. ])),
  901. run_command(&c, &["lrange", "mylist", "0", "-1"]).await
  902. );
  903. assert_eq!(
  904. Ok(Value::Integer(1)),
  905. run_command(&c, &["lrem", "mylist", "1", "hello"]).await
  906. );
  907. assert_eq!(
  908. Ok(Value::Array(vec![
  909. Value::Blob("hello".into()),
  910. Value::Blob("world".into()),
  911. ])),
  912. run_command(&c, &["lrange", "mylist", "0", "-1"]).await
  913. );
  914. }
  915. #[tokio::test]
  916. async fn lrem_3() {
  917. let c = create_connection();
  918. assert_eq!(
  919. Ok(Value::Integer(5)),
  920. run_command(
  921. &c,
  922. &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
  923. )
  924. .await
  925. );
  926. assert_eq!(
  927. Ok(Value::Integer(4)),
  928. run_command(&c, &["lrem", "mylist", "-100", "hello"]).await
  929. );
  930. assert_eq!(
  931. Ok(Value::Array(vec![Value::Blob("world".into()),])),
  932. run_command(&c, &["lrange", "mylist", "0", "-1"]).await
  933. );
  934. }
  935. #[tokio::test]
  936. async fn lrem_4() {
  937. let c = create_connection();
  938. assert_eq!(
  939. Ok(Value::Integer(5)),
  940. run_command(
  941. &c,
  942. &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
  943. )
  944. .await
  945. );
  946. assert_eq!(
  947. Ok(Value::Integer(4)),
  948. run_command(&c, &["lrem", "mylist", "100", "hello"]).await
  949. );
  950. assert_eq!(
  951. Ok(Value::Array(vec![Value::Blob("world".into()),])),
  952. run_command(&c, &["lrange", "mylist", "0", "-1"]).await
  953. );
  954. }
  955. #[tokio::test]
  956. async fn brpop_no_waiting() {
  957. let c = create_connection();
  958. assert_eq!(
  959. Ok(Value::Integer(5)),
  960. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
  961. );
  962. assert_eq!(
  963. Ok(Value::Array(vec![
  964. Value::Blob("foo".into()),
  965. Value::Blob("5".into()),
  966. ])),
  967. run_command(&c, &["brpop", "foo", "1"]).await
  968. );
  969. }
  970. #[tokio::test]
  971. async fn brpop_timeout() {
  972. let c = create_connection();
  973. let x = Instant::now();
  974. assert_eq!(
  975. Ok(Value::Null),
  976. run_command(&c, &["brpop", "foobar", "1"]).await
  977. );
  978. assert!(Instant::now() - x < Duration::from_millis(1000));
  979. }
  980. #[tokio::test]
  981. async fn brpop_wait_insert() {
  982. let c = create_connection();
  983. let x = Instant::now();
  984. // Query command that will block connection until some data is inserted
  985. // to foobar, foo, bar or the 5 seconds timeout happens.
  986. //
  987. // We are issuing the command, sleeping a little bit then adding data to
  988. // foobar, before actually waiting on the result.
  989. let waiting = run_command(&c, &["brpop", "foobar", "foo", "bar", "5"]);
  990. // Sleep 1 second before inserting new data
  991. sleep(Duration::from_millis(1000)).await;
  992. assert_eq!(
  993. Ok(Value::Integer(5)),
  994. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
  995. );
  996. // Read the output of the first blpop command now.
  997. assert_eq!(
  998. Ok(Value::Array(vec![
  999. Value::Blob("foo".into()),
  1000. Value::Blob("5".into()),
  1001. ])),
  1002. waiting.await
  1003. );
  1004. assert!(Instant::now() - x > Duration::from_millis(1000));
  1005. assert!(Instant::now() - x < Duration::from_millis(5000));
  1006. }
  1007. #[tokio::test]
  1008. async fn lindex() {
  1009. let c = create_connection();
  1010. assert_eq!(
  1011. Ok(Value::Integer(5)),
  1012. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await
  1013. );
  1014. assert_eq!(
  1015. Ok(Value::Array(vec![
  1016. Value::Blob("5".into()),
  1017. Value::Blob("4".into()),
  1018. Value::Blob("3".into()),
  1019. Value::Blob("2".into()),
  1020. Value::Blob("1".into()),
  1021. ])),
  1022. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1023. );
  1024. assert_eq!(
  1025. Ok(Value::Blob("5".into())),
  1026. run_command(&c, &["lindex", "foo", "0"]).await
  1027. );
  1028. assert_eq!(
  1029. Ok(Value::Blob("1".into())),
  1030. run_command(&c, &["lindex", "foo", "-1"]).await
  1031. );
  1032. assert_eq!(
  1033. Ok(Value::Null),
  1034. run_command(&c, &["lindex", "foo", "-100"]).await
  1035. );
  1036. assert_eq!(
  1037. Ok(Value::Null),
  1038. run_command(&c, &["lindex", "foo", "100"]).await
  1039. );
  1040. }
  1041. #[tokio::test]
  1042. async fn linsert_syntax_err() {
  1043. let c = create_connection();
  1044. assert_eq!(
  1045. Ok(Value::Integer(2)),
  1046. run_command(&c, &["rpush", "foo", "hello", "world"]).await
  1047. );
  1048. assert_eq!(
  1049. Err(Error::Syntax),
  1050. run_command(&c, &["linsert", "foo", "beforex", "world", "there"]).await
  1051. );
  1052. }
  1053. #[tokio::test]
  1054. async fn linsert_before() {
  1055. let c = create_connection();
  1056. assert_eq!(
  1057. Ok(Value::Integer(2)),
  1058. run_command(&c, &["rpush", "foo", "hello", "world"]).await
  1059. );
  1060. assert_eq!(
  1061. Ok(Value::Integer(3)),
  1062. run_command(&c, &["linsert", "foo", "before", "world", "there"]).await
  1063. );
  1064. assert_eq!(
  1065. Ok(Value::Array(vec![
  1066. Value::Blob("hello".into()),
  1067. Value::Blob("there".into()),
  1068. Value::Blob("world".into()),
  1069. ])),
  1070. run_command(&c, &["lrange", "foo", "0", "-1"]).await,
  1071. );
  1072. }
  1073. #[tokio::test]
  1074. async fn linsert_after() {
  1075. let c = create_connection();
  1076. assert_eq!(
  1077. Ok(Value::Integer(2)),
  1078. run_command(&c, &["rpush", "foo", "hello", "world"]).await
  1079. );
  1080. assert_eq!(
  1081. Ok(Value::Integer(3)),
  1082. run_command(&c, &["linsert", "foo", "after", "world", "there"]).await
  1083. );
  1084. assert_eq!(
  1085. Ok(Value::Array(vec![
  1086. Value::Blob("hello".into()),
  1087. Value::Blob("world".into()),
  1088. Value::Blob("there".into()),
  1089. ])),
  1090. run_command(&c, &["lrange", "foo", "0", "-1"]).await,
  1091. );
  1092. }
  1093. #[tokio::test]
  1094. async fn linsert_before_after() {
  1095. let c = create_connection();
  1096. assert_eq!(
  1097. Ok(Value::Integer(2)),
  1098. run_command(&c, &["rpush", "foo", "hello", "world"]).await
  1099. );
  1100. assert_eq!(
  1101. Ok(Value::Integer(3)),
  1102. run_command(&c, &["linsert", "foo", "after", "world", "there1"]).await
  1103. );
  1104. assert_eq!(
  1105. Ok(Value::Integer(4)),
  1106. run_command(&c, &["linsert", "foo", "before", "world", "there2"]).await
  1107. );
  1108. assert_eq!(
  1109. Ok(Value::Array(vec![
  1110. Value::Blob("hello".into()),
  1111. Value::Blob("there2".into()),
  1112. Value::Blob("world".into()),
  1113. Value::Blob("there1".into()),
  1114. ])),
  1115. run_command(&c, &["lrange", "foo", "0", "-1"]).await,
  1116. );
  1117. }
  1118. #[tokio::test]
  1119. async fn linsert_not_found() {
  1120. let c = create_connection();
  1121. assert_eq!(
  1122. Ok(Value::Integer(2)),
  1123. run_command(&c, &["rpush", "foo", "hello", "world"]).await
  1124. );
  1125. assert_eq!(
  1126. Ok(Value::Integer(-1)),
  1127. run_command(&c, &["linsert", "foo", "after", "worldx", "there"]).await
  1128. );
  1129. assert_eq!(
  1130. Ok(Value::Integer(-1)),
  1131. run_command(&c, &["linsert", "foo", "before", "worldx", "there"]).await
  1132. );
  1133. }
  1134. #[tokio::test]
  1135. async fn llen() {
  1136. let c = create_connection();
  1137. assert_eq!(
  1138. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
  1139. run_command(&c, &["llen", "foo"]).await
  1140. );
  1141. assert_eq!(
  1142. Ok(Value::Integer(0)),
  1143. run_command(&c, &["llen", "foobar"]).await
  1144. );
  1145. }
  1146. #[tokio::test]
  1147. async fn lmove_1() {
  1148. let c = create_connection();
  1149. assert_eq!(
  1150. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
  1151. run_command(&c, &["llen", "foo"]).await
  1152. );
  1153. assert_eq!(
  1154. Ok(Value::Blob("1".into())),
  1155. run_command(&c, &["lmove", "foo", "bar", "left", "left"]).await
  1156. );
  1157. assert_eq!(
  1158. Ok(Value::Array(vec![Value::Blob("1".into()),])),
  1159. run_command(&c, &["lrange", "bar", "0", "-1"]).await
  1160. );
  1161. assert_eq!(
  1162. Ok(Value::Blob("5".into())),
  1163. run_command(&c, &["lmove", "foo", "bar", "right", "left"]).await
  1164. );
  1165. assert_eq!(
  1166. Ok(Value::Array(vec![
  1167. Value::Blob("5".into()),
  1168. Value::Blob("1".into()),
  1169. ])),
  1170. run_command(&c, &["lrange", "bar", "0", "-1"]).await
  1171. );
  1172. }
  1173. #[tokio::test]
  1174. async fn lpop() {
  1175. let c = create_connection();
  1176. assert_eq!(
  1177. Ok(Value::Integer(5)),
  1178. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
  1179. );
  1180. assert_eq!(
  1181. Ok(Value::Blob("5".into())),
  1182. run_command(&c, &["lpop", "foo"]).await
  1183. );
  1184. assert_eq!(
  1185. Ok(Value::Array(vec![Value::Blob("4".into())])),
  1186. run_command(&c, &["lpop", "foo", "1"]).await
  1187. );
  1188. assert_eq!(
  1189. Ok(Value::Array(vec![
  1190. Value::Blob("3".into()),
  1191. Value::Blob("2".into()),
  1192. Value::Blob("1".into()),
  1193. ])),
  1194. run_command(&c, &["lpop", "foo", "55"]).await
  1195. );
  1196. assert_eq!(
  1197. Ok(Value::Null),
  1198. run_command(&c, &["lpop", "foo", "55"]).await
  1199. );
  1200. assert_eq!(Ok(Value::Null), run_command(&c, &["lpop", "foo"]).await);
  1201. assert_eq!(
  1202. Ok(Value::Integer(0)),
  1203. run_command(&c, &["llen", "foobar"]).await
  1204. );
  1205. }
  1206. #[tokio::test]
  1207. async fn lpos_single_match() {
  1208. let c = create_connection();
  1209. assert_eq!(
  1210. Ok(Value::Integer(11)),
  1211. run_command(
  1212. &c,
  1213. &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
  1214. )
  1215. .await
  1216. );
  1217. assert_eq!(
  1218. Ok(Value::Integer(6)),
  1219. run_command(&c, &["lpos", "mylist", "3"]).await
  1220. );
  1221. }
  1222. #[tokio::test]
  1223. async fn lpos_with_negative_rank_with_count() {
  1224. let c = create_connection();
  1225. assert_eq!(
  1226. Ok(Value::Integer(8)),
  1227. run_command(
  1228. &c,
  1229. &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
  1230. )
  1231. .await
  1232. );
  1233. assert_eq!(
  1234. Ok(Value::Array(vec![Value::Integer(7), Value::Integer(6)])),
  1235. run_command(&c, &["lpos", "mylist", "c", "count", "2", "rank", "-1"]).await
  1236. );
  1237. }
  1238. #[tokio::test]
  1239. async fn lpos_with_negative_rank_with_count_max_len() {
  1240. let c = create_connection();
  1241. assert_eq!(
  1242. Ok(Value::Integer(8)),
  1243. run_command(
  1244. &c,
  1245. &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
  1246. )
  1247. .await
  1248. );
  1249. assert_eq!(
  1250. Ok(Value::Array(vec![Value::Integer(7), Value::Integer(6)])),
  1251. run_command(
  1252. &c,
  1253. &["lpos", "mylist", "c", "count", "0", "maxlen", "3", "rank", "-1"]
  1254. )
  1255. .await
  1256. );
  1257. }
  1258. #[tokio::test]
  1259. async fn lpos_rank_with_count() {
  1260. let c = create_connection();
  1261. assert_eq!(
  1262. Ok(Value::Integer(8)),
  1263. run_command(
  1264. &c,
  1265. &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
  1266. )
  1267. .await
  1268. );
  1269. assert_eq!(
  1270. Ok(Value::Array(vec![Value::Integer(6), Value::Integer(7)])),
  1271. run_command(&c, &["lpos", "mylist", "c", "count", "0", "rank", "2"]).await
  1272. );
  1273. }
  1274. #[tokio::test]
  1275. async fn lpos_all_settings() {
  1276. let c = create_connection();
  1277. assert_eq!(
  1278. Ok(Value::Integer(8)),
  1279. run_command(
  1280. &c,
  1281. &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
  1282. )
  1283. .await
  1284. );
  1285. assert_eq!(
  1286. Ok(Value::Array(vec![Value::Integer(6)])),
  1287. run_command(
  1288. &c,
  1289. &["lpos", "mylist", "c", "count", "0", "rank", "2", "maxlen", "7"]
  1290. )
  1291. .await
  1292. );
  1293. }
  1294. #[tokio::test]
  1295. async fn lpos_negative_rank() {
  1296. let c = create_connection();
  1297. assert_eq!(
  1298. Ok(Value::Integer(8)),
  1299. run_command(
  1300. &c,
  1301. &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
  1302. )
  1303. .await
  1304. );
  1305. assert_eq!(
  1306. Ok(Value::Integer(7)),
  1307. run_command(&c, &["lpos", "mylist", "c", "rank", "-1"]).await
  1308. );
  1309. }
  1310. #[tokio::test]
  1311. async fn lpos_single_skip() {
  1312. let c = create_connection();
  1313. assert_eq!(
  1314. Ok(Value::Integer(11)),
  1315. run_command(
  1316. &c,
  1317. &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
  1318. )
  1319. .await
  1320. );
  1321. assert_eq!(
  1322. Ok(Value::Integer(8)),
  1323. run_command(&c, &["lpos", "mylist", "3", "rank", "2"]).await
  1324. );
  1325. }
  1326. #[tokio::test]
  1327. async fn lpos_single_skip_max_len() {
  1328. let c = create_connection();
  1329. assert_eq!(
  1330. Ok(Value::Integer(11)),
  1331. run_command(
  1332. &c,
  1333. &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
  1334. )
  1335. .await
  1336. );
  1337. assert_eq!(
  1338. Ok(Value::Null),
  1339. run_command(&c, &["lpos", "mylist", "3", "rank", "2", "maxlen", "7"]).await
  1340. );
  1341. }
  1342. #[tokio::test]
  1343. async fn lpos_not_found() {
  1344. let c = create_connection();
  1345. assert_eq!(
  1346. Ok(Value::Array(vec![])),
  1347. run_command(&c, &["lpos", "mylist", "3", "count", "5", "maxlen", "9"]).await
  1348. );
  1349. assert_eq!(
  1350. Ok(Value::Null),
  1351. run_command(&c, &["lpos", "mylist", "3"]).await
  1352. );
  1353. }
  1354. #[tokio::test]
  1355. async fn lpos() {
  1356. let c = create_connection();
  1357. assert_eq!(
  1358. Ok(Value::Integer(11)),
  1359. run_command(
  1360. &c,
  1361. &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
  1362. )
  1363. .await
  1364. );
  1365. assert_eq!(
  1366. Ok(Value::Array(vec![Value::Integer(6), Value::Integer(8),])),
  1367. run_command(&c, &["lpos", "mylist", "3", "count", "5", "maxlen", "9"]).await
  1368. );
  1369. }
  1370. #[tokio::test]
  1371. async fn lpush() {
  1372. let c = create_connection();
  1373. assert_eq!(
  1374. Ok(Value::Integer(5)),
  1375. run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await
  1376. );
  1377. assert_eq!(
  1378. Ok(Value::Array(vec![
  1379. Value::Blob("5".into()),
  1380. Value::Blob("4".into()),
  1381. Value::Blob("3".into()),
  1382. Value::Blob("2".into()),
  1383. Value::Blob("1".into()),
  1384. ])),
  1385. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1386. );
  1387. assert_eq!(
  1388. Ok(Value::Integer(10)),
  1389. run_command(&c, &["lpush", "foo", "6", "7", "8", "9", "10"]).await
  1390. );
  1391. assert_eq!(
  1392. Ok(Value::Array(vec![
  1393. Value::Blob("10".into()),
  1394. Value::Blob("9".into()),
  1395. Value::Blob("8".into()),
  1396. Value::Blob("7".into()),
  1397. Value::Blob("6".into()),
  1398. Value::Blob("5".into()),
  1399. Value::Blob("4".into()),
  1400. Value::Blob("3".into()),
  1401. Value::Blob("2".into()),
  1402. Value::Blob("1".into()),
  1403. ])),
  1404. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1405. );
  1406. }
  1407. #[tokio::test]
  1408. async fn lpush_simple() {
  1409. let c = create_connection();
  1410. assert_eq!(
  1411. Ok(Value::Integer(1)),
  1412. run_command(&c, &["lpush", "foo", "world"]).await
  1413. );
  1414. assert_eq!(
  1415. Ok(Value::Integer(2)),
  1416. run_command(&c, &["lpush", "foo", "hello"]).await
  1417. );
  1418. assert_eq!(
  1419. Ok(Value::Array(vec![
  1420. Value::Blob("hello".into()),
  1421. Value::Blob("world".into()),
  1422. ])),
  1423. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1424. );
  1425. }
  1426. #[tokio::test]
  1427. async fn lset() {
  1428. let c = create_connection();
  1429. assert_eq!(
  1430. Ok(Value::Integer(5)),
  1431. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1432. );
  1433. assert_eq!(
  1434. Ok(Value::Ok),
  1435. run_command(&c, &["lset", "foo", "-1", "6"]).await,
  1436. );
  1437. assert_eq!(
  1438. Ok(Value::Ok),
  1439. run_command(&c, &["lset", "foo", "-2", "7"]).await,
  1440. );
  1441. assert_eq!(
  1442. Ok(Value::Ok),
  1443. run_command(&c, &["lset", "foo", "0", "8"]).await,
  1444. );
  1445. assert_eq!(
  1446. Err(Error::OutOfRange),
  1447. run_command(&c, &["lset", "foo", "55", "8"]).await,
  1448. );
  1449. assert_eq!(
  1450. Err(Error::OutOfRange),
  1451. run_command(&c, &["lset", "foo", "-55", "8"]).await,
  1452. );
  1453. assert_eq!(
  1454. Err(Error::NotFound),
  1455. run_command(&c, &["lset", "key_not_exists", "-55", "8"]).await,
  1456. );
  1457. assert_eq!(
  1458. Ok(Value::Blob("6".into())),
  1459. run_command(&c, &["rpop", "foo"]).await
  1460. );
  1461. assert_eq!(
  1462. Ok(Value::Blob("7".into())),
  1463. run_command(&c, &["rpop", "foo"]).await
  1464. );
  1465. assert_eq!(
  1466. Ok(Value::Blob("8".into())),
  1467. run_command(&c, &["lpop", "foo"]).await
  1468. );
  1469. }
  1470. #[tokio::test]
  1471. async fn ltrim() {
  1472. let c = create_connection();
  1473. assert_eq!(
  1474. Ok(Value::Integer(5)),
  1475. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1476. );
  1477. assert_eq!(
  1478. Ok(Value::Ok),
  1479. run_command(&c, &["ltrim", "foo", "1", "-2"]).await
  1480. );
  1481. assert_eq!(
  1482. Ok(Value::Array(vec![
  1483. Value::Blob("2".into()),
  1484. Value::Blob("3".into()),
  1485. Value::Blob("4".into()),
  1486. ])),
  1487. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1488. );
  1489. }
  1490. #[tokio::test]
  1491. async fn rpop() {
  1492. let c = create_connection();
  1493. assert_eq!(
  1494. Ok(Value::Integer(5)),
  1495. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1496. );
  1497. assert_eq!(
  1498. Ok(Value::Blob("5".into())),
  1499. run_command(&c, &["rpop", "foo"]).await
  1500. );
  1501. assert_eq!(
  1502. Ok(Value::Array(vec![Value::Blob("4".into())])),
  1503. run_command(&c, &["rpop", "foo", "1"]).await
  1504. );
  1505. assert_eq!(
  1506. Ok(Value::Array(vec![
  1507. Value::Blob("3".into()),
  1508. Value::Blob("2".into()),
  1509. Value::Blob("1".into()),
  1510. ])),
  1511. run_command(&c, &["rpop", "foo", "55"]).await
  1512. );
  1513. assert_eq!(
  1514. Ok(Value::Null),
  1515. run_command(&c, &["rpop", "foo", "55"]).await
  1516. );
  1517. assert_eq!(Ok(Value::Null), run_command(&c, &["rpop", "foo"]).await);
  1518. assert_eq!(
  1519. Ok(Value::Integer(0)),
  1520. run_command(&c, &["llen", "foobar"]).await
  1521. );
  1522. }
  1523. #[tokio::test]
  1524. async fn rpush_simple() {
  1525. let c = create_connection();
  1526. assert_eq!(
  1527. Ok(Value::Integer(1)),
  1528. run_command(&c, &["rpush", "foo", "world"]).await
  1529. );
  1530. assert_eq!(
  1531. Ok(Value::Integer(2)),
  1532. run_command(&c, &["rpush", "foo", "hello"]).await
  1533. );
  1534. assert_eq!(
  1535. Ok(Value::Array(vec![
  1536. Value::Blob("world".into()),
  1537. Value::Blob("hello".into()),
  1538. ])),
  1539. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1540. );
  1541. }
  1542. #[tokio::test]
  1543. async fn lrange() {
  1544. let c = create_connection();
  1545. assert_eq!(
  1546. Ok(Value::Integer(5)),
  1547. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1548. );
  1549. assert_eq!(
  1550. Ok(Value::Array(vec![
  1551. Value::Blob("1".into()),
  1552. Value::Blob("2".into()),
  1553. Value::Blob("3".into()),
  1554. Value::Blob("4".into()),
  1555. Value::Blob("5".into()),
  1556. ])),
  1557. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1558. );
  1559. assert_eq!(
  1560. Ok(Value::Array(vec![
  1561. Value::Blob("1".into()),
  1562. Value::Blob("2".into()),
  1563. Value::Blob("3".into()),
  1564. Value::Blob("4".into()),
  1565. ])),
  1566. run_command(&c, &["lrange", "foo", "0", "-2"]).await
  1567. );
  1568. assert_eq!(
  1569. Ok(Value::Array(vec![
  1570. Value::Blob("4".into()),
  1571. Value::Blob("5".into()),
  1572. ])),
  1573. run_command(&c, &["lrange", "foo", "-2", "-1"]).await
  1574. );
  1575. assert_eq!(
  1576. Ok(Value::Array(vec![Value::Blob("3".into()),])),
  1577. run_command(&c, &["lrange", "foo", "-3", "-3"]).await
  1578. );
  1579. }
  1580. #[tokio::test]
  1581. async fn rpush() {
  1582. let c = create_connection();
  1583. assert_eq!(
  1584. Ok(Value::Integer(5)),
  1585. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1586. );
  1587. assert_eq!(
  1588. Ok(Value::Array(vec![
  1589. Value::Blob("1".into()),
  1590. Value::Blob("2".into()),
  1591. Value::Blob("3".into()),
  1592. Value::Blob("4".into()),
  1593. Value::Blob("5".into()),
  1594. ])),
  1595. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1596. );
  1597. assert_eq!(
  1598. Ok(Value::Integer(10)),
  1599. run_command(&c, &["rpush", "foo", "6", "7", "8", "9", "10"]).await
  1600. );
  1601. assert_eq!(
  1602. Ok(Value::Array(vec![
  1603. Value::Blob("1".into()),
  1604. Value::Blob("2".into()),
  1605. Value::Blob("3".into()),
  1606. Value::Blob("4".into()),
  1607. Value::Blob("5".into()),
  1608. Value::Blob("6".into()),
  1609. Value::Blob("7".into()),
  1610. Value::Blob("8".into()),
  1611. Value::Blob("9".into()),
  1612. Value::Blob("10".into()),
  1613. ])),
  1614. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1615. );
  1616. }
  1617. #[tokio::test]
  1618. async fn rpushx() {
  1619. let c = create_connection();
  1620. assert_eq!(
  1621. Ok(Value::Integer(5)),
  1622. run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
  1623. );
  1624. assert_eq!(
  1625. Ok(Value::Array(vec![
  1626. Value::Blob("1".into()),
  1627. Value::Blob("2".into()),
  1628. Value::Blob("3".into()),
  1629. Value::Blob("4".into()),
  1630. Value::Blob("5".into()),
  1631. ])),
  1632. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1633. );
  1634. assert_eq!(
  1635. Ok(Value::Integer(10)),
  1636. run_command(&c, &["rpushx", "foo", "6", "7", "8", "9", "10"]).await
  1637. );
  1638. assert_eq!(
  1639. Ok(Value::Array(vec![
  1640. Value::Blob("1".into()),
  1641. Value::Blob("2".into()),
  1642. Value::Blob("3".into()),
  1643. Value::Blob("4".into()),
  1644. Value::Blob("5".into()),
  1645. Value::Blob("6".into()),
  1646. Value::Blob("7".into()),
  1647. Value::Blob("8".into()),
  1648. Value::Blob("9".into()),
  1649. Value::Blob("10".into()),
  1650. ])),
  1651. run_command(&c, &["lrange", "foo", "0", "-1"]).await
  1652. );
  1653. assert_eq!(
  1654. Ok(Value::Integer(0)),
  1655. run_command(&c, &["rpushx", "foobar", "6", "7", "8", "9", "10"]).await
  1656. );
  1657. }
  1658. #[tokio::test]
  1659. async fn lrange_test_1() {
  1660. let c = create_connection();
  1661. assert_eq!(
  1662. Ok(Value::Integer(10)),
  1663. run_command(
  1664. &c,
  1665. &[
  1666. "rpush",
  1667. "mylist",
  1668. "largevalue",
  1669. "1",
  1670. "2",
  1671. "3",
  1672. "4",
  1673. "5",
  1674. "6",
  1675. "7",
  1676. "8",
  1677. "9"
  1678. ]
  1679. )
  1680. .await
  1681. );
  1682. assert_eq!(
  1683. Ok(Value::Array(vec![
  1684. "1".into(),
  1685. "2".into(),
  1686. "3".into(),
  1687. "4".into(),
  1688. "5".into(),
  1689. "6".into(),
  1690. "7".into(),
  1691. "8".into()
  1692. ])),
  1693. run_command(&c, &["lrange", "mylist", "1", "-2"]).await
  1694. );
  1695. assert_eq!(
  1696. Ok(Value::Array(vec!["7".into(), "8".into(), "9".into()])),
  1697. run_command(&c, &["lrange", "mylist", "-3", "-1"]).await
  1698. );
  1699. assert_eq!(
  1700. Ok(Value::Array(vec!["4".into()])),
  1701. run_command(&c, &["lrange", "mylist", "4", "4"]).await
  1702. );
  1703. }
  1704. }