BitCount counts the number of set bits (population counting) in a string.
(ctx *Context, txn *db.Transaction)
| 545 | |
| 546 | // BitCount counts the number of set bits (population counting) in a string. |
| 547 | func BitCount(ctx *Context, txn *db.Transaction) (OnCommit, error) { |
| 548 | key := []byte(ctx.Args[0]) |
| 549 | str, err := txn.String(key) |
| 550 | if err != nil { |
| 551 | if err == db.ErrTypeMismatch { |
| 552 | return nil, ErrTypeMismatch |
| 553 | } |
| 554 | return nil, errors.New("ERR " + err.Error()) |
| 555 | } |
| 556 | |
| 557 | if !str.Exist() { |
| 558 | return Integer(ctx.Out, 0), nil |
| 559 | } |
| 560 | |
| 561 | var begin, end int |
| 562 | switch len(ctx.Args) { |
| 563 | case 3: |
| 564 | begin, err = strconv.Atoi(ctx.Args[1]) |
| 565 | if err != nil { |
| 566 | return nil, ErrInteger |
| 567 | } |
| 568 | end, err = strconv.Atoi(ctx.Args[2]) |
| 569 | if err != nil { |
| 570 | return nil, ErrInteger |
| 571 | } |
| 572 | case 1: |
| 573 | begin = 0 |
| 574 | end = len(str.Meta.Value) - 1 |
| 575 | default: |
| 576 | return nil, ErrSyntax |
| 577 | } |
| 578 | |
| 579 | val, err := str.BitCount(begin, end) |
| 580 | if err != nil { |
| 581 | return nil, errors.New("ERR " + err.Error()) |
| 582 | } |
| 583 | return Integer(ctx.Out, int64(val)), nil |
| 584 | } |
| 585 | |
| 586 | // BitPos finds first bit set or clear in a string |
| 587 | func BitPos(ctx *Context, txn *db.Transaction) (OnCommit, error) { |