Debian Codegraph @

encoders/protobuf/protobuf_enc.go

raw
1 // Copyright 2015-2023 The NATS Authors
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package protobuf
15
16 import (
17 "errors"
18
19 "github.com/nats-io/nats.go"
20 "google.golang.org/protobuf/proto"
21 )
22
23 //lint:file-ignore SA1019 Ignore deprecation warnings for EncodedConn
24
25 // Additional index for registered Encoders.
26 const (
27 PROTOBUF_ENCODER = "protobuf"
28 )
29
30 func init() {
31 // Register protobuf encoder
32 nats.RegisterEncoder(PROTOBUF_ENCODER, &ProtobufEncoder{})
33 }
34
35 // ProtobufEncoder is a protobuf implementation for EncodedConn
36 // This encoder will use the builtin protobuf lib to Marshal
37 // and Unmarshal structs.
38 //
39 // Deprecated: Encoded connections are no longer supported.
40 type ProtobufEncoder struct {
41 // Empty
42 }
43
44 var (
45 ErrInvalidProtoMsgEncode = errors.New("nats: Invalid protobuf proto.Message object passed to encode")
46 ErrInvalidProtoMsgDecode = errors.New("nats: Invalid protobuf proto.Message object passed to decode")
47 )
48
49 // Encode
50 //
51 // Deprecated: Encoded connections are no longer supported.
52 func (pb *ProtobufEncoder) Encode(subject string, v any) ([]byte, error) {
53 if v == nil {
54 return nil, nil
55 }
56 i, found := v.(proto.Message)
57 if !found {
58 return nil, ErrInvalidProtoMsgEncode
59 }
60
61 b, err := proto.Marshal(i)
62 if err != nil {
63 return nil, err
64 }
65 return b, nil
66 }
67
68 // Decode
69 //
70 // Deprecated: Encoded connections are no longer supported.
71 func (pb *ProtobufEncoder) Decode(subject string, data []byte, vPtr any) error {
72 if _, ok := vPtr.(*any); ok {
73 return nil
74 }
75 i, found := vPtr.(proto.Message)
76 if !found {
77 return ErrInvalidProtoMsgDecode
78 }
79
80 return proto.Unmarshal(data, i)
81 }