1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975 |
- //! # List command handlers
- use crate::{
- check_arg,
- connection::{Connection, ConnectionStatus, UnblockReason},
- db::utils::far_future,
- error::Error,
- try_get_arg, try_get_arg_str,
- value::bytes_to_number,
- value::checksum,
- value::Value,
- };
- use bytes::Bytes;
- use std::collections::VecDeque;
- use tokio::time::{sleep, Duration, Instant};
- #[allow(clippy::needless_range_loop)]
- /// Removes an element from a list
- #[inline]
- fn remove_element(
- conn: &Connection,
- key: &Bytes,
- limit: Option<usize>,
- front: bool,
- ) -> Result<Value, Error> {
- let db = conn.db();
- let mut new_len = 0;
- let result = db.get_map_or(
- key,
- |v| match v {
- Value::List(x) => {
- let mut x = x.write();
- let limit = if let Some(limit) = limit {
- limit
- } else {
- // Return a single element
- let ret = Ok((if front { x.pop_front() } else { x.pop_back() })
- .map_or(Value::Null, |x| x.clone_value()));
- new_len = x.len();
- return ret;
- };
- let mut ret = vec![None; limit];
- for i in 0..limit {
- if front {
- ret[i] = x.pop_front();
- } else {
- ret[i] = x.pop_back();
- }
- }
- new_len = x.len();
- Ok(ret
- .iter()
- .flatten()
- .map(|m| m.clone_value())
- .collect::<Vec<Value>>()
- .into())
- }
- _ => Err(Error::WrongType),
- },
- || Ok(Value::Null),
- )?;
- if new_len == 0 {
- let _ = db.del(&[key.clone()]);
- } else {
- db.bump_version(key);
- }
- Ok(result)
- }
- #[inline]
- /// Handles the timeout/sleep logic for all blocking commands.
- async fn handle_timeout(conn: &Connection, timeout: Option<Instant>) -> Result<bool, Error> {
- if let Some(timeout) = timeout {
- if Instant::now() >= timeout {
- conn.unblock(UnblockReason::Timeout);
- return Ok(true);
- }
- }
- if let Some(reason) = conn.has_been_unblocked_externally() {
- match reason {
- UnblockReason::Error => Err(Error::UnblockByError),
- _ => Ok(true),
- }
- } else {
- sleep(Duration::from_millis(100)).await;
- Ok(false)
- }
- }
- /// Parses timeout and returns an instant or none if it should wait forever.
- #[inline]
- fn parse_timeout(arg: &Bytes) -> Result<Option<Instant>, Error> {
- let raw_timeout = bytes_to_number::<f64>(arg)?;
- if raw_timeout < 0f64 {
- return Err(Error::NegativeNumber("timeout".to_owned()));
- }
- if raw_timeout == 0.0 {
- return Ok(None);
- }
- Ok(Some(
- Instant::now()
- .checked_add(Duration::from_millis(
- (raw_timeout * 1_000f64).round() as u64
- ))
- .unwrap_or_else(far_future),
- ))
- }
- /// BLPOP is a blocking list pop primitive. It is the blocking version of LPOP because it blocks
- /// the connection when there are no elements to pop from any of the given lists. An element is
- /// popped from the head of the first list that is non-empty, with the given keys being checked in
- /// the order that they are given.
- pub async fn blpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let blpop_task = |conn: &Connection, args: &[Bytes]| -> Result<Value, Error> {
- for key in (1..args.len() - 1) {
- let key = &args[key];
- match remove_element(&conn, key, None, true)? {
- Value::Null => (),
- n => return Ok(vec![Value::new(&key), n].into()),
- };
- }
- Ok(Value::Null)
- };
- if conn.is_executing_tx() {
- return blpop_task(conn, args);
- }
- let timeout = parse_timeout(&args[args.len() - 1])?;
- let conn = conn.clone();
- let args = args.to_vec();
- conn.block();
- tokio::spawn(async move {
- loop {
- match blpop_task(&conn, &args) {
- Ok(Value::Null) => {}
- Ok(x) => {
- conn.append_response(x);
- conn.unblock(UnblockReason::Finished);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- conn.unblock(UnblockReason::Finished);
- break;
- }
- }
- match handle_timeout(&conn, timeout).await {
- Ok(true) => {
- conn.append_response(Value::Null);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- break;
- }
- _ => {}
- }
- }
- });
- Ok(Value::Ignore)
- }
- /// BLMOVE is the blocking variant of LMOVE. When source contains elements, this
- /// command behaves exactly like LMOVE. When used inside a MULTI/EXEC block,
- /// this command behaves exactly like LMOVE. When source is empty, Redis will
- /// block the connection until another client pushes to it or until timeout (a
- /// double value specifying the maximum number of seconds to block) is reached.
- /// A timeout of zero can be used to block indefinitely.
- ///
- /// This command comes in place of the now deprecated BRPOPLPUSH. Doing BLMOVE
- /// RIGHT LEFT is equivalent.
- ///
- /// See LMOVE for more information.
- pub async fn blmove(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- if conn.is_executing_tx() {
- return lmove(&conn, &args).await;
- }
- let timeout = parse_timeout(&args[5])?;
- conn.block();
- let conn = conn.clone();
- let args = args.to_vec();
- tokio::spawn(async move {
- loop {
- match lmove(&conn, &args).await {
- Ok(Value::Null) => (),
- Ok(n) => {
- conn.append_response(n);
- conn.unblock(UnblockReason::Finished);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- conn.unblock(UnblockReason::Finished);
- break;
- }
- };
- match handle_timeout(&conn, timeout).await {
- Ok(true) => {
- conn.append_response(Value::Null);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- break;
- }
- _ => {}
- }
- }
- });
- Ok(Value::Ignore)
- }
- /// BRPOPLPUSH is the blocking variant of RPOPLPUSH. When source contains
- /// elements, this command behaves exactly like RPOPLPUSH. When used inside a
- /// MULTI/EXEC block, this command behaves exactly like RPOPLPUSH. When source
- /// is empty, Redis will block the connection until another client pushes to it
- /// or until timeout is reached. A timeout of zero can be used to block
- /// indefinitely.
- pub async fn brpoplpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- blmove(
- conn,
- &[
- "blmove".into(),
- args[1].clone(),
- args[2].clone(),
- "RIGHT".into(),
- "LEFT".into(),
- args[3].clone(),
- ],
- )
- .await
- }
- /// BRPOP is a blocking list pop primitive. It is the blocking version of RPOP because it blocks
- /// the connection when there are no elements to pop from any of the given lists. An element is
- /// popped from the tail of the first list that is non-empty, with the given keys being checked in
- /// the order that they are given.
- pub async fn brpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let brpop_task = |conn: &Connection, args: &[Bytes]| -> Result<Value, Error> {
- for key in (1..args.len() - 1) {
- let key = &args[key];
- match remove_element(&conn, key, None, false)? {
- Value::Null => (),
- n => return Ok(vec![Value::new(&key), n].into()),
- };
- }
- Ok(Value::Null)
- };
- if conn.is_executing_tx() {
- return brpop_task(conn, args);
- }
- let timeout = parse_timeout(&args[args.len() - 1])?;
- let conn = conn.clone();
- let args = args.to_vec();
- conn.block();
- tokio::spawn(async move {
- loop {
- match brpop_task(&conn, &args) {
- Ok(Value::Null) => {}
- Ok(x) => {
- conn.append_response(x);
- conn.unblock(UnblockReason::Finished);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- conn.unblock(UnblockReason::Finished);
- break;
- }
- }
- match handle_timeout(&conn, timeout).await {
- Ok(true) => {
- conn.append_response(Value::Null);
- break;
- }
- Err(x) => {
- conn.append_response(x.into());
- break;
- }
- _ => {}
- }
- }
- });
- Ok(Value::Ignore)
- }
- /// Returns the element at index index in the list stored at key. The index is zero-based, so 0
- /// means the first element, 1 the second element and so on. Negative indices can be used to
- /// designate elements starting at the tail of the list. Here, -1 means the last element, -2 means
- /// the penultimate and so forth.
- pub async fn lindex(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let mut index: i64 = bytes_to_number(&args[2])?;
- let x = x.read();
- let index = if index < 0 {
- x.len()
- .checked_sub((index * -1) as usize)
- .unwrap_or(x.len())
- } else {
- index as usize
- };
- Ok(x.get(index).map_or(Value::Null, |x| x.clone_value()))
- }
- _ => Err(Error::WrongType),
- },
- || Ok(Value::Null),
- )
- }
- /// Inserts element in the list stored at key either before or after the reference value pivot.
- ///
- /// When key does not exist, it is considered an empty list and no operation is performed.
- pub async fn linsert(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let is_before = if check_arg!(args, 2, "BEFORE") {
- true
- } else if check_arg!(args, 2, "AFTER") {
- false
- } else {
- return Err(Error::Syntax);
- };
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let pivot = checksum::Ref::new(&args[3]);
- let mut x = x.write();
- let mut found = false;
- for (key, val) in x.iter().enumerate() {
- if *val == pivot {
- let id = if is_before { key } else { key + 1 };
- let value = checksum::Value::new(args[4].clone());
- if id > x.len() {
- x.push_back(value);
- } else {
- x.insert(id as usize, value);
- }
- found = true;
- break;
- }
- }
- if found {
- Ok(x.len().into())
- } else {
- Ok((-1).into())
- }
- }
- _ => Err(Error::WrongType),
- },
- || Ok(0.into()),
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Returns the length of the list stored at key. If key does not exist, it is interpreted as an
- /// empty list and 0 is returned. An error is returned when the value stored at key is not a list.
- pub async fn llen(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => Ok(x.read().len().into()),
- _ => Err(Error::WrongType),
- },
- || Ok(0.into()),
- )
- }
- /// Atomically returns and removes the first/last element (head/tail depending on the wherefrom
- /// argument) of the list stored at source, and pushes the element at the first/last element
- /// (head/tail depending on the whereto argument) of the list stored at destination.
- pub async fn lmove(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let source_is_left = if check_arg!(args, 3, "LEFT") {
- true
- } else if check_arg!(args, 3, "RIGHT") {
- false
- } else {
- return Err(Error::Syntax);
- };
- let target_is_left = if check_arg!(args, 4, "LEFT") {
- true
- } else if check_arg!(args, 4, "RIGHT") {
- false
- } else {
- return Err(Error::Syntax);
- };
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(source) => conn.db().get_map_or(
- &args[2],
- |v| match v {
- Value::List(target) => {
- let element = if source_is_left {
- source.write().pop_front()
- } else {
- source.write().pop_back()
- };
- if let Some(element) = element {
- let ret = element.clone_value();
- if target_is_left {
- target.write().push_front(element);
- } else {
- target.write().push_back(element);
- }
- Ok(ret)
- } else {
- Ok(Value::Null)
- }
- }
- _ => Err(Error::WrongType),
- },
- || {
- let element = if source_is_left {
- source.write().pop_front()
- } else {
- source.write().pop_back()
- };
- if let Some(element) = element {
- let ret = element.clone_value();
- let mut h = VecDeque::new();
- h.push_front(element);
- conn.db().set(&args[2], h.into(), None);
- Ok(ret)
- } else {
- Ok(Value::Null)
- }
- },
- ),
- _ => Err(Error::WrongType),
- },
- || Ok(Value::Null),
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Removes and returns the first elements of the list stored at key.
- ///
- /// By default, the command pops a single element from the beginning of the list. When provided
- /// with the optional count argument, the reply will consist of up to count elements, depending on
- /// the list's length.
- pub async fn lpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let count = match args.get(2) {
- Some(v) => Some(bytes_to_number(&v)?),
- None => None,
- };
- remove_element(conn, &args[1], count, true)
- }
- /// The command returns the index of matching elements inside a Redis list. By default, when no
- /// options are given, it will scan the list from head to tail, looking for the first match of
- /// "element". If the element is found, its index (the zero-based position in the list) is
- /// returned. Otherwise, if no match is found, nil is returned.
- pub async fn lpos(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let element = checksum::Ref::new(&args[2]);
- let mut rank = None;
- let mut count = None;
- let mut max_len = None;
- let mut index = 3;
- loop {
- if args.len() <= index {
- break;
- }
- let next = try_get_arg!(args, index + 1);
- match try_get_arg_str!(args, index).to_uppercase().as_str() {
- "RANK" => rank = Some(bytes_to_number::<i64>(&next)?),
- "COUNT" => count = Some(bytes_to_number::<usize>(&next)?),
- "MAXLEN" => max_len = Some(bytes_to_number::<usize>(&next)?),
- _ => return Err(Error::Syntax),
- }
- index += 2;
- }
- let (must_reverse, rank) = if let Some(rank) = rank {
- if rank == 0 {
- return Err(Error::InvalidRank("RANK".to_owned()));
- }
- if rank < 0 {
- (true, Some((rank * -1) as usize))
- } else {
- (false, Some(rank as usize))
- }
- } else {
- (false, None)
- };
- let max_len = max_len.unwrap_or_default();
- conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let x = x.read();
- let mut result: Vec<Value> = vec![];
- let mut values = x
- .iter()
- .enumerate()
- .collect::<Vec<(usize, &checksum::Value)>>();
- if must_reverse {
- values.reverse();
- }
- let mut checks = 1;
- for (id, val) in values.iter() {
- if **val == element {
- // Match!
- if let Some(count) = count {
- result.push((*id).into());
- if result.len() == count && count != 0 && rank.is_none() {
- // There is no point in keep looping. No RANK provided, COUNT is not 0
- // therefore we can return the vector of result as IS
- return Ok(result.into());
- }
- } else if let Some(rank) = rank {
- result.push((*id).into());
- if result.len() == rank {
- return Ok((*id).into());
- }
- } else {
- // return first match!
- return Ok((*id).into());
- }
- }
- if checks == max_len {
- break;
- }
- checks += 1;
- }
- if let Some(rank) = rank {
- let rank = rank - 1;
- let result = if rank < result.len() {
- (&result[rank..]).to_vec()
- } else {
- vec![]
- };
- return Ok(if let Some(count) = count {
- if count > 0 && count < result.len() {
- (&result[0..count]).to_vec().into()
- } else {
- result.to_vec().into()
- }
- } else {
- result
- .to_vec()
- .get(0)
- .map(|c| c.clone())
- .unwrap_or_default()
- });
- }
- if count.is_some() {
- Ok(result.into())
- } else {
- Ok(Value::Null)
- }
- }
- _ => Err(Error::WrongType),
- },
- || {
- Ok(if count.is_some() {
- Value::Array(vec![])
- } else {
- Value::Null
- })
- },
- )
- }
- /// Insert all the specified values at the head of the list stored at key. If key does not exist,
- /// it is created as empty list before performing the push operations. When key holds a value that
- /// is not a list, an error is returned.
- ///
- /// It is possible to push multiple elements using a single command call just specifying multiple
- /// arguments at the end of the command. Elements are inserted one after the other to the head of
- /// the list, from the leftmost element to the rightmost element. So for instance the command LPUSH
- /// mylist a b c will result into a list containing c as first element, b as second element and a
- /// as third element.
- pub async fn lpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let is_push_x = check_arg!(args, 0, "LPUSHX");
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let mut x = x.write();
- for val in args.iter().skip(2) {
- x.push_front(checksum::Value::new(val.clone()));
- }
- Ok(x.len().into())
- }
- _ => Err(Error::WrongType),
- },
- || {
- if is_push_x {
- return Ok(0.into());
- }
- let mut h = VecDeque::new();
- for val in args.iter().skip(2) {
- h.push_front(checksum::Value::new(val.clone()));
- }
- let len = h.len();
- conn.db().set(&args[1], h.into(), None);
- Ok(len.into())
- },
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Returns the specified elements of the list stored at key. The offsets start and stop are
- /// zero-based indexes, with 0 being the first element of the list (the head of the list), 1 being
- /// the next element and so on.
- ///
- /// These offsets can also be negative numbers indicating offsets starting at the end of the list.
- /// For example, -1 is the last element of the list, -2 the penultimate, and so on.
- pub async fn lrange(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let start: i64 = bytes_to_number(&args[2])?;
- let end: i64 = bytes_to_number(&args[3])?;
- let mut ret = vec![];
- let x = x.read();
- let start = if start < 0 {
- x.len()
- .checked_sub((start * -1) as usize)
- .unwrap_or_default()
- } else {
- (start as usize)
- };
- let end = if end < 0 {
- if let Some(x) = x.len().checked_sub((end * -1) as usize) {
- x
- } else {
- return Ok(Value::Array((vec![])));
- }
- } else {
- end as usize
- };
- for (i, val) in x.iter().enumerate().skip(start) {
- if i > end {
- break;
- }
- ret.push(val.clone_value());
- }
- Ok(ret.into())
- }
- _ => Err(Error::WrongType),
- },
- || Ok(Value::Array(vec![])),
- )
- }
- /// Removes the first count occurrences of elements equal to element from the list stored at key
- pub async fn lrem(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let element = checksum::Ref::new(&args[3]);
- let limit: i64 = bytes_to_number(&args[2])?;
- let mut x = x.write();
- let (is_reverse, limit) = if limit < 0 {
- (true, -limit)
- } else {
- (false, limit)
- };
- let mut keep = vec![true; x.len()];
- let mut removed = 0;
- let len = x.len();
- for i in 0..len {
- let i = if is_reverse { len - 1 - i } else { i };
- if let Some(value) = x.get(i) {
- if *value == element {
- keep[i] = false;
- removed += 1;
- if removed == limit {
- break;
- }
- }
- }
- }
- let mut i = 0;
- x.retain(|_| {
- i += 1;
- keep[i - 1]
- });
- Ok(removed.into())
- }
- _ => Err(Error::WrongType),
- },
- || Ok(0.into()),
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Sets the list element at index to element. For more information on the index argument, see
- /// LINDEX.
- ///
- /// An error is returned for out of range indexes.
- pub async fn lset(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let mut index: i64 = bytes_to_number(&args[2])?;
- let mut x = x.write();
- if index < 0 {
- index += x.len() as i64;
- }
- if let Some(x) = x.get_mut(index as usize) {
- *x = checksum::Value::new(args[3].clone());
- Ok(Value::Ok)
- } else {
- Err(Error::OutOfRange)
- }
- }
- _ => Err(Error::WrongType),
- },
- || Err(Error::NotFound),
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Trim an existing list so that it will contain only the specified range of elements specified.
- /// Both start and stop are zero-based indexes, where 0 is the first element of the list (the
- /// head), 1 the next element and so on.
- pub async fn ltrim(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let mut start: i64 = bytes_to_number(&args[2])?;
- let mut end: i64 = bytes_to_number(&args[3])?;
- let mut x = x.write();
- if start < 0 {
- start += x.len() as i64;
- }
- if end < 0 {
- end += x.len() as i64;
- }
- let mut i = 0;
- x.retain(|_| {
- let retain = i >= start && i <= end;
- i += 1;
- retain
- });
- Ok(Value::Ok)
- }
- _ => Err(Error::WrongType),
- },
- || Ok(Value::Ok),
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- /// Removes and returns the last elements of the list stored at key.
- ///
- /// By default, the command pops a single element from the end of the list. When provided with the
- /// optional count argument, the reply will consist of up to count elements, depending on the
- /// list's length.
- pub async fn rpop(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let count = match args.get(2) {
- Some(v) => Some(bytes_to_number(&v)?),
- None => None,
- };
- remove_element(conn, &args[1], count, false)
- }
- /// Atomically returns and removes the last element (tail) of the list stored at source, and pushes
- /// the element at the first element (head) of the list stored at destination.
- pub async fn rpoplpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- lmove(
- conn,
- &[
- "lmove".into(),
- args[1].clone(),
- args[2].clone(),
- "RIGHT".into(),
- "LEFT".into(),
- ],
- )
- .await
- }
- /// Insert all the specified values at the tail of the list stored at key. If key does not exist,
- /// it is created as empty list before performing the push operation. When key holds a value that
- /// is not a list, an error is returned.
- pub async fn rpush(conn: &Connection, args: &[Bytes]) -> Result<Value, Error> {
- let is_push_x = check_arg!(args, 0, "RPUSHX");
- let result = conn.db().get_map_or(
- &args[1],
- |v| match v {
- Value::List(x) => {
- let mut x = x.write();
- for val in args.iter().skip(2) {
- x.push_back(checksum::Value::new(val.clone()));
- }
- Ok(x.len().into())
- }
- _ => Err(Error::WrongType),
- },
- || {
- if is_push_x {
- return Ok(0.into());
- }
- let mut h = VecDeque::new();
- for val in args.iter().skip(2) {
- h.push_back(checksum::Value::new(val.clone()));
- }
- let len = h.len();
- conn.db().set(&args[1], h.into(), None);
- Ok(len.into())
- },
- )?;
- conn.db().bump_version(&args[1]);
- Ok(result)
- }
- #[cfg(test)]
- mod test {
- use crate::{
- cmd::test::{create_connection, run_command},
- error::Error,
- value::Value,
- };
- use tokio::time::{sleep, Duration, Instant};
- #[tokio::test]
- async fn blpop_no_waiting() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("foo".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["blpop", "foo", "1"]).await
- );
- }
- #[tokio::test]
- async fn blpop_timeout() {
- let c = create_connection();
- let x = Instant::now();
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["blpop", "foobar", "1"]).await
- );
- assert!(Instant::now() - x <= Duration::from_millis(1000));
- }
- #[tokio::test]
- async fn blpop_wait_insert() {
- let c = create_connection();
- let x = Instant::now();
- // Query command that will block connection until some data is inserted
- // to foobar, foo, bar or the 5 seconds timeout happens.
- //
- // We are issuing the command, sleeping a little bit then adding data to
- // foobar, before actually waiting on the result.
- let waiting = run_command(&c, &["blpop", "foobar", "foo", "bar", "5"]);
- // Sleep 1 second before inserting new data
- sleep(Duration::from_millis(1000)).await;
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
- );
- // Read the output of the first blpop command now.
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("foo".into()),
- Value::Blob("5".into()),
- ])),
- waiting.await
- );
- assert!(Instant::now() - x > Duration::from_millis(1000));
- assert!(Instant::now() - x < Duration::from_millis(5000));
- }
- #[tokio::test]
- async fn lrem_1() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(
- &c,
- &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(3)),
- run_command(&c, &["lrem", "mylist", "3", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("world".into()),
- Value::Blob("hello".into()),
- ])),
- run_command(&c, &["lrange", "mylist", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lrem_2() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(
- &c,
- &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["lrem", "mylist", "-2", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("hello".into()),
- Value::Blob("world".into()),
- ])),
- run_command(&c, &["lrange", "mylist", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(1)),
- run_command(&c, &["lrem", "mylist", "1", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("world".into()),
- ])),
- run_command(&c, &["lrange", "mylist", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lrem_3() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(
- &c,
- &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(4)),
- run_command(&c, &["lrem", "mylist", "-100", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("world".into()),])),
- run_command(&c, &["lrange", "mylist", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lrem_4() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(
- &c,
- &["rpush", "mylist", "hello", "hello", "world", "hello", "hello"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(4)),
- run_command(&c, &["lrem", "mylist", "100", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("world".into()),])),
- run_command(&c, &["lrange", "mylist", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn brpop_no_waiting() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("foo".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["brpop", "foo", "1"]).await
- );
- }
- #[tokio::test]
- async fn brpop_timeout() {
- let c = create_connection();
- let x = Instant::now();
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["brpop", "foobar", "1"]).await
- );
- assert!(Instant::now() - x < Duration::from_millis(1000));
- }
- #[tokio::test]
- async fn brpop_wait_insert() {
- let c = create_connection();
- let x = Instant::now();
- // Query command that will block connection until some data is inserted
- // to foobar, foo, bar or the 5 seconds timeout happens.
- //
- // We are issuing the command, sleeping a little bit then adding data to
- // foobar, before actually waiting on the result.
- let waiting = run_command(&c, &["brpop", "foobar", "foo", "bar", "5"]);
- // Sleep 1 second before inserting new data
- sleep(Duration::from_millis(1000)).await;
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
- );
- // Read the output of the first blpop command now.
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("foo".into()),
- Value::Blob("5".into()),
- ])),
- waiting.await
- );
- assert!(Instant::now() - x > Duration::from_millis(1000));
- assert!(Instant::now() - x < Duration::from_millis(5000));
- }
- #[tokio::test]
- async fn lindex() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("5".into()),
- Value::Blob("4".into()),
- Value::Blob("3".into()),
- Value::Blob("2".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Blob("5".into())),
- run_command(&c, &["lindex", "foo", "0"]).await
- );
- assert_eq!(
- Ok(Value::Blob("1".into())),
- run_command(&c, &["lindex", "foo", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["lindex", "foo", "-100"]).await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["lindex", "foo", "100"]).await
- );
- }
- #[tokio::test]
- async fn linsert_syntax_err() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello", "world"]).await
- );
- assert_eq!(
- Err(Error::Syntax),
- run_command(&c, &["linsert", "foo", "beforex", "world", "there"]).await
- );
- }
- #[tokio::test]
- async fn linsert_before() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(3)),
- run_command(&c, &["linsert", "foo", "before", "world", "there"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("there".into()),
- Value::Blob("world".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await,
- );
- }
- #[tokio::test]
- async fn linsert_after() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(3)),
- run_command(&c, &["linsert", "foo", "after", "world", "there"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("world".into()),
- Value::Blob("there".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await,
- );
- }
- #[tokio::test]
- async fn linsert_before_after() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(3)),
- run_command(&c, &["linsert", "foo", "after", "world", "there1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(4)),
- run_command(&c, &["linsert", "foo", "before", "world", "there2"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("there2".into()),
- Value::Blob("world".into()),
- Value::Blob("there1".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await,
- );
- }
- #[tokio::test]
- async fn linsert_not_found() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(-1)),
- run_command(&c, &["linsert", "foo", "after", "worldx", "there"]).await
- );
- assert_eq!(
- Ok(Value::Integer(-1)),
- run_command(&c, &["linsert", "foo", "before", "worldx", "there"]).await
- );
- }
- #[tokio::test]
- async fn llen() {
- let c = create_connection();
- assert_eq!(
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
- run_command(&c, &["llen", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Integer(0)),
- run_command(&c, &["llen", "foobar"]).await
- );
- }
- #[tokio::test]
- async fn lmove_1() {
- let c = create_connection();
- assert_eq!(
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await,
- run_command(&c, &["llen", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Blob("1".into())),
- run_command(&c, &["lmove", "foo", "bar", "left", "left"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("1".into()),])),
- run_command(&c, &["lrange", "bar", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Blob("5".into())),
- run_command(&c, &["lmove", "foo", "bar", "right", "left"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("5".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["lrange", "bar", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lpop() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await,
- );
- assert_eq!(
- Ok(Value::Blob("5".into())),
- run_command(&c, &["lpop", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("4".into())])),
- run_command(&c, &["lpop", "foo", "1"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("3".into()),
- Value::Blob("2".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["lpop", "foo", "55"]).await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["lpop", "foo", "55"]).await
- );
- assert_eq!(Ok(Value::Null), run_command(&c, &["lpop", "foo"]).await);
- assert_eq!(
- Ok(Value::Integer(0)),
- run_command(&c, &["llen", "foobar"]).await
- );
- }
- #[tokio::test]
- async fn lpos_single_match() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(11)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(6)),
- run_command(&c, &["lpos", "mylist", "3"]).await
- );
- }
- #[tokio::test]
- async fn lpos_with_negative_rank_with_count() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Integer(7), Value::Integer(6)])),
- run_command(&c, &["lpos", "mylist", "c", "count", "2", "rank", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lpos_with_negative_rank_with_count_max_len() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Integer(7), Value::Integer(6)])),
- run_command(
- &c,
- &["lpos", "mylist", "c", "count", "0", "maxlen", "3", "rank", "-1"]
- )
- .await
- );
- }
- #[tokio::test]
- async fn lpos_rank_with_count() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Integer(6), Value::Integer(7)])),
- run_command(&c, &["lpos", "mylist", "c", "count", "0", "rank", "2"]).await
- );
- }
- #[tokio::test]
- async fn lpos_all_settings() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Integer(6)])),
- run_command(
- &c,
- &["lpos", "mylist", "c", "count", "0", "rank", "2", "maxlen", "7"]
- )
- .await
- );
- }
- #[tokio::test]
- async fn lpos_negative_rank() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "1", "2", "3", "c", "c"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(7)),
- run_command(&c, &["lpos", "mylist", "c", "rank", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lpos_single_skip() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(11)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Integer(8)),
- run_command(&c, &["lpos", "mylist", "3", "rank", "2"]).await
- );
- }
- #[tokio::test]
- async fn lpos_single_skip_max_len() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(11)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["lpos", "mylist", "3", "rank", "2", "maxlen", "7"]).await
- );
- }
- #[tokio::test]
- async fn lpos_not_found() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Array(vec![])),
- run_command(&c, &["lpos", "mylist", "3", "count", "5", "maxlen", "9"]).await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["lpos", "mylist", "3"]).await
- );
- }
- #[tokio::test]
- async fn lpos() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(11)),
- run_command(
- &c,
- &["RPUSH", "mylist", "a", "b", "c", "d", "1", "2", "3", "4", "3", "3", "3"]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Integer(6), Value::Integer(8),])),
- run_command(&c, &["lpos", "mylist", "3", "count", "5", "maxlen", "9"]).await
- );
- }
- #[tokio::test]
- async fn lpush() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["lpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("5".into()),
- Value::Blob("4".into()),
- Value::Blob("3".into()),
- Value::Blob("2".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(10)),
- run_command(&c, &["lpush", "foo", "6", "7", "8", "9", "10"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("10".into()),
- Value::Blob("9".into()),
- Value::Blob("8".into()),
- Value::Blob("7".into()),
- Value::Blob("6".into()),
- Value::Blob("5".into()),
- Value::Blob("4".into()),
- Value::Blob("3".into()),
- Value::Blob("2".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lpush_simple() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(1)),
- run_command(&c, &["lpush", "foo", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["lpush", "foo", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("hello".into()),
- Value::Blob("world".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lset() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Ok),
- run_command(&c, &["lset", "foo", "-1", "6"]).await,
- );
- assert_eq!(
- Ok(Value::Ok),
- run_command(&c, &["lset", "foo", "-2", "7"]).await,
- );
- assert_eq!(
- Ok(Value::Ok),
- run_command(&c, &["lset", "foo", "0", "8"]).await,
- );
- assert_eq!(
- Err(Error::OutOfRange),
- run_command(&c, &["lset", "foo", "55", "8"]).await,
- );
- assert_eq!(
- Err(Error::OutOfRange),
- run_command(&c, &["lset", "foo", "-55", "8"]).await,
- );
- assert_eq!(
- Err(Error::NotFound),
- run_command(&c, &["lset", "key_not_exists", "-55", "8"]).await,
- );
- assert_eq!(
- Ok(Value::Blob("6".into())),
- run_command(&c, &["rpop", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Blob("7".into())),
- run_command(&c, &["rpop", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Blob("8".into())),
- run_command(&c, &["lpop", "foo"]).await
- );
- }
- #[tokio::test]
- async fn ltrim() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Ok),
- run_command(&c, &["ltrim", "foo", "1", "-2"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn rpop() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Blob("5".into())),
- run_command(&c, &["rpop", "foo"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("4".into())])),
- run_command(&c, &["rpop", "foo", "1"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("3".into()),
- Value::Blob("2".into()),
- Value::Blob("1".into()),
- ])),
- run_command(&c, &["rpop", "foo", "55"]).await
- );
- assert_eq!(
- Ok(Value::Null),
- run_command(&c, &["rpop", "foo", "55"]).await
- );
- assert_eq!(Ok(Value::Null), run_command(&c, &["rpop", "foo"]).await);
- assert_eq!(
- Ok(Value::Integer(0)),
- run_command(&c, &["llen", "foobar"]).await
- );
- }
- #[tokio::test]
- async fn rpush_simple() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(1)),
- run_command(&c, &["rpush", "foo", "world"]).await
- );
- assert_eq!(
- Ok(Value::Integer(2)),
- run_command(&c, &["rpush", "foo", "hello"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("world".into()),
- Value::Blob("hello".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn lrange() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-2"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["lrange", "foo", "-2", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![Value::Blob("3".into()),])),
- run_command(&c, &["lrange", "foo", "-3", "-3"]).await
- );
- }
- #[tokio::test]
- async fn rpush() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(10)),
- run_command(&c, &["rpush", "foo", "6", "7", "8", "9", "10"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- Value::Blob("6".into()),
- Value::Blob("7".into()),
- Value::Blob("8".into()),
- Value::Blob("9".into()),
- Value::Blob("10".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- }
- #[tokio::test]
- async fn rpushx() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(5)),
- run_command(&c, &["rpush", "foo", "1", "2", "3", "4", "5"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(10)),
- run_command(&c, &["rpushx", "foo", "6", "7", "8", "9", "10"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- Value::Blob("1".into()),
- Value::Blob("2".into()),
- Value::Blob("3".into()),
- Value::Blob("4".into()),
- Value::Blob("5".into()),
- Value::Blob("6".into()),
- Value::Blob("7".into()),
- Value::Blob("8".into()),
- Value::Blob("9".into()),
- Value::Blob("10".into()),
- ])),
- run_command(&c, &["lrange", "foo", "0", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Integer(0)),
- run_command(&c, &["rpushx", "foobar", "6", "7", "8", "9", "10"]).await
- );
- }
- #[tokio::test]
- async fn lrange_test_1() {
- let c = create_connection();
- assert_eq!(
- Ok(Value::Integer(10)),
- run_command(
- &c,
- &[
- "rpush",
- "mylist",
- "largevalue",
- "1",
- "2",
- "3",
- "4",
- "5",
- "6",
- "7",
- "8",
- "9"
- ]
- )
- .await
- );
- assert_eq!(
- Ok(Value::Array(vec![
- "1".into(),
- "2".into(),
- "3".into(),
- "4".into(),
- "5".into(),
- "6".into(),
- "7".into(),
- "8".into()
- ])),
- run_command(&c, &["lrange", "mylist", "1", "-2"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec!["7".into(), "8".into(), "9".into()])),
- run_command(&c, &["lrange", "mylist", "-3", "-1"]).await
- );
- assert_eq!(
- Ok(Value::Array(vec!["4".into()])),
- run_command(&c, &["lrange", "mylist", "4", "4"]).await
- );
- }
- }
|