Module: MockRedis::StringMethods

Includes:
Assertions, UtilityMethods
Included in:
Database
Defined in:
lib/mock_redis/string_methods.rb

Instance Method Summary collapse

Instance Method Details

#append(key, value) ⇒ Object



8
9
10
11
12
13
# File 'lib/mock_redis/string_methods.rb', line 8

def append(key, value)
  assert_stringy(key)
  data[key] ||= ''
  data[key] << value
  data[key].length
end

#bitcount(key, start = 0, stop = -1)) ⇒ Object



318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
# File 'lib/mock_redis/string_methods.rb', line 318

def bitcount(key, start = 0, stop = -1)
  assert_stringy(key)

  str   = data[key] || ''
  count = 0
  m1    = 0x5555555555555555
  m2    = 0x3333333333333333
  m4    = 0x0f0f0f0f0f0f0f0f
  m8    = 0x00ff00ff00ff00ff
  m16   = 0x0000ffff0000ffff
  m32   = 0x00000000ffffffff

  str.bytes.to_a[start..stop].each do |byte|
    # Naive Hamming weight
    c = byte
    c = (c & m1) + ((c >> 1) & m1)
    c = (c & m2) + ((c >> 2) & m2)
    c = (c & m4) + ((c >> 4) & m4)
    c = (c & m8) + ((c >> 8) & m8)
    c = (c & m16) + ((c >> 16) & m16)
    c = (c & m32) + ((c >> 32) & m32)
    count += c
  end

  count
end

#bitfield(*args) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/mock_redis/string_methods.rb', line 15

def bitfield(*args)
  if args.length < 4
    raise Error.command_error('ERR wrong number of arguments for BITFIELD', self)
  end

  key = args.shift
  output = []
  overflow_method = 'wrap'

  until args.empty?
    command = args.shift.to_s

    if command == 'overflow'
      new_overflow_method = args.shift.to_s.downcase

      unless %w[wrap sat fail].include? new_overflow_method
        raise Error.command_error('ERR Invalid OVERFLOW type specified', self)
      end

      overflow_method = new_overflow_method
      next
    end

    type, offset = args.shift(2)

    is_signed = type.slice(0) == 'i'
    type_size = type[1..].to_i

    if (type_size > 64 && is_signed) || (type_size >= 64 && !is_signed)
      raise Error.command_error(
        'ERR Invalid bitfield type. Use something like i16 u8. ' \
        'Note that u64 is not supported but i64 is.',
        self
      )
    end

    if offset.to_s[0] == '#'
      offset = offset[1..].to_i * type_size
    end

    bits = []

    type_size.times do |i|
      bits.push(getbit(key, offset + i))
    end

    val = is_signed ? twos_complement_decode(bits) : bits.join('').to_i(2)

    case command
    when 'get'
      output.push(val)
    when 'set'
      output.push(val)

      set_bitfield(key, args.shift.to_i, is_signed, type_size, offset)
    when 'incrby'
      new_val = incr_bitfield(val, args.shift.to_i, is_signed, type_size, overflow_method)

      set_bitfield(key, new_val, is_signed, type_size, offset) if new_val
      output.push(new_val)
    end
  end

  output
end

#decr(key) ⇒ Object



81
82
83
# File 'lib/mock_redis/string_methods.rb', line 81

def decr(key)
  decrby(key, 1)
end

#decrby(key, n) ⇒ Object



85
86
87
# File 'lib/mock_redis/string_methods.rb', line 85

def decrby(key, n)
  incrby(key, -n)
end

#get(key) ⇒ Object



89
90
91
92
93
# File 'lib/mock_redis/string_methods.rb', line 89

def get(key)
  key = key.to_s
  assert_stringy(key)
  data[key]
end

#getbit(key, offset) ⇒ Object



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/mock_redis/string_methods.rb', line 95

def getbit(key, offset)
  assert_stringy(key)

  offset = offset.to_i
  offset_of_byte = offset / 8
  offset_within_byte = offset % 8

  # String#getbyte would be lovely, but it's not in 1.8.7.
  byte = (data[key] || '').each_byte.drop(offset_of_byte).first

  if byte
    (byte & (2**7 >> offset_within_byte)) > 0 ? 1 : 0
  else
    0
  end
