Debian Codegraph @

internal/controlpb/raw.go

raw
1 package controlpb
2
3 import (
4 "bytes"
5 "errors"
6 )
7
8 // Raw type used by Centrifuge protocol as a type for fields in structs which
9 // value we want to stay untouched. For example custom application specific JSON
10 // payload data in published message. This is very similar to json.RawMessage
11 // type but have some extra methods to fit gogo/protobuf custom type interface.
12 type Raw []byte
13
14 // Marshal encodes Raw to slice of bytes. Exists to fit gogo/protobuf custom
15 // type interface.
16 func (r Raw) Marshal() ([]byte, error) {
17 if len(r) == 0 {
18 return nil, nil
19 }
20 return r, nil
21 }
22
23 // MarshalTo exists to fit gogo/protobuf custom type interface.
24 func (r Raw) MarshalTo(data []byte) (n int, err error) {
25 if len(r) == 0 {
26 return 0, nil
27 }
28 copy(data, r)
29 return len(r), nil
30 }
31
32 // Unmarshal exists to fit gogo/protobuf custom type interface.
33 func (r *Raw) Unmarshal(data []byte) error {
34 if len(data) == 0 {
35 return nil
36 }
37 id := Raw(make([]byte, len(data)))
38 copy(id, data)
39 *r = id
40 return nil
41 }
42
43 // Size exists to fit gogo/protobuf custom type interface.
44 func (r *Raw) Size() int {
45 if r == nil {
46 return 0
47 }
48 return len(*r)
49 }
50
51 // MarshalJSON returns *r as the JSON encoding of r.
52 func (r Raw) MarshalJSON() ([]byte, error) {
53 if r == nil {
54 return []byte("null"), nil
55 }
56 return r, nil
57 }
58
59 // UnmarshalJSON sets *r to a copy of data.
60 func (r *Raw) UnmarshalJSON(data []byte) error {
61 if r == nil {
62 return errors.New("type Raw: UnmarshalJSON on nil pointer")
63 }
64 *r = append((*r)[0:0], data...)
65 return nil
66 }
67
68 // Equal exists to fit gogo/protobuf custom type interface.
69 func (r Raw) Equal(other Raw) bool {
70 return bytes.Equal(r[0:], other[0:])
71 }
72
73 // Compare exists to fit gogo/protobuf custom type interface.
74 func (r Raw) Compare(other Raw) int {
75 return bytes.Compare(r[0:], other[0:])
76 }
77
78 type intn interface {
79 Intn(n int) int
80 }
81
82 // NewPopulatedRaw required for gogoprotobuf custom type.
83 func NewPopulatedRaw(r intn) *Raw {
84 v1 := r.Intn(100)
85 data := make([]byte, v1)
86 for i := 0; i < v1; i++ {
87 data[i] = byte('a')
88 }
89 d := `{"key":"` + string(data) + `"}`
90 raw := Raw(d)
91 return &raw
92 }