Class: Redis::Connection::Memory

Inherits:
Object
  • Object
show all
Includes:
BitopCommand, CommandExecutor, FakeRedis, CommandHelper, SortMethod, TransactionCommands
Defined in:
lib/redis/connection/memory.rb

Constant Summary

Constants included from FakeRedis

FakeRedis::Redis, FakeRedis::TRANSACTION_COMMANDS, FakeRedis::VERSION

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from FakeRedis

disable, enable, enabled?

Constructor Details

#initialize(options = {}) ⇒ Memory

Returns a new instance of Memory.



52
53
54
# File 'lib/redis/connection/memory.rb', line 52

def initialize(options = {})
  self.options = options
end

Instance Attribute Details

#database_idObject



56
57
58
# File 'lib/redis/connection/memory.rb', line 56

def database_id
  @database_id ||= 0
end

#optionsObject

Returns the value of attribute options.



23
24
25
# File 'lib/redis/connection/memory.rb', line 23

def options
  @options
end

#repliesObject



77
78
79
# File 'lib/redis/connection/memory.rb', line 77

def replies
  @replies ||= []
end

Class Method Details

.channelsObject



40
41
42
# File 'lib/redis/connection/memory.rb', line 40

def self.channels
  @channels ||= Hash.new {|h,k| h[k] = [] }
end

.connect(options = {}) ⇒ Object



48
49
50
# File 'lib/redis/connection/memory.rb', line 48

def self.connect(options = {})
  new(options)
end

.databasesObject

Tracks all databases for all instances across the current process. We have to be able to handle two clients with the same host/port accessing different databases at once without overwriting each other. So we store our “data” outside the client instances, in this class level instance method. Client instances access it with a key made up of their host/port, and then select which DB out of the array of them they want. Allows the access we need.



31
32
33
# File 'lib/redis/connection/memory.rb', line 31

def self.databases
  @databases ||= Hash.new {|h,k| h[k] = [] }
end

.reset_all_channelsObject



44
45
46
# File 'lib/redis/connection/memory.rb', line 44

def self.reset_all_channels
  @channels = nil
end

.reset_all_databasesObject

Used for resetting everything in specs



36
37
38
# File 'lib/redis/connection/memory.rb', line 36

def self.reset_all_databases
  @databases = nil
end

Instance Method Details

#[](key) ⇒ Object



853
854
855
# File 'lib/redis/connection/memory.rb', line 853

def [](key)
  get(key)
end

#[]=(key, value) ⇒ Object



857
858
859
# File 'lib/redis/connection/memory.rb', line 857

def []=(key, value)
  set(key, value)
end

#append(key, value) ⇒ Object



234
235
236
237
# File 'lib/redis/connection/memory.rb', line 234

def append(key, value)
  data[key] = (data[key] || "")
  data[key] = data[key] + value.to_s
end

#auth(password) ⇒ Object



118
119
120
# File 'lib/redis/connection/memory.rb', line 118

def auth(password)
  "OK"
end

#bgrewriteaofObject



149
# File 'lib/redis/connection/memory.rb', line 149

def bgrewriteaof ; end

#bgsaveObject



147
# File 'lib/redis/connection/memory.rb', line 147

def bgsave ; end

#bitcount(key, start_index = 0, end_index = -1)) ⇒ Object



209
210
211
212
# File 'lib/redis/connection/memory.rb', line 209

def bitcount(key, start_index = 0, end_index = -1)
  return 0 unless data[key]
  data[key][start_index..end_index].unpack('B*')[0].count("1")
end

#blpop(keys, timeout = 0) ⇒ Object



504
505
506
507
508
509
510
511
512
513
514
# File 'lib/redis/connection/memory.rb', line 504

def blpop(keys, timeout=0)
  #todo threaded mode
  keys = Array(keys)
  keys.each do |key|
    if data[key] && data[key].size > 0
      return [key, data[key].shift]
    end
  end
  sleep(timeout.to_f)
  nil
end

#brpop(keys, timeout = 0) ⇒ Object



472
473
474
475
476
477
478
479
480
481
482
# File 'lib/redis/connection/memory.rb', line 472

def brpop(keys, timeout=0)
  #todo threaded mode
  keys = Array(keys)
  keys.each do |key|
    if data[key] && data[key].size > 0
      return [key, data[key].pop]
    end
  end
  sleep(timeout.to_f)
  nil
end

#brpoplpush(key1, key2, opts = {}) ⇒ Object



491
492
493
494
495
496
# File 'lib/redis/connection/memory.rb', line 491

def brpoplpush(key1, key2, opts={})
  data_type_check(key1, Array)
  brpop(key1).tap do |elem|
    lpush(key2, elem) unless elem.nil?
  end
end

#client(command, options = {}) ⇒ Object



92
93
94
95
96
97
98
99
# File 'lib/redis/connection/memory.rb', line 92

def client(command, options = {})
  case command
  when :setname then true
  when :getname then nil
  else
    raise Redis::CommandError, "ERR unknown command '#{command}'"
  end
end

#connect_unix(path, timeout) ⇒ Object



86
87
# File 'lib/redis/connection/memory.rb', line 86

def connect_unix(path, timeout)
end

#connected?Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/redis/connection/memory.rb', line 82

def connected?
  true
end

#dataObject



73
74
75
# File 'lib/redis/connection/memory.rb', line 73

def data
  find_database
end

#database_instance_keyObject



61
62
63
# File 'lib/redis/connection/memory.rb', line 61

def database_instance_key
  [options[:host], options[:port]].hash
end

#databasesObject



65
66
67
# File 'lib/redis/connection/memory.rb', line 65

def databases
  self.class.databases[database_instance_key]
end

#dbsizeObject



342
343
344
# File 'lib/redis/connection/memory.rb', line 342

def dbsize
  data.keys.count
end

#decr(key) ⇒ Object



943
944
945
946
# File 'lib/redis/connection/memory.rb', line 943

def decr(key)
  data.merge!({ key => (data[key].to_i - 1).to_s || "-1"})
  data[key].to_i
end

#decrby(key, by) ⇒ Object



948
949
950
951
# File 'lib/redis/connection/memory.rb', line 948

def decrby(key, by)
  data.merge!({ key => ((data[key].to_i - by.to_i) || (by.to_i * -1)).to_s })
  data[key].to_i