end

#getdel(key) ⇒ Object



112
113
114
115
116
# File 'lib/mock_redis/string_methods.rb', line 112

def getdel(key)
  value = get(key)
  del(key)
  value
end

#getrange(key, start, stop) ⇒ Object



118
119
120
121
# File 'lib/mock_redis/string_methods.rb', line 118

def getrange(key, start, stop)
  assert_stringy(key)
  (data[key] || '')[start..stop]
end

#getset(key, value) ⇒ Object



123
124
125
126
127
# File 'lib/mock_redis/string_methods.rb', line 123

def getset(key, value)
  retval = get(key)
  set(key, value)
  retval
end

#incr(key) ⇒ Object



129
130
131
# File 'lib/mock_redis/string_methods.rb', line 129

def incr(key)
  incrby(key, 1)
end

#incrby(key, n) ⇒ Object



133
134
135
136
137
138
139
140
141
142
143
144
145
# File 'lib/mock_redis/string_methods.rb', line 133

def incrby(key, n)
  assert_stringy(key)
  n = Integer(n)

  unless can_incr?(data[key])
    raise Error.command_error('ERR value is not an integer or out of range', self)
  end

  new_value = data[key].to_i + n.to_i
  data[key] = new_value.to_s
  # for some reason, redis-rb doesn't return this as a string.
  new_value
end

#incrbyfloat(key, n) ⇒ Object



147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/mock_redis/string_methods.rb', line 147

def incrbyfloat(key, n)
  assert_stringy(key)
  n = Float(n)
  unless can_incr_float?(data[key])
    raise Error.command_error('ERR value is not a valid float', self)
  end

  new_value = data[key].to_f + n.to_f
  data[key] = new_value.to_s
  # for some reason, redis-rb doesn't return this as a string.
  new_value
end

#mapped_mget(*keys) ⇒ Object



172
173
174
# File 'lib/mock_redis/string_methods.rb', line 172

def mapped_mget(*keys)
  Hash[keys.zip(mget(*keys))]
end

#mapped_mset(hash) ⇒ Object



191
192
193
# File 'lib/mock_redis/string_methods.rb', line 191

def mapped_mset(hash)
  mset(*hash.to_a.flatten)
end

#mapped_msetnx(hash) ⇒ Object



206
207
208
# File 'lib/mock_redis/string_methods.rb', line 206

def mapped_msetnx(hash)
  msetnx(*hash.to_a.flatten)
end

#mget(*keys, &blk) ⇒ Object



160
161
162
163
164
165
166
167
168
169
170
# File 'lib/mock_redis/string_methods.rb', line 160

def mget(*keys, &blk)
  keys.flatten!

  assert_has_args(keys, 'mget')

  data = keys.map do |key|
    get(key) if stringy?(key)
  end

  blk ? blk.call(data) : data
end

#mset(*kvpairs) ⇒ Object



176
177
178
179
180
181
182
183
184
185
186
187
188
189
# File 'lib/mock_redis/string_methods.rb', line 176

def mset(*kvpairs)
  assert_has_args(kvpairs, 'mset')
  kvpairs = kvpairs.first if kvpairs.size == 1 && kvpairs.first.is_a?(Enumerable)

  if kvpairs.length.odd?
    raise Error.command_error('ERR wrong number of arguments for MSET', self)
  end

  kvpairs.each_slice(2) do |(k, v)|
    set(k, v)
  end

  'OK'
end

#msetnx(*kvpairs) ⇒ Object



195
196
197
198
199
200
201
202
203
204
# File 'lib/mock_redis/string_methods.rb', line 195

def msetnx(*kvpairs)
  assert_has_args(kvpairs, 'msetnx')

  if kvpairs.each_slice(2).any? { |(k, _)| exists?(k) }
    false
  else
    mset(*kvpairs)
    true
  end
end

#psetex(key, milliseconds, value) ⇒ Object



355
356
357
358
359
360
361
362
363
# File 'lib/mock_redis/string_methods.rb', line 355

def psetex(key, milliseconds, value)
  if milliseconds <= 0
    raise Error.command_error('ERR invalid expire time in psetex', self)
  else
    set(key, value)
    pexpire(key, milliseconds)
    'OK'
  end
