ledisdb/ledis/util.go

104 lines
2.1 KiB
Go
Raw Permalink Normal View History

2014-05-09 10:49:22 +04:00
package ledis
2014-05-09 05:17:28 +04:00
import (
"encoding/binary"
"errors"
"strconv"
2015-05-04 17:42:28 +03:00
"github.com/siddontang/go/hack"
2014-05-09 05:17:28 +04:00
)
var errIntNumber = errors.New("invalid integer")
2014-09-24 09:29:27 +04:00
/*
Below I forget why I use little endian to store int.
Maybe I was foolish at that time.
*/
2018-03-29 15:33:36 +03:00
// Int64 gets 64 integer with the little endian format.
2014-05-09 05:17:28 +04:00
func Int64(v []byte, err error) (int64, error) {
if err != nil {
return 0, err
} else if v == nil || len(v) == 0 {
return 0, nil
} else if len(v) != 8 {
return 0, errIntNumber
}
return int64(binary.LittleEndian.Uint64(v)), nil
}
2018-03-29 15:33:36 +03:00
// Uint64 gets unsigned 64 integer.
2014-09-17 19:06:42 +04:00
func Uint64(v []byte, err error) (uint64, error) {
if err != nil {
return 0, err
} else if v == nil || len(v) == 0 {
return 0, nil
} else if len(v) != 8 {
return 0, errIntNumber
}
return binary.LittleEndian.Uint64(v), nil
}
2018-03-29 15:33:36 +03:00
// PutInt64 puts the 64 integer.
2014-05-09 05:17:28 +04:00
func PutInt64(v int64) []byte {
2014-09-24 09:29:27 +04:00
b := make([]byte, 8)
binary.LittleEndian.PutUint64(b, uint64(v))
return b
}
2018-03-29 15:33:36 +03:00
// StrInt64 gets the 64 integer with string format.
func StrInt64(v []byte, err error) (int64, error) {
if err != nil {
return 0, err
} else if v == nil {
return 0, nil
} else {
2014-09-24 08:34:21 +04:00
return strconv.ParseInt(hack.String(v), 10, 64)
}
2014-05-09 05:17:28 +04:00
}
2018-03-29 15:33:36 +03:00
// StrUint64 gets the unsigned 64 integer with string format.
func StrUint64(v []byte, err error) (uint64, error) {
if err != nil {
return 0, err
} else if v == nil {
return 0, nil
} else {
2014-09-24 08:34:21 +04:00
return strconv.ParseUint(hack.String(v), 10, 64)
}
}
2018-03-29 15:33:36 +03:00
// StrInt32 gets the 32 integer with string format.
2014-07-08 13:10:44 +04:00
func StrInt32(v []byte, err error) (int32, error) {
if err != nil {
return 0, err
} else if v == nil {
return 0, nil
} else {
2014-09-24 08:34:21 +04:00
res, err := strconv.ParseInt(hack.String(v), 10, 32)
2014-07-08 13:10:44 +04:00
return int32(res), err
}
}
2018-03-29 15:33:36 +03:00
// StrInt8 ets the 8 integer with string format.
2014-07-08 13:10:44 +04:00
func StrInt8(v []byte, err error) (int8, error) {
if err != nil {
return 0, err
} else if v == nil {
return 0, nil
} else {
2014-09-24 08:34:21 +04:00
res, err := strconv.ParseInt(hack.String(v), 10, 8)
2014-07-08 13:10:44 +04:00
return int8(res), err
}
}
2018-03-29 15:33:36 +03:00
// AsyncNotify notices the channel.
func AsyncNotify(ch chan struct{}) {
select {
case ch <- struct{}{}:
default:
}
}