end

#del(*keys) ⇒ Object



679
680
681
682
683
684
685
686
687
688
# File 'lib/redis/connection/memory.rb', line 679

def del(*keys)
  keys = keys.flatten(1)
  raise_argument_error('del') if keys.empty?

  old_count = data.keys.size
  keys.each do |key|
    data.delete(key)
  end
  old_count - data.keys.size
end

#disconnectObject



89
90
# File 'lib/redis/connection/memory.rb', line 89

def disconnect
end

#dump(key) ⇒ Object



160
161
162
163
164
165
166
167
168
169
# File 'lib/redis/connection/memory.rb', line 160

def dump(key)
  return nil unless exists(key)

  value = data[key]

  Marshal.dump(
    value: value,
    version: FakeRedis::VERSION, # Redis includes the version, so we might as well
  )
end

#echo(string) ⇒ Object



325
326
327
# File 'lib/redis/connection/memory.rb', line 325

def echo(string)
  string
end

#exists(key) ⇒ Object



346
347
348
# File 'lib/redis/connection/memory.rb', line 346

def exists(key)
  data.key?(key)
end

#expire(key, ttl) ⇒ Object



715
716
717
718
719
# File 'lib/redis/connection/memory.rb', line 715

def expire(key, ttl)
  return 0 unless data[key]
  data.expires[key] = Time.now + ttl
  1
end

#expireat(key, timestamp) ⇒ Object



743
744
745
746
# File 'lib/redis/connection/memory.rb', line 743

def expireat(key, timestamp)
  data.expires[key] = Time.at(timestamp)
  true
end

#find_database(id = database_id) ⇒ Object



69
70
71
# File 'lib/redis/connection/memory.rb', line 69

def find_database id=database_id
  databases[id] ||= ExpiringHash.new
end

#flushallObject



113
114
115
116
# File 'lib/redis/connection/memory.rb', line 113

def flushall
  self.class.databases[database_instance_key] = []
  "OK"
end

#flushdbObject



108
109
110
111
# File 'lib/redis/connection/memory.rb', line 108

def flushdb
  databases.delete_at(database_id)
  "OK"
end

#get(key) ⇒ Object



199
200
201
202
# File 'lib/redis/connection/memory.rb', line 199

def get(key)
  data_type_check(key, String)
  data[key]
end

#getbit(key, offset) ⇒ Object



204
205
206
207
# File 'lib/redis/connection/memory.rb', line 204

def getbit(key, offset)
  return unless data[key]
  data[key].unpack('B*')[0].split("")[offset].to_i
end

#getrange(key, start, ending) ⇒ Object Also known as: substr



214
215
216
217
# File 'lib/redis/connection/memory.rb', line 214

def getrange(key, start, ending)
  return unless data[key]
  data[key][start..ending]
end

#getset(key, value) ⇒ Object



220
221
222
223
224
225
# File 'lib/redis/connection/memory.rb', line 220

def getset(key, value)
  data_type_check(key, String)
  data[key].tap do
    set(key, value)
  end
end

#hdel(key, field) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/redis/connection/memory.rb', line 254

def hdel(key, field)
  data_type_check(key, Hash)
  return 0 unless data[key]

  if field.is_a?(Array)
    old_keys_count = data[key].size
    fields = field.map(&:to_s)

    data[key].delete_if { |k, v| fields.include? k }
    deleted = old_keys_count - data[key].size
  else
    field = field.to_s
    deleted = data[key].delete(field) ? 1 : 0
  end

  remove_key_for_empty_collection(key)
  deleted
end

#hexists(key, field) ⇒ Object



845
846
847
848
849
# File 'lib/redis/connection/memory.rb', line 845

def hexists(key, field)
  data_type_check(key, Hash)
  return false unless data[key]
  data[key].key?(field.to_s)
end

#hget(key, field) ⇒ Object



249
250
251
252
# File 'lib/redis/connection/memory.rb', line 249

def hget(key, field)
  data_type_check(key, Hash)
  data[key] && data[key][field.to_s]
end

#hgetall(key) ⇒ Object



244
245
246
247
# File 'lib/redis/connection/memory.rb', line 244

def hgetall(key)
  data_type_check(key, Hash)
  data[key].to_a.flatten || {}
end

#hincrby(key, field, increment) ⇒ Object



823
824
825
826
827
828
829
830
831
832
# File 'lib/redis/connection/memory.rb', line 823

def hincrby(key, field, increment)
  data_type_check(key, Hash)
  field = field.to_s
  if data[key]
    data[key][field] = (data[key][field].to_i + increment.to_i).to_s
  else
    data[key] = { field => increment.to_s }
  end
  data[key][field].to_i
end

#hincrbyfloat(key, field, increment) ⇒ Object



834
835
836
837
838
839
840
841
842
843
# File 'lib/redis/connection/memory.rb', line 834

def hincrbyfloat(key, field, increment)
  data_type_check(key, Hash)
  field = field.to_s
  if data[key]
    data[key][field] = (data[key][field].to_f + increment.to_f).to_s
  else
    data[key] = { field => increment.to_s }
  end
  data[key][field]
end

#hkeys(key) ⇒ Object



273
274
275
276
277
# File 'lib/redis/connection/memory.rb', line 273

def hkeys(key)
  data_type_check(key, Hash)
  return [] if data[key].nil?
  data[key].keys
end

#hlen(key) ⇒ Object



811
812
813
814
815
# File 'lib/redis/connection/memory.rb', line 811

def hlen(key)
  data_type_check(key, Hash)
  return 0 unless data[key]
  data[key].size
end

#hmget(key, *fields) ⇒ Object



797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'lib/redis/connection/memory.rb', line 797

def hmget(key, *fields)
  raise_argument_error('hmget')  if fields.empty?

  data_type_check(key, Hash)
  fields.flatten.map do |field|
    field = field.to_s
    if data[key]
      data[key][field]
    else
      nil
    end
  end
end

#hmset(key, *fields) ⇒ Object



772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# File 'lib/redis/connection/memory.rb', line 772

