value_unsafe.go

 1// Copyright 2018 The Go Authors. All rights reserved.
 2// Use of this source code is governed by a BSD-style
 3// license that can be found in the LICENSE file.
 4
 5package protoreflect
 6
 7import (
 8	"unsafe"
 9
10	"google.golang.org/protobuf/internal/pragma"
11)
12
13type (
14	ifaceHeader struct {
15		_    [0]any // if interfaces have greater alignment than unsafe.Pointer, this will enforce it.
16		Type unsafe.Pointer
17		Data unsafe.Pointer
18	}
19)
20
21var (
22	nilType     = typeOf(nil)
23	boolType    = typeOf(*new(bool))
24	int32Type   = typeOf(*new(int32))
25	int64Type   = typeOf(*new(int64))
26	uint32Type  = typeOf(*new(uint32))
27	uint64Type  = typeOf(*new(uint64))
28	float32Type = typeOf(*new(float32))
29	float64Type = typeOf(*new(float64))
30	stringType  = typeOf(*new(string))
31	bytesType   = typeOf(*new([]byte))
32	enumType    = typeOf(*new(EnumNumber))
33)
34
35// typeOf returns a pointer to the Go type information.
36// The pointer is comparable and equal if and only if the types are identical.
37func typeOf(t any) unsafe.Pointer {
38	return (*ifaceHeader)(unsafe.Pointer(&t)).Type
39}
40
41// value is a union where only one type can be represented at a time.
42// The struct is 24B large on 64-bit systems and requires the minimum storage
43// necessary to represent each possible type.
44//
45// The Go GC needs to be able to scan variables containing pointers.
46// As such, pointers and non-pointers cannot be intermixed.
47type value struct {
48	pragma.DoNotCompare // 0B
49
50	// typ stores the type of the value as a pointer to the Go type.
51	typ unsafe.Pointer // 8B
52
53	// ptr stores the data pointer for a String, Bytes, or interface value.
54	ptr unsafe.Pointer // 8B
55
56	// num stores a Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, or
57	// Enum value as a raw uint64.
58	//
59	// It is also used to store the length of a String or Bytes value;
60	// the capacity is ignored.
61	num uint64 // 8B
62}
63
64func valueOfString(v string) Value {
65	return Value{typ: stringType, ptr: unsafe.Pointer(unsafe.StringData(v)), num: uint64(len(v))}
66}
67func valueOfBytes(v []byte) Value {
68	return Value{typ: bytesType, ptr: unsafe.Pointer(unsafe.SliceData(v)), num: uint64(len(v))}
69}
70func valueOfIface(v any) Value {
71	p := (*ifaceHeader)(unsafe.Pointer(&v))
72	return Value{typ: p.Type, ptr: p.Data}
73}
74
75func (v Value) getString() string {
76	return unsafe.String((*byte)(v.ptr), v.num)
77}
78func (v Value) getBytes() []byte {
79	return unsafe.Slice((*byte)(v.ptr), v.num)
80}
81func (v Value) getIface() (x any) {
82	*(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr}
83	return x
84}