restic/backend/id.go

109 lines
1.9 KiB
Go
Raw Normal View History

2014-09-23 22:39:12 +02:00
package backend
2014-04-21 23:25:31 +02:00
import (
"bytes"
2016-01-26 21:49:33 +01:00
"crypto/sha256"
2014-04-21 23:25:31 +02:00
"encoding/hex"
"encoding/json"
2014-09-23 22:39:12 +02:00
"errors"
2014-04-21 23:25:31 +02:00
)
2016-01-26 21:49:33 +01:00
// Hash returns the ID for data.
func Hash(data []byte) ID {
return sha256.Sum256(data)
}
// IDSize contains the size of an ID, in bytes.
2016-01-26 21:49:33 +01:00
const IDSize = sha256.Size
2014-09-23 22:39:12 +02:00
2015-05-02 16:22:43 +02:00
// ID references content within a repository.
type ID [IDSize]byte
2014-04-21 23:25:31 +02:00
// ParseID converts the given string to an ID.
func ParseID(s string) (ID, error) {
b, err := hex.DecodeString(s)
if err != nil {
return ID{}, err
2014-04-21 23:25:31 +02:00
}
if len(b) != IDSize {
return ID{}, errors.New("invalid length for hash")
2014-09-23 22:39:12 +02:00
}
id := ID{}
copy(id[:], b)
return id, nil
2014-04-21 23:25:31 +02:00
}
2014-07-28 20:20:32 +02:00
2014-04-21 23:25:31 +02:00
func (id ID) String() string {
return hex.EncodeToString(id[:])
2014-04-21 23:25:31 +02:00
}
const shortStr = 4
// Str returns the shortened string version of id.
func (id *ID) Str() string {
2015-03-15 19:05:25 +01:00
if id == nil {
return "[nil]"
}
if id.IsNull() {
return "[null]"
}
return hex.EncodeToString(id[:shortStr])
}
// IsNull returns true iff id only consists of null bytes.
func (id ID) IsNull() bool {
var nullID ID
return id == nullID
}
2014-04-21 23:25:31 +02:00
// Equal compares an ID to another other.
func (id ID) Equal(other ID) bool {
return id == other
2014-04-21 23:25:31 +02:00
}
// EqualString compares this ID to another one, given as a string.
func (id ID) EqualString(other string) (bool, error) {
s, err := hex.DecodeString(other)
if err != nil {
return false, err
}
id2 := ID{}
copy(id2[:], s)
return id == id2, nil
2014-04-21 23:25:31 +02:00
}
2014-11-21 21:21:44 +01:00
// Compare compares this ID to another one, returning -1, 0, or 1.
func (id ID) Compare(other ID) int {
return bytes.Compare(other[:], id[:])
2014-11-21 21:21:44 +01:00
}
2016-01-26 21:52:02 +01:00
// MarshalJSON returns the JSON encoding of id.
2014-04-21 23:25:31 +02:00
func (id ID) MarshalJSON() ([]byte, error) {
return json.Marshal(id.String())
}
2016-01-26 21:52:02 +01:00
// UnmarshalJSON parses the JSON-encoded data and stores the result in id.
2014-04-21 23:25:31 +02:00
func (id *ID) UnmarshalJSON(b []byte) error {
var s string
err := json.Unmarshal(b, &s)
if err != nil {
return err
}
_, err = hex.Decode(id[:], []byte(s))
2014-04-21 23:25:31 +02:00
if err != nil {
return err
}
return nil
}