def hmset(key, *fields)
  # mapped_hmset gives us [[:k1, "v1", :k2, "v2"]] for `fields`. Fix that.
  fields = fields[0] if mapped_param?(fields)
  raise_argument_error('hmset') if fields.empty?

  is_list_of_arrays = fields.all?{|field| field.instance_of?(Array)}

  raise_argument_error('hmset') if fields.size.odd? and !is_list_of_arrays
  raise_argument_error('hmset') if is_list_of_arrays and !fields.all?{|field| field.length == 2}

  data_type_check(key, Hash)
  data[key] ||= {}

  if is_list_of_arrays
    fields.each do |pair|
      data[key][pair[0].to_s] = pair[1].to_s
    end
  else
    fields.each_slice(2) do |field|
      data[key][field[0].to_s] = field[1].to_s
    end
  end
  "OK"
end

#hscan(key, start_cursor, *args) ⇒ Object



279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/redis/connection/memory.rb', line 279

def hscan(key, start_cursor, *args)
  data_type_check(key, Hash)
  return ["0", []] unless data[key]

  match = "*"
  count = 10

  if args.size.odd?
    raise_argument_error('hscan')
  end

  if idx = args.index("MATCH")
    match = args[idx + 1]
  end

  if idx = args.index("COUNT")
    count = args[idx + 1]
  end

  start_cursor = start_cursor.to_i

  cursor = start_cursor
  next_keys = []

  if start_cursor + count >= data[key].length
    next_keys = (data[key].to_a)[start_cursor..-1]
    cursor = 0
  else
    cursor = start_cursor + count
    next_keys = (data[key].to_a)[start_cursor..cursor-1]
  end

  filtered_next_keys = next_keys.select{|k,v| File.fnmatch(match, k)}
  result = filtered_next_keys.flatten.map(&:to_s)

  return ["#{cursor}", result]
end

#hset(key, field, value) ⇒ Object



752
753
754
755
756
757
758
759
760
761
762
763
# File 'lib/redis/connection/memory.rb', line 752

def hset(key, field, value)
  data_type_check(key, Hash)
  field = field.to_s
  if data[key]
    result = !data[key].include?(field)
    data[key][field] = value.to_s
    result ? 1 : 0
  else
    data[key] = { field => value.to_s }
    1
  end
end

#hsetnx(key, field, value) ⇒ Object



765
766
767
768
769
770
# File 'lib/redis/connection/memory.rb', line 765

def hsetnx(key, field, value)
  data_type_check(key, Hash)
  field = field.to_s
  return false if data[key] && data[key][field]
  hset(key, field, value)
end

#hvals(key) ⇒ Object



817
818
819
820
821
# File 'lib/redis/connection/memory.rb', line 817

def hvals(key)
  data_type_check(key, Hash)
  return [] unless data[key]
  data[key].values
end

#incr(key) ⇒ Object



928
929
930
931
# File 'lib/redis/connection/memory.rb', line 928

def incr(key)
  data.merge!({ key => (data[key].to_i + 1).to_s || "1"})
  data[key].to_i
end

#incrby(key, by) ⇒ Object



933
934
935
936
# File 'lib/redis/connection/memory.rb', line 933

def incrby(key, by)
  data.merge!({ key => (data[key].to_i + by.to_i).to_s || by })
  data[key].to_i
end

#incrbyfloat(key, by) ⇒ Object



938
939
940
941
# File 'lib/redis/connection/memory.rb', line 938

def incrbyfloat(key, by)
  data.merge!({ key => (data[key].to_f + by.to_f).to_s || by })
  data[key]
end

#infoObject



128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'lib/redis/connection/memory.rb', line 128

def info
  {
    "redis_version" => "2.6.16",
    "connected_clients" => "1",
    "connected_slaves" => "0",
    "used_memory" => "3187",
    "changes_since_last_save" => "0",
    "last_save_time" => "1237655729",
    "total_connections_received" => "1",
    "total_commands_processed" => "1",
    "uptime_in_seconds" => "36000",
    "uptime_in_days" => 0
  }
end

#keys(pattern = "*") ⇒ Object



317
318
319
# File 'lib/redis/connection/memory.rb', line 317

def keys(pattern = "*")
  data.keys.select { |key| File.fnmatch(pattern, key) }
end

#lastsaveObject



333
334
335
# File 'lib/redis/connection/memory.rb', line 333

def lastsave
  Time.now.to_i
end

#lindex(key, index) ⇒ Object



385
386
387
388
# File 'lib/redis/connection/memory.rb', line 385

def lindex(key, index)
  data_type_check(key, Array)
  data[key] && data[key][index]
end

#linsert(key, where, pivot, value) ⇒ Object



390
391
392
393
394
395
396
397
398
399
400
401
402
403
# File 'lib/redis/connection/memory.rb', line 390

def linsert(key, where, pivot, value)
  data_type_check(key, Array)
  return unless data[key]

  value = value.to_s
  index = data[key].index(pivot.to_s)
  return -1 if index.nil?

  case where.to_s
    when /\Abefore\z/i then data[key].insert(index, value)
    when /\Aafter\z/i  then data[key].insert(index + 1, value)
    else raise_syntax_error
  end
end

#llen(key) ⇒ Object



350
351
352
353
354
# File 'lib/redis/connection/memory.rb', line 350

def llen(key)
  data_type_check(key, Array)
  return 0 unless data[key]
  data[key].size
end

#lpop(key) ⇒ Object



498
499
500
501
502
# File 'lib/redis/connection/memory.rb', line 498

def lpop(key)
  data_type_check(key, Array)
  return unless data[key]
  data[key].shift
end

#lpush(key, value) ⇒ Object



449
450
451
452
453
454
455
456
457
# File 'lib/redis/connection/memory.rb', line 449

def lpush(key, value)
  raise_argument_error('lpush') if value.respond_to?(:each) && value.empty?
  data_type_check(key, Array)
  data[key] ||= []
  [value].flatten.each do |val|
    data[key].unshift(val.to_s)
  end
  data[key].size
end

#lpushx(key, value) ⇒ Object



459
460
461
462
463
464
# File 'lib/redis/connection/memory.rb', line 459

def lpushx(key, value)
  raise_argument_error('lpushx') if value.respond_to?(:each) && value.empty?
  data_type_check(key, Array)
  return unless data[key]
  lpush(key, value)
end

#lrange(key, startidx, endidx) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
# File 'lib/redis/connection/memory.rb', line 356

