diff --git a/record.go b/record.go index eac0325..85a8c2b 100644 --- a/record.go +++ b/record.go @@ -16,7 +16,7 @@ const ( type Record struct { Type RecordType - KeyHash []byte + KeyHash [28]byte ValueBytes []byte } diff --git a/utils.go b/utils.go index 10e0e15..97d63be 100644 --- a/utils.go +++ b/utils.go @@ -17,20 +17,17 @@ func decode(b []byte, value interface{}) error { return gob.NewDecoder(bytes.NewReader(b)).Decode(value) } -func hashInterface(value interface{}) ([]byte, error) { +func hashInterface(value interface{}) ([sha256.Size224]byte, error) { valueBytes, err := encode(value) if err != nil { - return nil, err + return [sha256.Size224]byte{}, err } return hashBytes(valueBytes), nil } -func hashBytes(b []byte) []byte { - bytes := sha256.Sum224(b) - - return bytes[:] - +func hashBytes(b []byte) [sha256.Size224]byte { + return sha256.Sum224(b) } func skip(r io.Reader, count int64) (err error) { diff --git a/zkv.go b/zkv.go index 25fbb94..4df780b 100644 --- a/zkv.go +++ b/zkv.go @@ -47,7 +47,7 @@ func (db *Database) Set(key, value interface{}) error { return err } - db.dataOffset[string(record.KeyHash)] = db.offset // TODO: удалить хеш и откатить запись в случае ошибки + db.dataOffset[string(record.KeyHash[:])] = db.offset // TODO: удалить хеш и откатить запись в случае ошибки _, err = db.compressor.Write(b) if err != nil { @@ -68,7 +68,7 @@ func (db *Database) Get(key, value interface{}) error { return err } - offset, exists := db.dataOffset[string(hashToFind)] + offset, exists := db.dataOffset[string(hashToFind[:])] if !exists { return ErrNotExists } @@ -95,8 +95,8 @@ func (db *Database) Get(key, value interface{}) error { return err } - if !bytes.Equal(record.KeyHash, hashToFind) { - return fmt.Errorf("wrong hash on this offset: expected %s, got %s", base64.StdEncoding.EncodeToString(hashToFind), base64.StdEncoding.EncodeToString(record.KeyHash)) // TODO: заменить на константную ошибку + if !bytes.Equal(record.KeyHash[:], hashToFind[:]) { + return fmt.Errorf("wrong hash on this offset: expected %s, got %s", base64.StdEncoding.EncodeToString(hashToFind[:]), base64.StdEncoding.EncodeToString(record.KeyHash[:])) // TODO: заменить на константную ошибку } return decode(record.ValueBytes, value) @@ -147,9 +147,9 @@ func Open(filePath string) (*Database, error) { switch record.Type { case RecordTypeSet: - database.dataOffset[string(record.KeyHash)] = offset + database.dataOffset[string(record.KeyHash[:])] = offset case RecordTypeDelete: - delete(database.dataOffset, string(record.KeyHash)) + delete(database.dataOffset, string(record.KeyHash[:])) } offset += n @@ -177,7 +177,7 @@ func (db *Database) Delete(key interface{}) error { return err } - delete(db.dataOffset, string(record.KeyHash)) + delete(db.dataOffset, string(record.KeyHash[:])) _, err = db.compressor.Write(b) if err != nil {