github.com/turingchain2020/turingchain@v1.1.21/common/db/table/count.go (about)

     1  // Copyright Turing Corp. 2018 All Rights Reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package table
     6  
     7  import (
     8  	"math"
     9  
    10  	"github.com/turingchain2020/turingchain/common/db"
    11  	"github.com/turingchain2020/turingchain/types"
    12  )
    13  
    14  //Count 计数器
    15  type Count struct {
    16  	prefix  string
    17  	name    string
    18  	kvdb    db.KV
    19  	num     int64
    20  	keydata []byte
    21  }
    22  
    23  //NewCount 创建一个计数器
    24  func NewCount(prefix string, name string, kvdb db.KV) *Count {
    25  	keydata := []byte(prefix + sep + name)
    26  	return &Count{
    27  		prefix:  prefix,
    28  		name:    name,
    29  		kvdb:    kvdb,
    30  		keydata: keydata,
    31  		num:     math.MinInt64,
    32  	}
    33  }
    34  
    35  func (c *Count) getKey() []byte {
    36  	return c.keydata
    37  }
    38  
    39  //Save 保存kv
    40  func (c *Count) Save() (kvs []*types.KeyValue, err error) {
    41  	if c.num == math.MinInt64 {
    42  		return nil, nil
    43  	}
    44  	var i types.Int64
    45  	i.Data = c.num
    46  	item := &types.KeyValue{Key: c.getKey(), Value: types.Encode(&i)}
    47  	kvs = append(kvs, item)
    48  	return
    49  }
    50  
    51  //Get count
    52  func (c *Count) Get() (int64, error) {
    53  	if c.num == math.MinInt64 {
    54  		data, err := c.kvdb.Get(c.getKey())
    55  		if err == types.ErrNotFound {
    56  			c.num = 0
    57  		} else if err != nil {
    58  			return 0, err
    59  		}
    60  		var num types.Int64
    61  		err = types.Decode(data, &num)
    62  		if err != nil {
    63  			return 0, err
    64  		}
    65  		c.num = num.Data
    66  	}
    67  	return c.num, nil
    68  }
    69  
    70  //Inc 增加1
    71  func (c *Count) Inc() (num int64, err error) {
    72  	c.num, err = c.Get()
    73  	if err != nil {
    74  		return 0, err
    75  	}
    76  	c.num++
    77  	return c.num, nil
    78  }
    79  
    80  //Dec 减少1
    81  func (c *Count) Dec() (num int64, err error) {
    82  	c.num, err = c.Get()
    83  	if err != nil {
    84  		return 0, err
    85  	}
    86  	c.num--
    87  	return c.num, nil
    88  }
    89  
    90  //Set 这个操作要谨慎使用
    91  func (c *Count) Set(i int64) {
    92  	c.num = i
    93  }