def lrange(key, startidx, endidx)
  data_type_check(key, Array)
  if data[key]
    # In Ruby when negative start index is out of range Array#slice returns
    # nil which is not the case for lrange in Redis.
    startidx = 0 if startidx < 0 && startidx.abs > data[key].size
    data[key][startidx..endidx] || []
  else
    []
  end
end

#lrem(key, count, value) ⇒ Object



412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# File 'lib/redis/connection/memory.rb', line 412

def lrem(key, count, value)
  data_type_check(key, Array)
  return 0 unless data[key]

  value = value.to_s
  old_size = data[key].size
  diff =
    if count == 0
      data[key].delete(value)
      old_size - data[key].size
    else
      array = count > 0 ? data[key].dup : data[key].reverse
      count.abs.times{ array.delete_at(array.index(value) || array.length) }
      data[key] = count > 0 ? array.dup : array.reverse
      old_size - data[key].size
    end
  remove_key_for_empty_collection(key)
  diff
end

#lset(key, index, value) ⇒ Object

Raises:

  • (Redis::CommandError)


405
406
407
408
409
410
# File 'lib/redis/connection/memory.rb', line 405

def lset(key, index, value)
  data_type_check(key, Array)
  return unless data[key]
  raise Redis::CommandError, "ERR index out of range" if index >= data[key].size
  data[key][index] = value.to_s
end

#ltrim(key, start, stop) ⇒ Object



368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/redis/connection/memory.rb', line 368

def ltrim(key, start, stop)
  data_type_check(key, Array)
  return unless data[key]

  # Example: we have a list of 3 elements and
  # we give it a ltrim list, -5, -1. This means
  # it should trim to a max of 5. Since 3 < 5
  # we should not touch the list. This is consistent
  # with behavior of real Redis's ltrim with a negative
  # start argument.
  unless start < 0 && data[key].count < start.abs
    data[key] = data[key][start..stop]
  end

  "OK"
end

#mget(*keys) ⇒ Object



227
228
229
230
231
232
# File 'lib/redis/connection/memory.rb', line 227

def mget(*keys)
  raise_argument_error('mget') if keys.empty?
  # We work with either an array, or list of arguments
  keys = keys.first if keys.size == 1
  data.values_at(*keys)
end

#monitorObject



143
# File 'lib/redis/connection/memory.rb', line 143

def monitor; end

#move(key, destination_id) ⇒ Object

Raises:

  • (Redis::CommandError)


151
152
153
154
155
156
157
158
# File 'lib/redis/connection/memory.rb', line 151

def move key, destination_id
  raise Redis::CommandError, "ERR source and destination objects are the same" if destination_id == database_id
  destination = find_database(destination_id)
  return false unless data.has_key?(key)
  return false if destination.has_key?(key)
  destination[key] = data.delete(key)
  true
end

#mset(*pairs) ⇒ Object



905
906
907
908
909
910
911
912
913
914
915
916
# File 'lib/redis/connection/memory.rb', line 905

def mset(*pairs)
  # Handle pairs for mapped_mset command
  pairs = pairs[0] if mapped_param?(pairs)
  raise_argument_error('mset') if pairs.empty? || pairs.size == 1
  # We have to reply with a different error message here to be consistent with redis-rb 3.0.6 / redis-server 2.8.1
  raise_argument_error("mset", "mset_odd") if pairs.size.odd?

  pairs.each_slice(2) do |pair|
    data[pair[0].to_s] = pair[1].to_s
  end
  "OK"
end

#msetnx(*pairs) ⇒ Object



918
919
920
921
922
923
924
925
926
# File 'lib/redis/connection/memory.rb', line 918

def msetnx(*pairs)
  # Handle pairs for mapped_msetnx command
  pairs = pairs[0] if mapped_param?(pairs)
  keys = []
  pairs.each_with_index{|item, index| keys << item.to_s if index % 2 == 0}
  return false if keys.any?{|key| data.key?(key) }
  mset(*pairs)
  true
end

#persist(key) ⇒ Object



748
749
750
# File 'lib/redis/connection/memory.rb', line 748

def persist(key)
  !!data.expires.delete(key)
end

#pexpire(key, ttl) ⇒ Object



721
722
723
724
725
# File 'lib/redis/connection/memory.rb', line 721

def pexpire(key, ttl)
  return 0 unless data[key]
  data.expires[key] = Time.now + (ttl / 1000.0)
  1
end

#pingObject



329
330
331
# File 'lib/redis/connection/memory.rb', line 329

def ping
  "PONG"
end

#psubscribe(*patterns) ⇒ Object



1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
# File 'lib/redis/connection/memory.rb', line 1230

def psubscribe(*patterns)
  raise_argument_error('psubscribe') if patterns.empty?()

  #Create messages for all data from the channels
  channel_replies = self.class.channels.keys.map do |channel|
    pattern = patterns.find{|p| File.fnmatch(p, channel) }
    unless pattern.nil?()
      self.class.channels[channel].slice!(0..-1).map!{|v| ["pmessage", pattern, channel, v]}
    end
  end
  channel_replies.flatten!(1)
  channel_replies.compact!()

  #Put messages into the replies for the future
  patterns.each_with_index do |pattern,index|
    replies << ["psubscribe", pattern, index+1]
  end
  replies.push(*channel_replies)

  #Add unsubscribe to stop blocking
  replies.push(self.punsubscribe())

  replies.pop() #Last reply will be pushed back on
end

#pttl(key) ⇒ Object



735
736
737
738
739
740
741
# File 'lib/redis/connection/memory.rb', line 735

def pttl(key)
  if data.expires.include?(key) && (ttl = data.expires[key].to_f - Time.now.to_f) > 0
    ttl * 1000
  else
    exists(key) ? -1 : -2
  end
end

#publish(channel, message) ⇒ Object



1255
1256
1257
1258
# File 'lib/redis/connection/memory.rb', line 1255

def publish(channel, message)
  self.class.channels[channel] << message
  0 #Just fake number of subscribers
end

#punsubscribe(*patterns) ⇒ Object



1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
# File 'lib/redis/connection/memory.rb', line 1271

def punsubscribe(*patterns)
  if patterns.empty?()
    replies << ["punsubscribe", nil, 0]
  else
    patterns.each do |pattern|
      replies << ["punsubscribe", pattern, 0]
    end
  end
  replies.pop() #Last reply will be pushed back on
end

#quitObject



964
# File 'lib/redis/connection/memory.rb', line 964

