-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathintegers.go
41 lines (33 loc) · 1020 Bytes
/
integers.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
package main
import (
"fmt"
"log"
"unsafe"
"golang.org/x/exp/constraints"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/types/known/wrapperspb"
)
// serializedSize calculates the size in memory of data
// and the size after Protobuf serialization of the wrapper.
// It returns two values. The number of bytes for data in memory
// and the number of bytes after serialization of wrapper - 1 (removes the byte for tag + wire type).
func serializedSize[D constraints.Integer, W protoreflect.ProtoMessage](data D, wrapper W) (uintptr, int) {
out, err := proto.Marshal(wrapper)
if err != nil {
log.Fatal(err)
}
return unsafe.Sizeof(data), len(out) - 1
}
func main() {
var data int32 = 268_435_456
i32 := &wrapperspb.Int32Value{
Value: data,
}
// var data uint64 = 72_057_594_037_927_936
// ui64 := &wrapperspb.UInt64Value{
// Value: data,
// }
d, w := serializedSize(data, i32)
fmt.Printf("in memory: %d\npb: %d\n", d, w)
}