File: raw_codec.go

package info (click to toggle)
gitlab-agent 16.1.3-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 6,324 kB
  • sloc: makefile: 175; sh: 52; ruby: 3
file content (69 lines) | stat: -rw-r--r-- 1,609 bytes parent folder | download | duplicates (2)
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
package grpctool

import (
	"fmt"

	protoenc "google.golang.org/grpc/encoding/proto"
	"google.golang.org/protobuf/proto"
)

type RawFrame struct {
	Data []byte
}

// RawCodec is a *raw* encoding.Codec.
// This codec treats a gRPC message frame as raw bytes.
type RawCodec struct {
}

func (c RawCodec) Marshal(v interface{}) ([]byte, error) {
	out, ok := v.(*RawFrame)
	if !ok {
		return nil, fmt.Errorf("RawCodec.Marshal(): unexpected source message type: %T", v)
	}
	return out.Data, nil
}

func (c RawCodec) Unmarshal(data []byte, v interface{}) error {
	dst, ok := v.(*RawFrame)
	if !ok {
		return fmt.Errorf("RawCodec.Unmarshal(): unexpected target message type: %T", v)
	}
	dst.Data = data
	return nil
}

func (c RawCodec) Name() string {
	// Pretend to be a codec for protobuf.
	return protoenc.Name
}

// RawCodecWithProtoFallback is a *raw* encoding.Codec.
// This codec treats a gRPC message as raw bytes if it's RawFrame and falls back to default proto encoding
// for other message types.
type RawCodecWithProtoFallback struct {
}

func (c RawCodecWithProtoFallback) Marshal(v interface{}) ([]byte, error) {
	out, ok := v.(*RawFrame)
	if !ok {
		// Only works for v2 messages.
		return proto.Marshal(v.(proto.Message))
	}
	return out.Data, nil
}

func (c RawCodecWithProtoFallback) Unmarshal(data []byte, v interface{}) error {
	dst, ok := v.(*RawFrame)
	if !ok {
		// Only works for v2 messages.
		return proto.Unmarshal(data, v.(proto.Message))
	}
	dst.Data = data
	return nil
}

func (c RawCodecWithProtoFallback) Name() string {
	// Pretend to be a codec for protobuf.
	return protoenc.Name
}