def quit ; end

#randomkeyObject



321
322
323
# File 'lib/redis/connection/memory.rb', line 321

def randomkey
  data.keys[rand(dbsize)]
end

#readObject



104
105
106
# File 'lib/redis/connection/memory.rb', line 104

def read
  replies.shift
end

#rename(key, new_key) ⇒ Object



699
700
701
702
703
704
# File 'lib/redis/connection/memory.rb', line 699

def rename(key, new_key)
  return unless data[key]
  data[new_key] = data[key]
  data.expires[new_key] = data.expires[key] if data.expires.include?(key)
  data.delete(key)
end

#renamenx(key, new_key) ⇒ Object



706
707
708
709
710
711
712
713
# File 'lib/redis/connection/memory.rb', line 706

def renamenx(key, new_key)
  if exists(new_key)
    false
  else
    rename(key, new_key)
    true
  end
end

#restore(key, ttl, serialized_value) ⇒ Object

Raises:

  • (Redis::CommandError)


171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/redis/connection/memory.rb', line 171

def restore(key, ttl, serialized_value)
  raise Redis::CommandError, "ERR Target key name is busy." if exists(key)

  raise Redis::CommandError, "ERR DUMP payload version or checksum are wrong" if serialized_value.nil?

  parsed_value = begin
    Marshal.load(serialized_value)
  rescue TypeError
    raise Redis::CommandError, "ERR DUMP payload version or checksum are wrong"
  end

  if parsed_value[:version] != FakeRedis::VERSION
    raise Redis::CommandError, "ERR DUMP payload version or checksum are wrong"
  end

  # We could figure out what type the key was and set it with the public API here,
  # or we could just assign the value. If we presume the serialized_value is only ever
  # a return value from `dump` then we've only been given something that was in
  # the internal data structure anyway.
  data[key] = parsed_value[:value]

  # Set a TTL if one has been passed
  ttl = ttl.to_i # Makes nil into 0
  expire(key, ttl / 1000) unless ttl.zero?

  "OK"
end

#rpop(key) ⇒ Object



466
467
468
469
470
# File 'lib/redis/connection/memory.rb', line 466

def rpop(key)
  data_type_check(key, Array)
  return unless data[key]
  data[key].pop
end

#rpoplpush(key1, key2) ⇒ Object



484
485
486
487
488
489
# File 'lib/redis/connection/memory.rb', line 484

def rpoplpush(key1, key2)
  data_type_check(key1, Array)
  rpop(key1).tap do |elem|
    lpush(key2, elem) unless elem.nil?
  end
end

#rpush(key, value) ⇒ Object



432
433
434
435
436
437
438
439
440
# File 'lib/redis/connection/memory.rb', line 432

def rpush(key, value)
  raise_argument_error('rpush') if value.respond_to?(:each) && value.empty?
  data_type_check(key, Array)
  data[key] ||= []
  [value].flatten.each do |val|
    data[key].push(val.to_s)
  end
  data[key].size
end

#rpushx(key, value) ⇒ Object



442
443
444
445
446
447
# File 'lib/redis/connection/memory.rb', line 442

def rpushx(key, value)
  raise_argument_error('rpushx') if value.respond_to?(:each) && value.empty?
  data_type_check(key, Array)
  return unless data[key]
  rpush(key, value)
end

#sadd(key, value) ⇒ Object



528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
# File 'lib/redis/connection/memory.rb', line 528

def sadd(key, value)
  data_type_check(key, ::Set)
  value = Array(value)
  raise_argument_error('sadd') if value.empty?

  result = if data[key]
    old_set = data[key].dup
    data[key].merge(value.map(&:to_s))
    (data[key] - old_set).size
  else
    data[key] = ::Set.new(value.map(&:to_s))
    data[key].size
  end

  # 0 = false, 1 = true, 2+ untouched
  return result == 1 if result < 2
  result
end

#saveObject



145
# File 'lib/redis/connection/memory.rb', line 145

def save; end

#scan(start_cursor, *args) ⇒ Object



970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
# File 'lib/redis/connection/memory.rb', line 970

def scan(start_cursor, *args)
  match = "*"
  count = 10

  if idx = args.index("MATCH")
    match = args[idx + 1]
  end

  if idx = args.index("COUNT")
    count = args[idx + 1]
  end

  start_cursor = start_cursor.to_i
  data_type_check(start_cursor, Integer)

  cursor = start_cursor
  returned_keys = []
  final_page = start_cursor + count >= keys(match).length

  if final_page
    previous_keys_been_deleted = (count >= keys(match).length)
    start_index = previous_keys_been_deleted ? 0 : cursor

    returned_keys = keys(match)[start_index..-1]
    cursor = 0
  else
    end_index = start_cursor + (count - 1)
    returned_keys = keys(match)[start_cursor..end_index]
    cursor = start_cursor + count
  end

  return "#{cursor}", returned_keys
end

#scard(key) ⇒ Object



581
582
583
584
585
# File 'lib/redis/connection/memory.rb', line 581

def scard(key)
  data_type_check(key, ::Set)
  return 0 unless data[key]
  data[key].size
end

#sdiff(key1, *keys) ⇒ Object



622
623
624
625
626
627
628
629
# File 'lib/redis/connection/memory.rb', line 622

def sdiff(key1, *keys)
  keys = keys[0] if flatten?(keys)
  [key1, *keys].each { |k| data_type_check(k, ::Set) }
  keys = keys.map { |k| data[k] || ::Set.new }
  keys.inject(data[key1] || Set.new) do |memo, set|
    memo - set
  end.to_a
end

#sdiffstore(destination, key1, *keys) ⇒ Object



631
632
633
634
635
# File 'lib/redis/connection/memory.rb', line 631

def sdiffstore(destination, key1, *keys)
  data_type_check(destination, ::Set)
  result = sdiff(key1, *keys)
  data[destination] = ::Set.new(result)
end

#select(index) ⇒ Object



122
123
124
125
126
# File 'lib/redis/connection/memory.rb', line 122

def select(index)
  data_type_check(index, Integer)
  self.database_id = index
  "OK"
end

#set(key, value, *array_options) ⇒ Object



861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
# File 'lib/redis/connection/memory.rb', line 861

