Debian Codegraph @

types.go

raw
1 package desync
2
3 import (
4 "encoding/hex"
5 "encoding/json"
6 "fmt"
7 "strings"
8
9 "github.com/pkg/errors"
10 )
11
12 // ChunkID is the SHA512/256 in binary encoding
13 type ChunkID [32]byte
14
15 // ChunkIDFromSlice converts a SHA512/256 encoded as byte slice into a ChunkID.
16 // It's expected the slice is of the correct length
17 func ChunkIDFromSlice(b []byte) (ChunkID, error) {
18 var c ChunkID
19 if len(b) != len(c) {
20 return c, errors.New("chunk id string not of right size")
21 }
22 copy(c[:], b)
23 return c, nil
24 }
25
26 // ChunkIDFromString converts a SHA512/256 encoded as string into a ChunkID
27 func ChunkIDFromString(id string) (ChunkID, error) {
28 b, err := hex.DecodeString(id)
29 if err != nil {
30 return ChunkID{}, errors.Wrap(err, "failed to decode chunk id string")
31 }
32 return ChunkIDFromSlice(b)
33 }
34
35 func (c ChunkID) String() string {
36 return hex.EncodeToString(c[:])
37 }
38
39 // chunkIDFromFilename extracts the chunk ID from the base filename of a
40 // chunk, which is expected to be the hex-encoded ID followed by the given
41 // storage extension. Returns false if the name doesn't match that format,
42 // for example for chunks stored with different compression or encryption
43 // settings.
44 func chunkIDFromFilename(name, extension string) (ChunkID, bool) {
45 sID, ok := strings.CutSuffix(name, extension)
46 if !ok {
47 return ChunkID{}, false
48 }
49 id, err := ChunkIDFromString(sID)
50 if err != nil {
51 return ChunkID{}, false
52 }
53 return id, true
54 }
55
56 // chunkIDFromObjectName extracts the chunk ID from the name of an object in
57 // a bucket store such as S3 or GCS, which is expected to be the store prefix
58 // followed by the first four characters of the ID, a slash, and the chunk
59 // filename.
60 func chunkIDFromObjectName(name, prefix, extension string) (ChunkID, error) {
61 fragments := strings.Split(strings.TrimPrefix(name, prefix), "/")
62 if len(fragments) != 2 || !strings.HasPrefix(fragments[1], fragments[0]) {
63 return ChunkID{}, fmt.Errorf("incorrect chunk name for object %s", name)
64 }
65 id, ok := chunkIDFromFilename(fragments[1], extension)
66 if !ok {
67 return ChunkID{}, fmt.Errorf("object %s is not a chunk", name)
68 }
69 return id, nil
70 }
71
72 func (c ChunkID) MarshalJSON() ([]byte, error) {
73 return json.Marshal(c.String())
74 }
75
76 func (c *ChunkID) UnmarshalJSON(data []byte) error {
77 var (
78 str string
79 err error
80 )
81 if err = json.Unmarshal(data, &str); err != nil {
82 return err
83 }
84 *c, err = ChunkIDFromString(str)
85 return err
86 }