| 447 | } |
| 448 | |
| 449 | func cmdDECRBY(m uhaha.Machine, args []string) (interface{}, error) { |
| 450 | // 1. Validate the number of arguments |
| 451 | if len(args) != 3 { |
| 452 | return nil, uhaha.ErrWrongNumArgs |
| 453 | } |
| 454 | |
| 455 | // 2. Parse the decrement value |
| 456 | decrement, err := ledis.StrInt64([]byte(args[2]), nil) |
| 457 | if err != nil { |
| 458 | return nil, fmt.Errorf("ERR value is not an integer or out of range") |
| 459 | } |
| 460 | |
| 461 | // 3. Check if the key exists |
| 462 | key := []byte(args[1]) |
| 463 | exists, err := ldb.Exists(key) |
| 464 | if err != nil { |
| 465 | return nil, err |
| 466 | } |
| 467 | |
| 468 | // 4. If the key does not exist, initialize it to 0 |
| 469 | if exists == 0 { |
| 470 | if err := ldb.Set(key, []byte("0")); err != nil { |
| 471 | return nil, err |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | // 5. Perform the DECRBY operation |
| 476 | n, err := ldb.DecrBy(key, decrement) |
| 477 | if err != nil { |
| 478 | // Handle errors, such as the key containing a non-integer value |
| 479 | return nil, fmt.Errorf("ERR value is not an integer or out of range") |
| 480 | } |
| 481 | |
| 482 | // 6. Return the new value after decrementing |
| 483 | return redcon.SimpleInt(n), nil |
| 484 | } |
| 485 | |
| 486 | func cmdDECR(m uhaha.Machine, args []string) (interface{}, error) { |
| 487 | // 1. Validate the number of arguments |