def set(key, value, *array_options)
  option_nx = array_options.delete("NX")
  option_xx = array_options.delete("XX")

  return false if option_nx && option_xx

  return false if option_nx && exists(key)
  return false if option_xx && !exists(key)

  data[key] = value.to_s

  options = Hash[array_options.each_slice(2).to_a]
  ttl_in_seconds = options["EX"] if options["EX"]
  ttl_in_seconds = options["PX"] / 1000.0 if options["PX"]

  expire(key, ttl_in_seconds) if ttl_in_seconds

  "OK"
end

#setbit(key, offset, bit) ⇒ Object



881
882
883
884
885
886
887
888
889
890
891
# File 'lib/redis/connection/memory.rb', line 881

def setbit(key, offset, bit)
  old_val = data[key] ? data[key].unpack('B*')[0].split("") : []
  size_increment = [((offset/8)+1)*8-old_val.length, 0].max
  old_val += Array.new(size_increment).map{"0"}
  original_val = old_val[offset].to_i
  old_val[offset] = bit.to_s
  new_val = ""
  old_val.each_slice(8){|b| new_val = new_val + b.join("").to_i(2).chr }
  data[key] = new_val
  original_val
end

#setex(key, seconds, value) ⇒ Object



893
894
895
896
897
# File 'lib/redis/connection/memory.rb', line 893

def setex(key, seconds, value)
  data[key] = value.to_s
  expire(key, seconds)
  "OK"
end

#setnx(key, value) ⇒ Object



690
691
692
693
694
695
696
697
# File 'lib/redis/connection/memory.rb', line 690

def setnx(key, value)
  if exists(key)
    0
  else
    set(key, value)
    1
  end
end

#setrange(key, offset, value) ⇒ Object



899
900
901
902
903
# File 'lib/redis/connection/memory.rb', line 899

def setrange(key, offset, value)
  return unless data[key]
  s = data[key][offset,value.size]
  data[key][s] = value
end

#shutdownObject



966
# File 'lib/redis/connection/memory.rb', line 966

def shutdown; end

#sinter(*keys) ⇒ Object



587
588
589
590
591
592
593
594
595
596
597
# File 'lib/redis/connection/memory.rb', line 587

def sinter(*keys)
  keys = keys[0] if flatten?(keys)
  raise_argument_error('sinter') if keys.empty?

  keys.each { |k| data_type_check(k, ::Set) }
  return ::Set.new if keys.any? { |k| data[k].nil? }
  keys = keys.map { |k| data[k] || ::Set.new }
  keys.inject do |set, key|
    set & key
  end.to_a
end

#sinterstore(destination, *keys) ⇒ Object



599
600
601
602
603
# File 'lib/redis/connection/memory.rb', line 599

def sinterstore(destination, *keys)
  data_type_check(destination, ::Set)
  result = sinter(*keys)
  data[destination] = ::Set.new(result)
end

#sismember(key, value) ⇒ Object



522
523
524
525
526
# File 'lib/redis/connection/memory.rb', line 522

def sismember(key, value)
  data_type_check(key, ::Set)
  return false unless data[key]
  data[key].include?(value.to_s)
end

#slaveof(host, port) ⇒ Object



968
# File 'lib/redis/connection/memory.rb', line 968

def slaveof(host, port) ; end

#smembers(key) ⇒ Object



516
517
518
519
520
# File 'lib/redis/connection/memory.rb', line 516

def smembers(key)
  data_type_check(key, ::Set)
  return [] unless data[key]
  data[key].to_a.reverse
end

#smove(source, destination, value) ⇒ Object



564
565
566
567
568
569
# File 'lib/redis/connection/memory.rb', line 564

def smove(source, destination, value)
  data_type_check(destination, ::Set)
  result = self.srem(source, value)
  self.sadd(destination, value) if result
  result
end

#spop(key, count = nil) ⇒ Object



571
572
573
574
575
576
577
578
579
# File 'lib/redis/connection/memory.rb', line 571

def spop(key, count = nil)
  data_type_check(key, ::Set)
  results = (count || 1).times.map do
    elem = srandmember(key)
    srem(key, elem)
    elem
  end.compact
  count.nil? ? results.first : results
end

#srandmember(key, number = nil) ⇒ Object



637
638
639
# File 'lib/redis/connection/memory.rb', line 637

def srandmember(key, number=nil)
  number.nil? ? srandmember_single(key) : srandmember_multiple(key, number)
end

#srem(key, value) ⇒ Object



547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
# File 'lib/redis/connection/memory.rb', line 547

def srem(key, value)
  data_type_check(key, ::Set)
  return false unless data[key]

  if value.is_a?(Array)
    old_size = data[key].size
    values = value.map(&:to_s)
    values.each { |v| data[key].delete(v) }
    deleted = old_size - data[key].size
  else
    deleted = !!data[key].delete?(value.to_s)
  end

  remove_key_for_empty_collection(key)
  deleted
end

#sscan(key, start_cursor, *args) ⇒ Object



641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
# File 'lib/redis/connection/memory.rb', line 641

def sscan(key, start_cursor, *args)
  data_type_check(key, ::Set)
  return ["0", []] unless data[key]

  match = "*"
  count = 10

  if args.size.odd?
    raise_argument_error('sscan')
  end

  if idx = args.index("MATCH")
    match = args[idx + 1]
  end

  if idx = args.index("COUNT")
    count = args[idx + 1]
  end

  start_cursor = start_cursor.to_i

  cursor = start_cursor
  next_keys = []

  if start_cursor + count >= data[key].length
    next_keys = (data[key].to_a)[start_cursor..-1]
    cursor = 0
  else
    cursor = start_cursor + count
    next_keys = (data[key].to_a)[start_cursor..cursor-1]
  end

  filtered_next_keys = next_keys.select{ |k,v| File.fnmatch(match, k)}
  result = filtered_next_keys.flatten.map(&:to_s)

  return ["#{cursor}", result]
end

#strlen(key) ⇒ Object



239
240
241
242
# File 'lib/redis/connection/memory.rb', line 239

def strlen(key)
  return unless data[key]
  data[key].size
end

#subscribe(*channels) ⇒ Object



1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
# File 'lib/redis/connection/memory.rb', line 1208

