-
Notifications
You must be signed in to change notification settings - Fork 11
/
segmentid.go
76 lines (61 loc) · 2.16 KB
/
segmentid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Copyright (C) 2019 Storj Labs, Inc.
// See LICENSE for copying information.
package storj
import (
"github.com/zeebo/errs"
)
// ErrSegmentID is used when something goes wrong with a segment ID.
var ErrSegmentID = errs.Class("segment ID")
// SegmentID is the unique identifier for segment related to object.
type SegmentID []byte
// SegmentIDFromString decodes an base32 encoded.
func SegmentIDFromString(s string) (SegmentID, error) {
idBytes, err := base32Encoding.DecodeString(s)
if err != nil {
return SegmentID{}, ErrSegmentID.Wrap(err)
}
return SegmentIDFromBytes(idBytes)
}
// SegmentIDFromBytes converts a byte slice into a segment ID.
func SegmentIDFromBytes(b []byte) (SegmentID, error) {
// return error will be used in future implementation
id := make([]byte, len(b))
copy(id, b)
return id, nil
}
// IsZero returns whether segment ID is unassigned.
func (id SegmentID) IsZero() bool {
return len(id) == 0
}
// String representation of the segment ID.
func (id SegmentID) String() string { return base32Encoding.EncodeToString(id.Bytes()) }
// Bytes returns bytes of the segment ID.
func (id SegmentID) Bytes() []byte { return id[:] }
// Marshal serializes a segment ID (implements gogo's custom type interface).
func (id SegmentID) Marshal() ([]byte, error) {
return id.Bytes(), nil
}
// MarshalTo serializes a segment ID into the passed byte slice (implements gogo's custom type interface).
func (id *SegmentID) MarshalTo(data []byte) (n int, err error) {
return copy(data, id.Bytes()), nil
}
// Unmarshal deserializes a segment ID (implements gogo's custom type interface).
func (id *SegmentID) Unmarshal(data []byte) error {
var err error
*id, err = SegmentIDFromBytes(data)
return err
}
// Size returns the length of a segment ID (implements gogo's custom type interface).
func (id SegmentID) Size() int {
return len(id)
}
// MarshalText serializes a segment ID to a base32 string.
func (id SegmentID) MarshalText() ([]byte, error) {
return []byte(id.String()), nil
}
// UnmarshalText deserializes a base32 string to a segment ID.
func (id *SegmentID) UnmarshalText(data []byte) error {
var err error
*id, err = SegmentIDFromString(string(data))
return err
}