end

#set(key, value, _hash = nil, ex: nil, px: nil, exat: nil, pxat: nil, nx: nil, xx: nil, keepttl: nil, get: nil) ⇒ Object

Parameter list required to ensure the ArgumentError is returned correctly rubocop:disable Metrics/ParameterLists



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/mock_redis/string_methods.rb', line 212

def set(key, value, _hash = nil, ex: nil, px: nil, exat: nil, pxat: nil, nx: nil, xx: nil,
  keepttl: nil, get: nil)
  key = key.to_s
  retval = self.get(key) if get

  return_true = false
  if nx
    if exists?(key)
      return false
    else
      return_true = true
    end
  end
  if xx
    if exists?(key)
      return_true = true
    else
      return false
    end
  end
  data[key] = value.to_s

  remove_expiration(key) unless keepttl
  if ex
    if ex == 0
      raise Error.command_error('ERR invalid expire time in set', self)
    end
    expire(key, ex)
  end

  if px
    if px == 0
      raise Error.command_error('ERR invalid expire time in set', self)
    end
    pexpire(key, px)
  end

  if exat
    if exat == 0
      raise Error.command_error('ERR invalid expire time in set', self)
    end
    expireat(key, exat)
  end

  if pxat
    if pxat == 0
      raise Error.command_error('ERR invalid expire time in set', self)
    end
    pexpireat(key, pxat)
  end

  if get
    retval
  else
    return_true ? true : 'OK'
  end
end

#setbit(key, offset, value) ⇒ Object

rubocop:enable Metrics/ParameterLists



271
272
273
274
275
276
277
278
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
316
# File 'lib/mock_redis/string_methods.rb', line 271

def setbit(key, offset, value)
  assert_stringy(key, 'ERR bit is not an integer or out of range')
  retval = getbit(key, offset)

  str = data[key] || ''

  offset = offset.to_i
  offset_of_byte = offset / 8
  offset_within_byte = offset % 8

  if offset_of_byte >= str.bytesize
    str = zero_pad(str, offset_of_byte + 1)
  end

  char_index = byte_index = offset_within_char = 0
  str.each_char do |c|
    if byte_index < offset_of_byte
      char_index += 1
      byte_index += c.bytesize
    else
      offset_within_char = byte_index - offset_of_byte
      break
    end
  end

  char = str[char_index]
  char = char.chr if char.respond_to?(:chr) # ruby 1.8 vs 1.9
  char_as_number = char.each_byte.reduce(0) do |a, byte|
    (a << 8) + byte
  end

  bitmask_length = (char.bytesize * 8 - offset_within_char * 8 - offset_within_byte - 1)
  bitmask = 1 << bitmask_length

  if value.zero?
    bitmask ^= 2**(char.bytesize * 8) - 1
    char_as_number &= bitmask
  else
    char_as_number |= bitmask
  end

  str[char_index] = char_as_number.chr

  data[key] = str
  retval
end

#setex(key, seconds, value) ⇒ Object



345
346
347
348
349
350
351
352
353
# File 'lib/mock_redis/string_methods.rb', line 345

def setex(key, seconds, value)
  if seconds <= 0
    raise Error.command_error('ERR invalid expire time in setex', self)
  else
    set(key, value)
    expire(key, seconds)
    'OK'
  end
end

#setnx(key, value) ⇒ Object



365
366
367
368
369
370
371
372
# File 'lib/mock_redis/string_methods.rb', line 365

def setnx(key, value)
  if exists?(key)
    false
  else
    set(key, value)
    true
  end
end

#setrange(key, offset, value) ⇒ Object



374
375
376
377
378
379
380
381
382
# File 'lib/mock_redis/string_methods.rb', line 374

def setrange(key, offset, value)
  assert_stringy(key)
  value = value.to_s
  old_value = data[key] || ''

  prefix = zero_pad(old_value[0...offset], offset)
  data[key] = prefix + value + (old_value[(offset + value.length)..] || '')
  data[key].length
end

#strlen(key) ⇒ Object



384
385
386
387
# File 'lib/mock_redis/string_methods.rb', line 384

def strlen(key)
  assert_stringy(key)
  (data[key] || '').bytesize
end