def subscribe(*channels)
  raise_argument_error('subscribe') if channels.empty?()

  #Create messages for all data from the channels
  channel_replies = channels.map do |channel|
    self.class.channels[channel].slice!(0..-1).map!{|v| ["message", channel, v]}
  end
  channel_replies.flatten!(1)
  channel_replies.compact!()

  #Put messages into the replies for the future
  channels.each_with_index do |channel,index|
    replies << ["subscribe", channel, index+1]
  end
  replies.push(*channel_replies)

  #Add unsubscribe message to stop blocking (see https://github.com/redis/redis-rb/blob/v3.2.1/lib/redis/subscribe.rb#L38)
  replies.push(self.unsubscribe())

  replies.pop() #Last reply will be pushed back on
end

#sunion(*keys) ⇒ Object



605
606
607
608
609
610
611
612
613
614
# File 'lib/redis/connection/memory.rb', line 605

def sunion(*keys)
  keys = keys[0] if flatten?(keys)
  raise_argument_error('sunion') if keys.empty?

  keys.each { |k| data_type_check(k, ::Set) }
  keys = keys.map { |k| data[k] || ::Set.new }
  keys.inject(::Set.new) do |set, key|
    set | key
  end.to_a
end

#sunionstore(destination, *keys) ⇒ Object



616
617
618
619
620
# File 'lib/redis/connection/memory.rb', line 616

def sunionstore(destination, *keys)
  data_type_check(destination, ::Set)
  result = sunion(*keys)
  data[destination] = ::Set.new(result)
end

#syncObject



851
# File 'lib/redis/connection/memory.rb', line 851

def sync ; end

#timeObject



337
338
339
340
# File 'lib/redis/connection/memory.rb', line 337

def time
  microseconds = (Time.now.to_f * 1000000).to_i
  [ microseconds / 1000000, microseconds % 1000000 ]
end

#timeout=(usecs) ⇒ Object



101
102
# File 'lib/redis/connection/memory.rb', line 101

def timeout=(usecs)
end

#ttl(key) ⇒ Object



727
728
729
730
731
732
733
# File 'lib/redis/connection/memory.rb', line 727

def ttl(key)
  if data.expires.include?(key) && (ttl = data.expires[key].to_i - Time.now.to_i) > 0
    ttl
  else
    exists(key) ? -1 : -2
  end
end

#type(key) ⇒ Object



953
954
955
956
957
958
959
960
961
962
# File 'lib/redis/connection/memory.rb', line 953

def type(key)
  case data[key]
    when nil then "none"
    when String then "string"
    when ZSet then "zset"
    when Hash then "hash"
    when Array then "list"
    when ::Set then "set"
  end
end

#unsubscribe(*channels) ⇒ Object



1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
# File 'lib/redis/connection/memory.rb', line 1260

def unsubscribe(*channels)
  if channels.empty?()
    replies << ["unsubscribe", nil, 0]
  else
    channels.each do |channel|
      replies << ["unsubscribe", channel, 0]
    end
  end
  replies.pop() #Last reply will be pushed back on
end

#zadd(key, *args) ⇒ Object



1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
# File 'lib/redis/connection/memory.rb', line 1004

def zadd(key, *args)
  if !args.first.is_a?(Array)
    if args.size < 2
      raise_argument_error('zadd')
    elsif args.size.odd?
      raise_syntax_error
    end
  else
    unless args.all? {|pair| pair.size == 2 }
      raise_syntax_error
    end
  end

  data_type_check(key, ZSet)
  data[key] ||= ZSet.new

  if args.size == 2 && !(Array === args.first)
    score, value = args
    exists = !data[key].key?(value.to_s)
    data[key][value.to_s] = score
  else
    # Turn [1, 2, 3, 4] into [[1, 2], [3, 4]] unless it is already
    args = args.each_slice(2).to_a unless args.first.is_a?(Array)
    exists = args.map(&:last).map { |el| data[key].key?(el.to_s) }.count(false)
    args.each { |s, v| data[key][v.to_s] = s }
  end

  exists
end

#zcard(key) ⇒ Object



1047
1048
1049
1050
# File 'lib/redis/connection/memory.rb', line 1047

def zcard(key)
  data_type_check(key, ZSet)
  data[key] ? data[key].size : 0
end

#zcount(key, min, max) ⇒ Object



1058
1059
1060
1061
1062
# File 'lib/redis/connection/memory.rb', line 1058

def zcount(key, min, max)
  data_type_check(key, ZSet)
  return 0 unless data[key]
  data[key].select_by_score(min, max).size
end

#zincrby(key, num, value) ⇒ Object



1064
1065
1066
1067
1068
1069
1070
# File 'lib/redis/connection/memory.rb', line 1064

def zincrby(key, num, value)
  data_type_check(key, ZSet)
  data[key] ||= ZSet.new
  data[key][value.to_s] ||= 0
  data[key].increment(value.to_s, num)
  data[key][value.to_s].to_s
end

#zinterstore(out, *args) ⇒ Object



1194
1195
1196
1197
1198
1199
# File 'lib/redis/connection/memory.rb', line 1194

def zinterstore(out, *args)
  data_type_check(out, ZSet)
  args_handler = SortedSetArgumentHandler.new(args)
  data[out] = SortedSetIntersectStore.new(args_handler, data).call
  data[out].size
end

#zrange(key, start, stop, with_scores = nil) ⇒ Object



1086
1087
1088
1089
1090
1091
1092
1093
1094
# File 'lib/redis/connection/memory.rb', line 1086

def zrange(key, start, stop, with_scores = nil)
  data_type_check(key, ZSet)
  return [] unless data[key]

  results = sort_keys(data[key])
  # Select just the keys unless we want scores
  results = results.map(&:first) unless with_scores
  (results[start..stop] || []).flatten.map(&:to_s)
end

#zrangebylex(key, start, stop, *opts) ⇒ Object



1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
# File 'lib/redis/connection/memory.rb', line 1096

def zrangebylex(key, start, stop, *opts)
  data_type_check(key, ZSet)
  return [] unless data[key]
  zset = data[key]

  sorted = if zset.identical_scores?
    zset.keys.sort { |x, y| x.to_s <=> y.to_s }
  else
    zset.keys
  end

  range = get_range start, stop, sorted.first, sorted.last

  filtered = []
  sorted.each do |element|
    filtered << element if (range[0][:value]..range[1][:value]).cover?(element)
  end
  filtered.shift if filtered[0] == range[0][:value] && !range[0][:inclusive]
  filtered.pop if filtered.last == range[1][:value] && !range[1][:inclusive]

  limit = get_limit(opts, filtered)
  if limit
    filtered = filtered[limit[0]..-1].take(limit[1])
  end

  filtered
