github.com/insionng/yougam@v0.0.0-20170714101924-2bc18d833463/libraries/pingcap/tidb/kv/utils.go (about)

     1  // Copyright 2015 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package kv
    15  
    16  import (
    17  	"strconv"
    18  
    19  	"github.com/insionng/yougam/libraries/juju/errors"
    20  )
    21  
    22  // IncInt64 increases the value for key k in kv store by step.
    23  func IncInt64(rm RetrieverMutator, k Key, step int64) (int64, error) {
    24  	val, err := rm.Get(k)
    25  	if IsErrNotFound(err) {
    26  		err = rm.Set(k, []byte(strconv.FormatInt(step, 10)))
    27  		if err != nil {
    28  			return 0, errors.Trace(err)
    29  		}
    30  		return step, nil
    31  	}
    32  	if err != nil {
    33  		return 0, errors.Trace(err)
    34  	}
    35  
    36  	intVal, err := strconv.ParseInt(string(val), 10, 0)
    37  	if err != nil {
    38  		return 0, errors.Trace(err)
    39  	}
    40  
    41  	intVal += step
    42  	err = rm.Set(k, []byte(strconv.FormatInt(intVal, 10)))
    43  	if err != nil {
    44  		return 0, errors.Trace(err)
    45  	}
    46  	return intVal, nil
    47  }
    48  
    49  // GetInt64 get int64 value which created by IncInt64 method.
    50  func GetInt64(r Retriever, k Key) (int64, error) {
    51  	val, err := r.Get(k)
    52  	if IsErrNotFound(err) {
    53  		return 0, nil
    54  	}
    55  	if err != nil {
    56  		return 0, errors.Trace(err)
    57  	}
    58  	intVal, err := strconv.ParseInt(string(val), 10, 0)
    59  	return intVal, errors.Trace(err)
    60  }