forked from HDT3213/godis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring.go
602 lines (548 loc) · 15.3 KB
/
string.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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
269
270
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
317
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package godis
import (
"github.com/hdt3213/godis/interface/redis"
"github.com/hdt3213/godis/redis/reply"
"github.com/shopspring/decimal"
"strconv"
"strings"
"time"
)
func (db *DB) getAsString(key string) ([]byte, reply.ErrorReply) {
entity, ok := db.GetEntity(key)
if !ok {
return nil, nil
}
bytes, ok := entity.Data.([]byte)
if !ok {
return nil, &reply.WrongTypeErrReply{}
}
return bytes, nil
}
// execGet returns string value bound to the given key
func execGet(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
bytes, err := db.getAsString(key)
if err != nil {
return err
}
if bytes == nil {
return &reply.NullBulkReply{}
}
return reply.MakeBulkReply(bytes)
}
const (
upsertPolicy = iota // default
insertPolicy // set nx
updatePolicy // set ex
)
const unlimitedTTL int64 = 0
// execSet sets string value and time to live to the given key
func execSet(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
value := args[1]
policy := upsertPolicy
ttl := unlimitedTTL
// parse options
if len(args) > 2 {
for i := 2; i < len(args); i++ {
arg := strings.ToUpper(string(args[i]))
if arg == "NX" { // insert
if policy == updatePolicy {
return &reply.SyntaxErrReply{}
}
policy = insertPolicy
} else if arg == "XX" { // update policy
if policy == insertPolicy {
return &reply.SyntaxErrReply{}
}
policy = updatePolicy
} else if arg == "EX" { // ttl in seconds
if ttl != unlimitedTTL {
// ttl has been set
return &reply.SyntaxErrReply{}
}
if i+1 >= len(args) {
return &reply.SyntaxErrReply{}
}
ttlArg, err := strconv.ParseInt(string(args[i+1]), 10, 64)
if err != nil {
return &reply.SyntaxErrReply{}
}
if ttlArg <= 0 {
return reply.MakeErrReply("ERR invalid expire time in set")
}
ttl = ttlArg * 1000
i++ // skip next arg
} else if arg == "PX" { // ttl in milliseconds
if ttl != unlimitedTTL {
return &reply.SyntaxErrReply{}
}
if i+1 >= len(args) {
return &reply.SyntaxErrReply{}
}
ttlArg, err := strconv.ParseInt(string(args[i+1]), 10, 64)
if err != nil {
return &reply.SyntaxErrReply{}
}
if ttlArg <= 0 {
return reply.MakeErrReply("ERR invalid expire time in set")
}
ttl = ttlArg
i++ // skip next arg
} else {
return &reply.SyntaxErrReply{}
}
}
}
entity := &DataEntity{
Data: value,
}
db.Persist(key) // clean ttl
var result int
switch policy {
case upsertPolicy:
result = db.PutEntity(key, entity)
case insertPolicy:
result = db.PutIfAbsent(key, entity)
case updatePolicy:
result = db.PutIfExists(key, entity)
}
/*
* 如果设置了ttl 则以最新的ttl为准
* 如果没有设置ttl 是新增key的情况,不设置ttl。
* 如果没有设置ttl 且已存在key的 不修改ttl 但需要增加aof
*/
if ttl != unlimitedTTL {
expireTime := time.Now().Add(time.Duration(ttl) * time.Millisecond)
db.Expire(key, expireTime)
db.AddAof(reply.MakeMultiBulkReply([][]byte{
[]byte("SET"),
args[0],
args[1],
}))
db.AddAof(makeExpireCmd(key, expireTime))
} else if result > 0 {
db.Persist(key) // override ttl
db.AddAof(makeAofCmd("set", args))
} else {
db.AddAof(makeAofCmd("set", args))
}
if policy == upsertPolicy || result > 0 {
return &reply.OkReply{}
}
return &reply.NullBulkReply{}
}
// execSetNX sets string if not exists
func execSetNX(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
value := args[1]
entity := &DataEntity{
Data: value,
}
result := db.PutIfAbsent(key, entity)
db.AddAof(makeAofCmd("setnx", args))
return reply.MakeIntReply(int64(result))
}
// execSetEX sets string and its ttl
func execSetEX(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
value := args[2]
ttlArg, err := strconv.ParseInt(string(args[1]), 10, 64)
if err != nil {
return &reply.SyntaxErrReply{}
}
if ttlArg <= 0 {
return reply.MakeErrReply("ERR invalid expire time in setex")
}
ttl := ttlArg * 1000
entity := &DataEntity{
Data: value,
}
db.PutEntity(key, entity)
expireTime := time.Now().Add(time.Duration(ttl) * time.Millisecond)
db.Expire(key, expireTime)
db.AddAof(makeAofCmd("setex", args))
db.AddAof(makeExpireCmd(key, expireTime))
return &reply.OkReply{}
}
// execPSetEX set a key's time to live in milliseconds
func execPSetEX(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
value := args[2]
ttlArg, err := strconv.ParseInt(string(args[1]), 10, 64)
if err != nil {
return &reply.SyntaxErrReply{}
}
if ttlArg <= 0 {
return reply.MakeErrReply("ERR invalid expire time in setex")
}
entity := &DataEntity{
Data: value,
}
db.PutEntity(key, entity)
expireTime := time.Now().Add(time.Duration(ttlArg) * time.Millisecond)
db.Expire(key, expireTime)
db.AddAof(makeAofCmd("setex", args))
db.AddAof(makeExpireCmd(key, expireTime))
return &reply.OkReply{}
}
func prepareMSet(args [][]byte) ([]string, []string) {
size := len(args) / 2
keys := make([]string, size)
for i := 0; i < size; i++ {
keys[i] = string(args[2*i])
}
return keys, nil
}
func undoMSet(db *DB, args [][]byte) []CmdLine {
writeKeys, _ := prepareMSet(args)
return rollbackGivenKeys(db, writeKeys...)
}
// execMSet sets multi key-value in database
func execMSet(db *DB, args [][]byte) redis.Reply {
if len(args)%2 != 0 {
return reply.MakeSyntaxErrReply()
}
size := len(args) / 2
keys := make([]string, size)
values := make([][]byte, size)
for i := 0; i < size; i++ {
keys[i] = string(args[2*i])
values[i] = args[2*i+1]
}
for i, key := range keys {
value := values[i]
db.PutEntity(key, &DataEntity{Data: value})
}
db.AddAof(makeAofCmd("mset", args))
return &reply.OkReply{}
}
func prepareMGet(args [][]byte) ([]string, []string) {
keys := make([]string, len(args))
for i, v := range args {
keys[i] = string(v)
}
return nil, keys
}
// execMGet get multi key-value from database
func execMGet(db *DB, args [][]byte) redis.Reply {
keys := make([]string, len(args))
for i, v := range args {
keys[i] = string(v)
}
result := make([][]byte, len(args))
for i, key := range keys {
bytes, err := db.getAsString(key)
if err != nil {
_, isWrongType := err.(*reply.WrongTypeErrReply)
if isWrongType {
result[i] = nil
continue
} else {
return err
}
}
result[i] = bytes // nil or []byte
}
return reply.MakeMultiBulkReply(result)
}
// execMSetNX sets multi key-value in database, only if none of the given keys exist
func execMSetNX(db *DB, args [][]byte) redis.Reply {
// parse args
if len(args)%2 != 0 {
return reply.MakeSyntaxErrReply()
}
size := len(args) / 2
values := make([][]byte, size)
keys := make([]string, size)
for i := 0; i < size; i++ {
keys[i] = string(args[2*i])
values[i] = args[2*i+1]
}
for _, key := range keys {
_, exists := db.GetEntity(key)
if exists {
return reply.MakeIntReply(0)
}
}
for i, key := range keys {
value := values[i]
db.PutEntity(key, &DataEntity{Data: value})
}
db.AddAof(makeAofCmd("msetnx", args))
return reply.MakeIntReply(1)
}
// execGetSet sets value of a string-type key and returns its old value
func execGetSet(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
value := args[1]
old, err := db.getAsString(key)
if err != nil {
return err
}
db.PutEntity(key, &DataEntity{Data: value})
db.Persist(key) // override ttl
db.AddAof(makeAofCmd("getset", args))
if old == nil {
return new(reply.NullBulkReply)
}
return reply.MakeBulkReply(old)
}
// execIncr increments the integer value of a key by one
func execIncr(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
bytes, err := db.getAsString(key)
if err != nil {
return err
}
if bytes != nil {
val, err := strconv.ParseInt(string(bytes), 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
db.PutEntity(key, &DataEntity{
Data: []byte(strconv.FormatInt(val+1, 10)),
})
db.AddAof(makeAofCmd("incr", args))
return reply.MakeIntReply(val + 1)
}
db.PutEntity(key, &DataEntity{
Data: []byte("1"),
})
db.AddAof(makeAofCmd("incr", args))
return reply.MakeIntReply(1)
}
// execIncrBy increments the integer value of a key by given value
func execIncrBy(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
rawDelta := string(args[1])
delta, err := strconv.ParseInt(rawDelta, 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
bytes, errReply := db.getAsString(key)
if errReply != nil {
return errReply
}
if bytes != nil {
// existed value
val, err := strconv.ParseInt(string(bytes), 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
db.PutEntity(key, &DataEntity{
Data: []byte(strconv.FormatInt(val+delta, 10)),
})
db.AddAof(makeAofCmd("incrby", args))
return reply.MakeIntReply(val + delta)
}
db.PutEntity(key, &DataEntity{
Data: args[1],
})
db.AddAof(makeAofCmd("incrby", args))
return reply.MakeIntReply(delta)
}
// execIncrByFloat increments the float value of a key by given value
func execIncrByFloat(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
rawDelta := string(args[1])
delta, err := decimal.NewFromString(rawDelta)
if err != nil {
return reply.MakeErrReply("ERR value is not a valid float")
}
bytes, errReply := db.getAsString(key)
if errReply != nil {
return errReply
}
if bytes != nil {
val, err := decimal.NewFromString(string(bytes))
if err != nil {
return reply.MakeErrReply("ERR value is not a valid float")
}
resultBytes := []byte(val.Add(delta).String())
db.PutEntity(key, &DataEntity{
Data: resultBytes,
})
db.AddAof(makeAofCmd("incrbyfloat", args))
return reply.MakeBulkReply(resultBytes)
}
db.PutEntity(key, &DataEntity{
Data: args[1],
})
db.AddAof(makeAofCmd("incrbyfloat", args))
return reply.MakeBulkReply(args[1])
}
// execDecr decrements the integer value of a key by one
func execDecr(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
bytes, errReply := db.getAsString(key)
if errReply != nil {
return errReply
}
if bytes != nil {
val, err := strconv.ParseInt(string(bytes), 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
db.PutEntity(key, &DataEntity{
Data: []byte(strconv.FormatInt(val-1, 10)),
})
db.AddAof(makeAofCmd("decr", args))
return reply.MakeIntReply(val - 1)
}
entity := &DataEntity{
Data: []byte("-1"),
}
db.PutEntity(key, entity)
db.AddAof(makeAofCmd("decr", args))
return reply.MakeIntReply(-1)
}
// execDecrBy decrements the integer value of a key by onedecrement
func execDecrBy(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
rawDelta := string(args[1])
delta, err := strconv.ParseInt(rawDelta, 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
bytes, errReply := db.getAsString(key)
if errReply != nil {
return errReply
}
if bytes != nil {
val, err := strconv.ParseInt(string(bytes), 10, 64)
if err != nil {
return reply.MakeErrReply("ERR value is not an integer or out of range")
}
db.PutEntity(key, &DataEntity{
Data: []byte(strconv.FormatInt(val-delta, 10)),
})
db.AddAof(makeAofCmd("decrby", args))
return reply.MakeIntReply(val - delta)
}
valueStr := strconv.FormatInt(-delta, 10)
db.PutEntity(key, &DataEntity{
Data: []byte(valueStr),
})
db.AddAof(makeAofCmd("decrby", args))
return reply.MakeIntReply(-delta)
}
// execStrLen returns len of string value bound to the given key
func execStrLen(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
bytes, err := db.getAsString(key)
if err != nil {
return err
}
if bytes == nil {
return reply.MakeIntReply(0)
}
return reply.MakeIntReply(int64(len(bytes)))
}
// execAppend sets string value to the given key
func execAppend(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
bytes, err := db.getAsString(key)
if err != nil {
return err
}
bytes = append(bytes, args[1]...)
db.PutEntity(key, &DataEntity{
Data: bytes,
})
db.AddAof(makeAofCmd("append", args))
return reply.MakeIntReply(int64(len(bytes)))
}
// execSetRange overwrites part of the string stored at key, starting at the specified offset.
// If the offset is larger than the current length of the string at key, the string is padded with zero-bytes.
func execSetRange(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
offset, errNative := strconv.ParseInt(string(args[1]), 10, 64)
if errNative != nil {
return reply.MakeErrReply(errNative.Error())
}
value := args[2]
bytes, err := db.getAsString(key)
if err != nil {
return err
}
bytesLen := int64(len(bytes))
if bytesLen < offset {
diff := offset - bytesLen
diffArray := make([]byte, diff)
bytes = append(bytes, diffArray...)
bytesLen = int64(len(bytes))
}
for i := 0; i < len(value); i++ {
idx := offset + int64(i)
if idx >= bytesLen {
bytes = append(bytes, value[i])
} else {
bytes[idx] = value[i]
}
}
db.PutEntity(key, &DataEntity{
Data: bytes,
})
db.AddAof(makeAofCmd("setRange", args))
return reply.MakeIntReply(int64(len(bytes)))
}
func execGetRange(db *DB, args [][]byte) redis.Reply {
key := string(args[0])
startIdx, errNative := strconv.ParseInt(string(args[1]), 10, 64)
if errNative != nil {
return reply.MakeErrReply(errNative.Error())
}
endIdx, errNative := strconv.ParseInt(string(args[2]), 10, 64)
if errNative != nil {
return reply.MakeErrReply(errNative.Error())
}
bytes, err := db.getAsString(key)
if err != nil {
return err
}
if bytes == nil {
return reply.MakeNullBulkReply()
}
bytesLen := int64(len(bytes))
if startIdx < -1*bytesLen {
return &reply.NullBulkReply{}
} else if startIdx < 0 {
startIdx = bytesLen + startIdx
} else if startIdx >= bytesLen {
return &reply.NullBulkReply{}
}
if endIdx < -1*bytesLen {
return &reply.NullBulkReply{}
} else if endIdx < 0 {
endIdx = bytesLen + endIdx + 1
} else if endIdx < bytesLen {
endIdx = endIdx + 1
} else {
endIdx = bytesLen
}
if startIdx > endIdx {
return reply.MakeNullBulkReply()
}
return reply.MakeBulkReply(bytes[startIdx:endIdx])
}
func init() {
RegisterCommand("Set", execSet, writeFirstKey, rollbackFirstKey, -3)
RegisterCommand("SetNx", execSetNX, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("SetEX", execSetEX, writeFirstKey, rollbackFirstKey, 4)
RegisterCommand("PSetEX", execPSetEX, writeFirstKey, rollbackFirstKey, 4)
RegisterCommand("MSet", execMSet, prepareMSet, undoMSet, -3)
RegisterCommand("MGet", execMGet, prepareMGet, nil, -2)
RegisterCommand("MSetNX", execMSetNX, prepareMSet, undoMSet, -3)
RegisterCommand("Get", execGet, readFirstKey, nil, 2)
RegisterCommand("GetSet", execGetSet, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("Incr", execIncr, writeFirstKey, rollbackFirstKey, 2)
RegisterCommand("IncrBy", execIncrBy, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("IncrByFloat", execIncrByFloat, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("Decr", execDecr, writeFirstKey, rollbackFirstKey, 2)
RegisterCommand("DecrBy", execDecrBy, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("StrLen", execStrLen, readFirstKey, nil, 2)
RegisterCommand("Append", execAppend, writeFirstKey, rollbackFirstKey, 3)
RegisterCommand("SetRange", execSetRange, writeFirstKey, rollbackFirstKey, 4)
RegisterCommand("GetRange", execGetRange, readFirstKey, nil, 4)
}