From 572a8f2c9a9db49f631d39dbeff55154fec87484 Mon Sep 17 00:00:00 2001 From: holys Date: Thu, 14 Aug 2014 09:15:46 +0800 Subject: [PATCH] fix SAdd logic --- ledis/t_set.go | 24 +++++++++++++++--------- ledis/t_set_test.go | 11 ++++------- 2 files changed, 19 insertions(+), 16 deletions(-) diff --git a/ledis/t_set.go b/ledis/t_set.go index 7bfc170..78a750c 100644 --- a/ledis/t_set.go +++ b/ledis/t_set.go @@ -139,10 +139,6 @@ func (db *DB) sIncrSize(key []byte, delta int64) (int64, error) { db.rmExpire(t, SetType, key) } else { t.Put(sk, PutInt64(size)) - //FIXME - if err := t.Commit(); err != nil { - return 0, err - } } } @@ -189,22 +185,32 @@ func (db *DB) SAdd(key []byte, args ...[]byte) (int64, error) { t.Lock() defer t.Unlock() + var err error + var ek []byte var num int64 = 0 for i := 0; i < len(args); i++ { - member := args[i] - if err := checkSetKMSize(key, member); err != nil { + if err := checkSetKMSize(key, args[i]); err != nil { return 0, err } - if n, err := db.sSetItem(key, member); err != nil { + ek = db.sEncodeSetKey(key, args[i]) + + if v, err := db.db.Get(ek); err != nil { return 0, err - } else if n == 1 { + } else if v == nil { num++ } + + t.Put(ek, nil) } - err := t.Commit() + if _, err = db.sIncrSize(key, num); err != nil { + return 0, err + } + + err = t.Commit() return num, err + } func (db *DB) SCard(key []byte) (int64, error) { diff --git a/ledis/t_set_test.go b/ledis/t_set_test.go index 6518556..2284a68 100644 --- a/ledis/t_set_test.go +++ b/ledis/t_set_test.go @@ -82,21 +82,18 @@ func TestDBSet(t *testing.T) { db.SAdd(key1, member1, member2) - // tx := db.setTx - - // if n := db.sDelete(tx, key1); n != 2 { - // t.Fatal(n) - // } - if n, err := db.SClear(key1); err != nil { t.Fatal(err) } else if n != 2 { t.Fatal(n) } - db.SAdd(key2, member1, member2) db.SAdd(key1, member1, member2) + db.SAdd(key2, member1, member2, []byte("xxx")) + if n, _ := db.SCard(key2); n != 3 { + t.Fatal(n) + } if n, err := db.SMclear(key1, key2); err != nil { t.Fatal(err) } else if n != 2 {