-
Notifications
You must be signed in to change notification settings - Fork 82
/
serialization_noop.go
109 lines (95 loc) · 2.5 KB
/
serialization_noop.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package codec
import (
"errors"
"fmt"
)
func init() {
RegisterSerializer(SerializationTypeNoop, &NoopSerialization{})
}
// BytesBodyIn is used to check if Body implements BytesBodyIn
// method when compile.
var _ BytesBodyIn = &Body{}
// BytesBodyIn is used to check if Body implements BytesBodyOut
// method when compile.
var _ BytesBodyOut = &Body{}
// BytesBodyOut is used to receive custom type body.
type BytesBodyOut interface {
Bytes() ([]byte, error)
}
// BytesBodyIn is used to receive custom type body.
type BytesBodyIn interface {
SetBytes([]byte) error
}
// Body is bytes pack layer, it is not need serialized
// and used in gateway service generally.
type Body struct {
Data []byte
}
// String returns body data as string.
func (b *Body) String() string {
return fmt.Sprintf("%v", b.Data)
}
// SetBytes sets body data and implements ByteBodyIn interface.
func (b *Body) SetBytes(p []byte) error {
if b == nil {
return errors.New("body nil")
}
b.Data = p
return nil
}
// Bytes returns body data and implements ByteBodyOut interface.
func (b *Body) Bytes() ([]byte, error) {
if b == nil {
return nil, errors.New("body nil")
}
return b.Data, nil
}
// NoopSerialization provides empty serialization, it is
// used to serialize bytes.
type NoopSerialization struct {
}
// Unmarshal deserializes the in bytes into body, body should be a Body or implements
// BytesBodyIn interface.
func (s *NoopSerialization) Unmarshal(in []byte, body interface{}) error {
bytesBodyIn, ok := body.(BytesBodyIn)
if ok {
return bytesBodyIn.SetBytes(in)
}
noop, ok := body.(*Body)
if !ok {
return errors.New("body type invalid")
}
if noop == nil {
return errors.New("body nil")
}
noop.Data = in
return nil
}
// Marshal returns the serialized bytes. body should be a Body or implements
// BytesBodyOut interface.
func (s *NoopSerialization) Marshal(body interface{}) ([]byte, error) {
bytesBody, ok := body.(BytesBodyOut)
if ok {
return bytesBody.Bytes()
}
noop, ok := body.(*Body)
if !ok {
return nil, errors.New("body type invalid")
}
if noop == nil {
return nil, errors.New("body nil")
}
return noop.Data, nil
}