1
0
mirror of https://github.com/nxshock/zkv.git synced 2024-11-27 11:21:02 +05:00
zkv/utils.go

55 lines
1.0 KiB
Go
Raw Normal View History

2022-02-16 16:16:29 +05:00
package zkv
2022-02-16 16:08:20 +05:00
import (
"bytes"
"crypto/sha256"
2022-02-16 16:38:50 +05:00
"encoding/gob"
2023-04-16 10:32:58 +05:00
"errors"
2022-02-16 16:08:20 +05:00
"io"
2023-04-16 10:32:58 +05:00
"os"
2022-02-16 16:08:20 +05:00
)
func encode(value interface{}) ([]byte, error) {
buf := new(bytes.Buffer)
2022-02-16 16:38:50 +05:00
err := gob.NewEncoder(buf).Encode(value)
2022-02-16 16:08:20 +05:00
return buf.Bytes(), err
}
func decode(b []byte, value interface{}) error {
2022-02-16 16:38:50 +05:00
return gob.NewDecoder(bytes.NewReader(b)).Decode(value)
2022-02-16 16:08:20 +05:00
}
2022-12-02 21:37:34 +05:00
func hashInterface(value interface{}) ([sha256.Size224]byte, error) {
2022-02-16 16:08:20 +05:00
valueBytes, err := encode(value)
if err != nil {
2022-12-02 21:37:34 +05:00
return [sha256.Size224]byte{}, err
2022-02-16 16:08:20 +05:00
}
return hashBytes(valueBytes), nil
}
2022-12-02 21:37:34 +05:00
func hashBytes(b []byte) [sha256.Size224]byte {
return sha256.Sum224(b)
2022-02-16 16:08:20 +05:00
}
func skip(r io.Reader, count int64) (err error) {
switch r := r.(type) {
case io.Seeker:
_, err = r.Seek(count, io.SeekCurrent)
default:
_, err = io.CopyN(io.Discard, r, count)
2022-02-16 16:08:20 +05:00
}
return err
}
2023-04-16 10:32:58 +05:00
func isFileExists(filePath string) (bool, error) {
if _, err := os.Stat(filePath); err == nil {
return true, nil
} else if errors.Is(err, os.ErrNotExist) {
return false, nil
} else {
return false, err
}
}