end

#zrangebyscore(key, min, max, *opts) ⇒ Object



1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
# File 'lib/redis/connection/memory.rb', line 1139

def zrangebyscore(key, min, max, *opts)
  data_type_check(key, ZSet)
  return [] unless data[key]

  range = data[key].select_by_score(min, max)
  vals = if opts.include?('WITHSCORES')
    range.sort_by {|_,v| v }
  else
    range.keys.sort_by {|k| range[k] }
  end

  limit = get_limit(opts, vals)
  vals = vals[*limit] if limit

  vals.flatten.map(&:to_s)
end

#zrank(key, value) ⇒ Object



1072
1073
1074
1075
1076
1077
# File 'lib/redis/connection/memory.rb', line 1072

def zrank(key, value)
  data_type_check(key, ZSet)
  z = data[key]
  return unless z
  z.keys.sort_by {|k| z[k] }.index(value.to_s)
end

#zrem(key, value) ⇒ Object



1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
# File 'lib/redis/connection/memory.rb', line 1034

def zrem(key, value)
  data_type_check(key, ZSet)
  values = Array(value)
  return 0 unless data[key]

  response = values.map do |v|
    data[key].delete(v.to_s) if data[key].has_key?(v.to_s)
  end.compact.size

  remove_key_for_empty_collection(key)
  response
end

#zremrangebyrank(key, start, stop) ⇒ Object



1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
# File 'lib/redis/connection/memory.rb', line 1183

def zremrangebyrank(key, start, stop)
  data_type_check(key, ZSet)
  return 0 unless data[key]

  sorted_elements = data[key].sort_by { |k, v| v }
  start = sorted_elements.length if start > sorted_elements.length
  elements_to_delete = sorted_elements[start..stop]
  elements_to_delete.each { |elem, rank| data[key].delete(elem) }
  elements_to_delete.size
end

#zremrangebyscore(key, min, max) ⇒ Object



1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/redis/connection/memory.rb', line 1174

def zremrangebyscore(key, min, max)
  data_type_check(key, ZSet)
  return 0 unless data[key]

  range = data[key].select_by_score(min, max)
  range.each {|k,_| data[key].delete(k) }
  range.size
end

#zrevrange(key, start, stop, with_scores = nil) ⇒ Object



1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
# File 'lib/redis/connection/memory.rb', line 1128

def zrevrange(key, start, stop, with_scores = nil)
  data_type_check(key, ZSet)
  return [] unless data[key]

  if with_scores
    data[key].sort_by {|_,v| -v }
  else
    data[key].keys.sort_by {|k| -data[key][k] }
  end[start..stop].flatten.map(&:to_s)
end

#zrevrangebylex(key, start, stop, *args) ⇒ Object



1124
1125
1126
# File 'lib/redis/connection/memory.rb', line 1124

def zrevrangebylex(key, start, stop, *args)
  zrangebylex(key, stop, start, args).reverse
end

#zrevrangebyscore(key, max, min, *opts) ⇒ Object



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
# File 'lib/redis/connection/memory.rb', line 1156

def zrevrangebyscore(key, max, min, *opts)
  opts = opts.flatten
  data_type_check(key, ZSet)
  return [] unless data[key]

  range = data[key].select_by_score(min, max)
  vals = if opts.include?('WITHSCORES')
    range.sort_by {|_,v| -v }
  else
    range.keys.sort_by {|k| -range[k] }
  end

  limit = get_limit(opts, vals)
  vals = vals[*limit] if limit

  vals.flatten.map(&:to_s)
end

#zrevrank(key, value) ⇒ Object



1079
1080
1081
1082
1083
1084
# File 'lib/redis/connection/memory.rb', line 1079

def zrevrank(key, value)
  data_type_check(key, ZSet)
  z = data[key]
  return unless z
  z.keys.sort_by {|k| -z[k] }.index(value.to_s)
end

#zscan(key, start_cursor, *args) ⇒ Object



1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
# File 'lib/redis/connection/memory.rb', line 1282

def zscan(key, start_cursor, *args)
  data_type_check(key, ZSet)
  return [] unless data[key]

  match = "*"
  count = 10

  if args.size.odd?
    raise_argument_error('zscan')
  end

  if idx = args.index("MATCH")
    match = args[idx + 1]
  end

  if idx = args.index("COUNT")
    count = args[idx + 1]
  end

  start_cursor = start_cursor.to_i
  data_type_check(start_cursor, Integer)

  cursor = start_cursor
  next_keys = []

  sorted_keys = sort_keys(data[key])

  if start_cursor + count >= sorted_keys.length
    next_keys = sorted_keys.to_a.select { |k| File.fnmatch(match, k[0]) } [start_cursor..-1]
    cursor = 0
  else
    cursor = start_cursor + count
    next_keys = sorted_keys.to_a.select { |k| File.fnmatch(match, k[0]) } [start_cursor..cursor-1]
  end
  return "#{cursor}", next_keys.flatten.map(&:to_s)
end

#zscan_each(key, *args, &block) ⇒ Object

Originally from redis-rb



1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
# File 'lib/redis/connection/memory.rb', line 1320

def zscan_each(key, *args, &block)
  data_type_check(key, ZSet)
  return [] unless data[key]

  return to_enum(:zscan_each, key, options) unless block_given?
  cursor = 0
  loop do
    cursor, values = zscan(key, cursor, options)
    values.each(&block)
    break if cursor == "0"
  end
end

#zscore(key, value) ⇒ Object



1052
1053
1054
1055
1056
# File 'lib/redis/connection/memory.rb', line 1052

def zscore(key, value)
  data_type_check(key, ZSet)
  value = data[key] && data[key][value.to_s]
  value && value.to_s
end

#zunionstore(out, *args) ⇒ Object



1201
1202
1203
1204
1205
1206
# File 'lib/redis/connection/memory.rb', line 1201

def zunionstore(out, *args)
  data_type_check(out, ZSet)
  args_handler = SortedSetArgumentHandler.new(args)
  data[out] = SortedSetUnionStore.new(args_handler, data).call
  data[out].size
end