/
bytes.go
67 lines (59 loc) · 1.44 KB
/
bytes.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
package data
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
cbg "github.com/whyrusleeping/cbor-gen"
)
// Represents the "bytes" type from the atproto data model.
//
// In JSON, marshals to an object with $bytes key and base64-encoded data.
//
// In CBOR, marshals to a byte array.
type Bytes []byte
type JsonBytes struct {
Bytes string `json:"$bytes"`
}
func (lb Bytes) MarshalJSON() ([]byte, error) {
if lb == nil {
return nil, fmt.Errorf("tried to marshal nil $bytes")
}
jb := JsonBytes{
Bytes: base64.RawStdEncoding.EncodeToString([]byte(lb)),
}
return json.Marshal(jb)
}
func (lb *Bytes) UnmarshalJSON(raw []byte) error {
var jb JsonBytes
err := json.Unmarshal(raw, &jb)
if err != nil {
return fmt.Errorf("parsing $bytes JSON: %v", err)
}
out, err := base64.RawStdEncoding.DecodeString(jb.Bytes)
if err != nil {
return fmt.Errorf("parsing $bytes base64: %v", err)
}
*lb = Bytes(out)
return nil
}
func (lb *Bytes) MarshalCBOR(w io.Writer) error {
if lb == nil {
_, err := w.Write(cbg.CborNull)
return err
}
cw := cbg.NewCborWriter(w)
if err := cbg.WriteByteArray(cw, ([]byte)(*lb)); err != nil {
return fmt.Errorf("failed to write $bytes as CBOR: %w", err)
}
return nil
}
func (lb *Bytes) UnmarshalCBOR(r io.Reader) error {
cr := cbg.NewCborReader(r)
b, err := cbg.ReadByteArray(cr, MAX_RECORD_BYTES_LEN)
if err != nil {
return fmt.Errorf("failed to read $bytes from CBOR: %w", err)
}
*lb = Bytes(b)
return nil
}