repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/protolazy/bufferreader.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/protolazy/bufferreader.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Helper code for parsing a protocol buffer package protolazy import ( "errors" "fmt" "io" "google.golang.org/protobuf/encoding/protowire" ) // BufferReader is a structure encapsulating a protobuf and a current position type BufferReader struct { Buf []byte Pos int } // NewBufferReader creates a new BufferRead from a protobuf func NewBufferReader(buf []byte) BufferReader { return BufferReader{Buf: buf, Pos: 0} } var errOutOfBounds = errors.New("protobuf decoding: out of bounds") var errOverflow = errors.New("proto: integer overflow") func (b *BufferReader) DecodeVarintSlow() (x uint64, err error) { i := b.Pos l := len(b.Buf) for shift := uint(0); shift < 64; shift += 7 { if i >= l { err = io.ErrUnexpectedEOF return } v := b.Buf[i] i++ x |= (uint64(v) & 0x7F) << shift if v < 0x80 { b.Pos = i return } } // The number is too large to represent in a 64-bit value. err = errOverflow return } // decodeVarint decodes a varint at the current position func (b *BufferReader) DecodeVarint() (x uint64, err error) { i := b.Pos buf := b.Buf if i >= len(buf) { return 0, io.ErrUnexpectedEOF } else if buf[i] < 0x80 { b.Pos++ return uint64(buf[i]), nil } else if len(buf)-i < 10 { return b.DecodeVarintSlow() } var v uint64 // we already checked the first byte x = uint64(buf[i]) & 127 i++ v = uint64(buf[i]) i++ x |= (v & 127) << 7 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 14 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 21 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 28 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 35 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 42 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 49 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 56 if v < 128 { goto done } v = uint64(buf[i]) i++ x |= (v & 127) << 63 if v < 128 { goto done } return 0, errOverflow done: b.Pos = i return } // decodeVarint32 decodes a varint32 at the current position func (b *BufferReader) DecodeVarint32() (x uint32, err error) { i := b.Pos buf := b.Buf if i >= len(buf) { return 0, io.ErrUnexpectedEOF } else if buf[i] < 0x80 { b.Pos++ return uint32(buf[i]), nil } else if len(buf)-i < 5 { v, err := b.DecodeVarintSlow() return uint32(v), err } var v uint32 // we already checked the first byte x = uint32(buf[i]) & 127 i++ v = uint32(buf[i]) i++ x |= (v & 127) << 7 if v < 128 { goto done } v = uint32(buf[i]) i++ x |= (v & 127) << 14 if v < 128 { goto done } v = uint32(buf[i]) i++ x |= (v & 127) << 21 if v < 128 { goto done } v = uint32(buf[i]) i++ x |= (v & 127) << 28 if v < 128 { goto done } return 0, errOverflow done: b.Pos = i return } // skipValue skips a value in the protobuf, based on the specified tag func (b *BufferReader) SkipValue(tag uint32) (err error) { wireType := tag & 0x7 switch protowire.Type(wireType) { case protowire.VarintType: err = b.SkipVarint() case protowire.Fixed64Type: err = b.SkipFixed64() case protowire.BytesType: var n uint32 n, err = b.DecodeVarint32() if err == nil { err = b.Skip(int(n)) } case protowire.StartGroupType: err = b.SkipGroup(tag) case protowire.Fixed32Type: err = b.SkipFixed32() default: err = fmt.Errorf("Unexpected wire type (%d)", wireType) } return } // skipGroup skips a group with the specified tag. It executes efficiently using a tag stack func (b *BufferReader) SkipGroup(tag uint32) (err error) { tagStack := make([]uint32, 0, 16) tagStack = append(tagStack, tag) var n uint32 for len(tagStack) > 0 { tag, err = b.DecodeVarint32() if err != nil { return err } switch protowire.Type(tag & 0x7) { case protowire.VarintType: err = b.SkipVarint() case protowire.Fixed64Type: err = b.Skip(8) case protowire.BytesType: n, err = b.DecodeVarint32() if err == nil { err = b.Skip(int(n)) } case protowire.StartGroupType: tagStack = append(tagStack, tag) case protowire.Fixed32Type: err = b.SkipFixed32() case protowire.EndGroupType: if protoFieldNumber(tagStack[len(tagStack)-1]) == protoFieldNumber(tag) { tagStack = tagStack[:len(tagStack)-1] } else { err = fmt.Errorf("end group tag %d does not match begin group tag %d at pos %d", protoFieldNumber(tag), protoFieldNumber(tagStack[len(tagStack)-1]), b.Pos) } } if err != nil { return err } } return nil } // skipVarint effiently skips a varint func (b *BufferReader) SkipVarint() (err error) { i := b.Pos if len(b.Buf)-i < 10 { // Use DecodeVarintSlow() to check for buffer overflow, but ignore result if _, err := b.DecodeVarintSlow(); err != nil { return err } return nil } if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } i++ if b.Buf[i] < 0x80 { goto out } return errOverflow out: b.Pos = i + 1 return nil } // skip skips the specified number of bytes func (b *BufferReader) Skip(n int) (err error) { if len(b.Buf) < b.Pos+n { return io.ErrUnexpectedEOF } b.Pos += n return } // skipFixed64 skips a fixed64 func (b *BufferReader) SkipFixed64() (err error) { return b.Skip(8) } // skipFixed32 skips a fixed32 func (b *BufferReader) SkipFixed32() (err error) { return b.Skip(4) } // skipBytes skips a set of bytes func (b *BufferReader) SkipBytes() (err error) { n, err := b.DecodeVarint32() if err != nil { return err } return b.Skip(int(n)) } // Done returns whether we are at the end of the protobuf func (b *BufferReader) Done() bool { return b.Pos == len(b.Buf) } // Remaining returns how many bytes remain func (b *BufferReader) Remaining() int { return len(b.Buf) - b.Pos }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filetype/build.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filetype/build.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package filetype provides functionality for wrapping descriptors // with Go type information. package filetype import ( "reflect" "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/filedesc" pimpl "google.golang.org/protobuf/internal/impl" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Builder constructs type descriptors from a raw file descriptor // and associated Go types for each enum and message declaration. // // # Flattened Ordering // // The protobuf type system represents declarations as a tree. Certain nodes in // the tree require us to either associate it with a concrete Go type or to // resolve a dependency, which is information that must be provided separately // since it cannot be derived from the file descriptor alone. // // However, representing a tree as Go literals is difficult to simply do in a // space and time efficient way. Thus, we store them as a flattened list of // objects where the serialization order from the tree-based form is important. // // The "flattened ordering" is defined as a tree traversal of all enum, message, // extension, and service declarations using the following algorithm: // // def VisitFileDecls(fd): // for e in fd.Enums: yield e // for m in fd.Messages: yield m // for x in fd.Extensions: yield x // for s in fd.Services: yield s // for m in fd.Messages: yield from VisitMessageDecls(m) // // def VisitMessageDecls(md): // for e in md.Enums: yield e // for m in md.Messages: yield m // for x in md.Extensions: yield x // for m in md.Messages: yield from VisitMessageDecls(m) // // The traversal starts at the root file descriptor and yields each direct // declaration within each node before traversing into sub-declarations // that children themselves may have. type Builder struct { // File is the underlying file descriptor builder. File filedesc.Builder // GoTypes is a unique set of the Go types for all declarations and // dependencies. Each type is represented as a zero value of the Go type. // // Declarations are Go types generated for enums and messages directly // declared (not publicly imported) in the proto source file. // Messages for map entries are accounted for, but represented by nil. // Enum declarations in "flattened ordering" come first, followed by // message declarations in "flattened ordering". // // Dependencies are Go types for enums or messages referenced by // message fields, for parent extended messages of // extension fields, for enums or messages referenced by extension fields, // and for input and output messages referenced by service methods. // Dependencies must come after declarations, but the ordering of // dependencies themselves is unspecified. GoTypes []any // DependencyIndexes is an ordered list of indexes into GoTypes for the // dependencies of messages, extensions, or services. // // There are 5 sub-lists in "flattened ordering" concatenated back-to-back: // 0. Message field dependencies: list of the enum or message type // referred to by every message field. // 1. Extension field targets: list of the extended parent message of // every extension. // 2. Extension field dependencies: list of the enum or message type // referred to by every extension field. // 3. Service method inputs: list of the input message type // referred to by every service method. // 4. Service method outputs: list of the output message type // referred to by every service method. // // The offset into DependencyIndexes for the start of each sub-list // is appended to the end in reverse order. DependencyIndexes []int32 // EnumInfos is a list of enum infos in "flattened ordering". EnumInfos []pimpl.EnumInfo // MessageInfos is a list of message infos in "flattened ordering". // If provided, the GoType and PBType for each element is populated. // // Requirement: len(MessageInfos) == len(Build.Messages) MessageInfos []pimpl.MessageInfo // ExtensionInfos is a list of extension infos in "flattened ordering". // Each element is initialized and registered with the protoregistry package. // // Requirement: len(LegacyExtensions) == len(Build.Extensions) ExtensionInfos []pimpl.ExtensionInfo // TypeRegistry is the registry to register each type descriptor. // If nil, it uses protoregistry.GlobalTypes. TypeRegistry interface { RegisterMessage(protoreflect.MessageType) error RegisterEnum(protoreflect.EnumType) error RegisterExtension(protoreflect.ExtensionType) error } } // Out is the output of the builder. type Out struct { File protoreflect.FileDescriptor } func (tb Builder) Build() (out Out) { // Replace the resolver with one that resolves dependencies by index, // which is faster and more reliable than relying on the global registry. if tb.File.FileRegistry == nil { tb.File.FileRegistry = protoregistry.GlobalFiles } tb.File.FileRegistry = &resolverByIndex{ goTypes: tb.GoTypes, depIdxs: tb.DependencyIndexes, fileRegistry: tb.File.FileRegistry, } // Initialize registry if unpopulated. if tb.TypeRegistry == nil { tb.TypeRegistry = protoregistry.GlobalTypes } fbOut := tb.File.Build() out.File = fbOut.File // Process enums. enumGoTypes := tb.GoTypes[:len(fbOut.Enums)] if len(tb.EnumInfos) != len(fbOut.Enums) { panic("mismatching enum lengths") } if len(fbOut.Enums) > 0 { for i := range fbOut.Enums { tb.EnumInfos[i] = pimpl.EnumInfo{ GoReflectType: reflect.TypeOf(enumGoTypes[i]), Desc: &fbOut.Enums[i], } // Register enum types. if err := tb.TypeRegistry.RegisterEnum(&tb.EnumInfos[i]); err != nil { panic(err) } } } // Process messages. messageGoTypes := tb.GoTypes[len(fbOut.Enums):][:len(fbOut.Messages)] if len(tb.MessageInfos) != len(fbOut.Messages) { panic("mismatching message lengths") } if len(fbOut.Messages) > 0 { for i := range fbOut.Messages { if messageGoTypes[i] == nil { continue // skip map entry } tb.MessageInfos[i].GoReflectType = reflect.TypeOf(messageGoTypes[i]) tb.MessageInfos[i].Desc = &fbOut.Messages[i] // Register message types. if err := tb.TypeRegistry.RegisterMessage(&tb.MessageInfos[i]); err != nil { panic(err) } } // As a special-case for descriptor.proto, // locally register concrete message type for the options. if out.File.Path() == "google/protobuf/descriptor.proto" && out.File.Package() == "google.protobuf" { for i := range fbOut.Messages { switch fbOut.Messages[i].Name() { case "FileOptions": descopts.File = messageGoTypes[i].(protoreflect.ProtoMessage) case "EnumOptions": descopts.Enum = messageGoTypes[i].(protoreflect.ProtoMessage) case "EnumValueOptions": descopts.EnumValue = messageGoTypes[i].(protoreflect.ProtoMessage) case "MessageOptions": descopts.Message = messageGoTypes[i].(protoreflect.ProtoMessage) case "FieldOptions": descopts.Field = messageGoTypes[i].(protoreflect.ProtoMessage) case "OneofOptions": descopts.Oneof = messageGoTypes[i].(protoreflect.ProtoMessage) case "ExtensionRangeOptions": descopts.ExtensionRange = messageGoTypes[i].(protoreflect.ProtoMessage) case "ServiceOptions": descopts.Service = messageGoTypes[i].(protoreflect.ProtoMessage) case "MethodOptions": descopts.Method = messageGoTypes[i].(protoreflect.ProtoMessage) } } } } // Process extensions. if len(tb.ExtensionInfos) != len(fbOut.Extensions) { panic("mismatching extension lengths") } var depIdx int32 for i := range fbOut.Extensions { // For enum and message kinds, determine the referent Go type so // that we can construct their constructors. const listExtDeps = 2 var goType reflect.Type switch fbOut.Extensions[i].L1.Kind { case protoreflect.EnumKind: j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) goType = reflect.TypeOf(tb.GoTypes[j]) depIdx++ case protoreflect.MessageKind, protoreflect.GroupKind: j := depIdxs.Get(tb.DependencyIndexes, listExtDeps, depIdx) goType = reflect.TypeOf(tb.GoTypes[j]) depIdx++ default: goType = goTypeForPBKind[fbOut.Extensions[i].L1.Kind] } if fbOut.Extensions[i].IsList() { goType = reflect.SliceOf(goType) } pimpl.InitExtensionInfo(&tb.ExtensionInfos[i], &fbOut.Extensions[i], goType) // Register extension types. if err := tb.TypeRegistry.RegisterExtension(&tb.ExtensionInfos[i]); err != nil { panic(err) } } return out } var goTypeForPBKind = map[protoreflect.Kind]reflect.Type{ protoreflect.BoolKind: reflect.TypeOf(bool(false)), protoreflect.Int32Kind: reflect.TypeOf(int32(0)), protoreflect.Sint32Kind: reflect.TypeOf(int32(0)), protoreflect.Sfixed32Kind: reflect.TypeOf(int32(0)), protoreflect.Int64Kind: reflect.TypeOf(int64(0)), protoreflect.Sint64Kind: reflect.TypeOf(int64(0)), protoreflect.Sfixed64Kind: reflect.TypeOf(int64(0)), protoreflect.Uint32Kind: reflect.TypeOf(uint32(0)), protoreflect.Fixed32Kind: reflect.TypeOf(uint32(0)), protoreflect.Uint64Kind: reflect.TypeOf(uint64(0)), protoreflect.Fixed64Kind: reflect.TypeOf(uint64(0)), protoreflect.FloatKind: reflect.TypeOf(float32(0)), protoreflect.DoubleKind: reflect.TypeOf(float64(0)), protoreflect.StringKind: reflect.TypeOf(string("")), protoreflect.BytesKind: reflect.TypeOf([]byte(nil)), } type depIdxs []int32 // Get retrieves the jth element of the ith sub-list. func (x depIdxs) Get(i, j int32) int32 { return x[x[int32(len(x))-i-1]+j] } type ( resolverByIndex struct { goTypes []any depIdxs depIdxs fileRegistry } fileRegistry interface { FindFileByPath(string) (protoreflect.FileDescriptor, error) FindDescriptorByName(protoreflect.FullName) (protoreflect.Descriptor, error) RegisterFile(protoreflect.FileDescriptor) error } ) func (r *resolverByIndex) FindEnumByIndex(i, j int32, es []filedesc.Enum, ms []filedesc.Message) protoreflect.EnumDescriptor { if depIdx := int(r.depIdxs.Get(i, j)); int(depIdx) < len(es)+len(ms) { return &es[depIdx] } else { return pimpl.Export{}.EnumDescriptorOf(r.goTypes[depIdx]) } } func (r *resolverByIndex) FindMessageByIndex(i, j int32, es []filedesc.Enum, ms []filedesc.Message) protoreflect.MessageDescriptor { if depIdx := int(r.depIdxs.Get(i, j)); depIdx < len(es)+len(ms) { return &ms[depIdx-len(es)] } else { return pimpl.Export{}.MessageDescriptorOf(r.goTypes[depIdx]) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/version/version.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/version/version.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package version records versioning information about this module. package version import ( "fmt" "strings" ) // These constants determine the current version of this module. // // For our release process, we enforce the following rules: // - Tagged releases use a tag that is identical to String. // - Tagged releases never reference a commit where the String // contains "devel". // - The set of all commits in this repository where String // does not contain "devel" must have a unique String. // // Steps for tagging a new release: // // 1. Create a new CL. // // 2. Update Minor, Patch, and/or PreRelease as necessary. // PreRelease must not contain the string "devel". // // 3. Since the last released minor version, have there been any changes to // generator that relies on new functionality in the runtime? // If yes, then increment RequiredGenerated. // // 4. Since the last released minor version, have there been any changes to // the runtime that removes support for old .pb.go source code? // If yes, then increment SupportMinimum. // // 5. Send out the CL for review and submit it. // Note that the next CL in step 8 must be submitted after this CL // without any other CLs in-between. // // 6. Tag a new version, where the tag is is the current String. // // 7. Write release notes for all notable changes // between this release and the last release. // // 8. Create a new CL. // // 9. Update PreRelease to include the string "devel". // For example: "" -> "devel" or "rc.1" -> "rc.1.devel" // // 10. Send out the CL for review and submit it. const ( Major = 1 Minor = 36 Patch = 7 PreRelease = "" ) // String formats the version string for this module in semver format. // // Examples: // // v1.20.1 // v1.21.0-rc.1 func String() string { v := fmt.Sprintf("v%d.%d.%d", Major, Minor, Patch) if PreRelease != "" { v += "-" + PreRelease // TODO: Add metadata about the commit or build hash. // See https://golang.org/issue/29814 // See https://golang.org/issue/33533 var metadata string if strings.Contains(PreRelease, "devel") && metadata != "" { v += "+" + metadata } } return v }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/pragma/pragma.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/pragma/pragma.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package pragma provides types that can be embedded into a struct to // statically enforce or prevent certain language properties. package pragma import "sync" // NoUnkeyedLiterals can be embedded in a struct to prevent unkeyed literals. type NoUnkeyedLiterals struct{} // DoNotImplement can be embedded in an interface to prevent trivial // implementations of the interface. // // This is useful to prevent unauthorized implementations of an interface // so that it can be extended in the future for any protobuf language changes. type DoNotImplement interface{ ProtoInternal(DoNotImplement) } // DoNotCompare can be embedded in a struct to prevent comparability. type DoNotCompare [0]func() // DoNotCopy can be embedded in a struct to help prevent shallow copies. // This does not rely on a Go language feature, but rather a special case // within the vet checker. // // See https://golang.org/issues/8005. type DoNotCopy [0]sync.Mutex
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/errors/errors.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/errors/errors.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package errors implements functions to manipulate errors. package errors import ( "errors" "fmt" "google.golang.org/protobuf/internal/detrand" ) // Error is a sentinel matching all errors produced by this package. var Error = errors.New("protobuf error") // New formats a string according to the format specifier and arguments and // returns an error that has a "proto" prefix. func New(f string, x ...any) error { return &prefixError{s: format(f, x...)} } type prefixError struct{ s string } var prefix = func() string { // Deliberately introduce instability into the error message string to // discourage users from performing error string comparisons. if detrand.Bool() { return "proto: " // use non-breaking spaces (U+00a0) } else { return "proto: " // use regular spaces (U+0020) } }() func (e *prefixError) Error() string { return prefix + e.s } func (e *prefixError) Unwrap() error { return Error } // Wrap returns an error that has a "proto" prefix, the formatted string described // by the format specifier and arguments, and a suffix of err. The error wraps err. func Wrap(err error, f string, x ...any) error { return &wrapError{ s: format(f, x...), err: err, } } type wrapError struct { s string err error } func (e *wrapError) Error() string { return format("%v%v: %v", prefix, e.s, e.err) } func (e *wrapError) Unwrap() error { return e.err } func (e *wrapError) Is(target error) bool { return target == Error } func format(f string, x ...any) string { // avoid "proto: " prefix when chaining for i := 0; i < len(x); i++ { switch e := x[i].(type) { case *prefixError: x[i] = e.s case *wrapError: x[i] = format("%v: %v", e.s, e.err) } } return fmt.Sprintf(f, x...) } func InvalidUTF8(name string) error { return New("field %v contains invalid UTF-8", name) } func RequiredNotSet(name string) error { return New("required field %v not set", name) } type SizeMismatchError struct { Calculated, Measured int } func (e *SizeMismatchError) Error() string { return fmt.Sprintf("size mismatch (see https://github.com/golang/protobuf/issues/1609): calculated=%d, measured=%d", e.Calculated, e.Measured) } func MismatchedSizeCalculation(calculated, measured int) error { return &SizeMismatchError{ Calculated: calculated, Measured: measured, } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/editiondefaults/defaults.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/editiondefaults/defaults.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package editiondefaults contains the binary representation of the editions // defaults. package editiondefaults import _ "embed" //go:embed editions_defaults.binpb var Defaults []byte
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/flags.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/flags.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package flags provides a set of flags controlled by build tags. package flags // ProtoLegacy specifies whether to enable support for legacy functionality // such as MessageSets, and various other obscure behavior // that is necessary to maintain backwards compatibility with proto1 or // the pre-release variants of proto2 and proto3. // // This is disabled by default unless built with the "protolegacy" tag. // // WARNING: The compatibility agreement covers nothing provided by this flag. // As such, functionality may suddenly be removed or changed at our discretion. const ProtoLegacy = protoLegacy // LazyUnmarshalExtensions specifies whether to lazily unmarshal extensions. // // Lazy extension unmarshaling validates the contents of message-valued // extension fields at unmarshal time, but defers creating the message // structure until the extension is first accessed. const LazyUnmarshalExtensions = ProtoLegacy
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_disable.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !protolegacy // +build !protolegacy package flags const protoLegacy = false
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/flags/proto_legacy_enable.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build protolegacy // +build protolegacy package flags const protoLegacy = true
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_message.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_message.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "sort" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // coderMessageInfo contains per-message information used by the fast-path functions. // This is a different type from MessageInfo to keep MessageInfo as general-purpose as // possible. type coderMessageInfo struct { methods protoiface.Methods orderedCoderFields []*coderFieldInfo denseCoderFields []*coderFieldInfo coderFields map[protowire.Number]*coderFieldInfo sizecacheOffset offset unknownOffset offset unknownPtrKind bool extensionOffset offset needsInitCheck bool isMessageSet bool numRequiredFields uint8 lazyOffset offset presenceOffset offset presenceSize presenceSize } type coderFieldInfo struct { funcs pointerCoderFuncs // fast-path per-field functions mi *MessageInfo // field's message ft reflect.Type validation validationInfo // information used by message validation num protoreflect.FieldNumber // field number offset offset // struct field offset wiretag uint64 // field tag (number + wire type) tagsize int // size of the varint-encoded tag isPointer bool // true if IsNil may be called on the struct field isRequired bool // true if field is required isLazy bool presenceIndex uint32 } const noPresence = 0xffffffff func (mi *MessageInfo) makeCoderMethods(t reflect.Type, si structInfo) { mi.sizecacheOffset = invalidOffset mi.unknownOffset = invalidOffset mi.extensionOffset = invalidOffset mi.lazyOffset = invalidOffset mi.presenceOffset = si.presenceOffset if si.sizecacheOffset.IsValid() && si.sizecacheType == sizecacheType { mi.sizecacheOffset = si.sizecacheOffset } if si.unknownOffset.IsValid() && (si.unknownType == unknownFieldsAType || si.unknownType == unknownFieldsBType) { mi.unknownOffset = si.unknownOffset mi.unknownPtrKind = si.unknownType.Kind() == reflect.Ptr } if si.extensionOffset.IsValid() && si.extensionType == extensionFieldsType { mi.extensionOffset = si.extensionOffset } mi.coderFields = make(map[protowire.Number]*coderFieldInfo) fields := mi.Desc.Fields() preallocFields := make([]coderFieldInfo, fields.Len()) for i := 0; i < fields.Len(); i++ { fd := fields.Get(i) fs := si.fieldsByNumber[fd.Number()] isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic() if isOneof { fs = si.oneofsByName[fd.ContainingOneof().Name()] } ft := fs.Type var wiretag uint64 if !fd.IsPacked() { wiretag = protowire.EncodeTag(fd.Number(), wireTypes[fd.Kind()]) } else { wiretag = protowire.EncodeTag(fd.Number(), protowire.BytesType) } var fieldOffset offset var funcs pointerCoderFuncs var childMessage *MessageInfo switch { case ft == nil: // This never occurs for generated message types. // It implies that a hand-crafted type has missing Go fields // for specific protobuf message fields. funcs = pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { return 0 }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { return nil, nil }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { panic("missing Go struct field for " + string(fd.FullName())) }, isInit: func(p pointer, f *coderFieldInfo) error { panic("missing Go struct field for " + string(fd.FullName())) }, merge: func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { panic("missing Go struct field for " + string(fd.FullName())) }, } case isOneof: fieldOffset = offsetOf(fs) default: fieldOffset = offsetOf(fs) childMessage, funcs = fieldCoder(fd, ft) } cf := &preallocFields[i] *cf = coderFieldInfo{ num: fd.Number(), offset: fieldOffset, wiretag: wiretag, ft: ft, tagsize: protowire.SizeVarint(wiretag), funcs: funcs, mi: childMessage, validation: newFieldValidationInfo(mi, si, fd, ft), isPointer: fd.Cardinality() == protoreflect.Repeated || fd.HasPresence(), isRequired: fd.Cardinality() == protoreflect.Required, presenceIndex: noPresence, } mi.orderedCoderFields = append(mi.orderedCoderFields, cf) mi.coderFields[cf.num] = cf } for i, oneofs := 0, mi.Desc.Oneofs(); i < oneofs.Len(); i++ { if od := oneofs.Get(i); !od.IsSynthetic() { mi.initOneofFieldCoders(od, si) } } if messageset.IsMessageSet(mi.Desc) { if !mi.extensionOffset.IsValid() { panic(fmt.Sprintf("%v: MessageSet with no extensions field", mi.Desc.FullName())) } if !mi.unknownOffset.IsValid() { panic(fmt.Sprintf("%v: MessageSet with no unknown field", mi.Desc.FullName())) } mi.isMessageSet = true } sort.Slice(mi.orderedCoderFields, func(i, j int) bool { return mi.orderedCoderFields[i].num < mi.orderedCoderFields[j].num }) var maxDense protoreflect.FieldNumber for _, cf := range mi.orderedCoderFields { if cf.num >= 16 && cf.num >= 2*maxDense { break } maxDense = cf.num } mi.denseCoderFields = make([]*coderFieldInfo, maxDense+1) for _, cf := range mi.orderedCoderFields { if int(cf.num) >= len(mi.denseCoderFields) { break } mi.denseCoderFields[cf.num] = cf } // To preserve compatibility with historic wire output, marshal oneofs last. if mi.Desc.Oneofs().Len() > 0 { sort.Slice(mi.orderedCoderFields, func(i, j int) bool { fi := fields.ByNumber(mi.orderedCoderFields[i].num) fj := fields.ByNumber(mi.orderedCoderFields[j].num) return order.LegacyFieldOrder(fi, fj) }) } mi.needsInitCheck = needsInitCheck(mi.Desc) if mi.methods.Marshal == nil && mi.methods.Size == nil { mi.methods.Flags |= protoiface.SupportMarshalDeterministic mi.methods.Marshal = mi.marshal mi.methods.Size = mi.size } if mi.methods.Unmarshal == nil { mi.methods.Flags |= protoiface.SupportUnmarshalDiscardUnknown mi.methods.Unmarshal = mi.unmarshal } if mi.methods.CheckInitialized == nil { mi.methods.CheckInitialized = mi.checkInitialized } if mi.methods.Merge == nil { mi.methods.Merge = mi.merge } if mi.methods.Equal == nil { mi.methods.Equal = equal } } // getUnknownBytes returns a *[]byte for the unknown fields. // It is the caller's responsibility to check whether the pointer is nil. // This function is specially designed to be inlineable. func (mi *MessageInfo) getUnknownBytes(p pointer) *[]byte { if mi.unknownPtrKind { return *p.Apply(mi.unknownOffset).BytesPtr() } else { return p.Apply(mi.unknownOffset).Bytes() } } // mutableUnknownBytes returns a *[]byte for the unknown fields. // The returned pointer is guaranteed to not be nil. func (mi *MessageInfo) mutableUnknownBytes(p pointer) *[]byte { if mi.unknownPtrKind { bp := p.Apply(mi.unknownOffset).BytesPtr() if *bp == nil { *bp = new([]byte) } return *bp } else { return p.Apply(mi.unknownOffset).Bytes() } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/merge.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/merge.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) type mergeOptions struct{} func (o mergeOptions) Merge(dst, src proto.Message) { proto.Merge(dst, src) } // merge is protoreflect.Methods.Merge. func (mi *MessageInfo) merge(in protoiface.MergeInput) protoiface.MergeOutput { dp, ok := mi.getPointer(in.Destination) if !ok { return protoiface.MergeOutput{} } sp, ok := mi.getPointer(in.Source) if !ok { return protoiface.MergeOutput{} } mi.mergePointer(dp, sp, mergeOptions{}) return protoiface.MergeOutput{Flags: protoiface.MergeComplete} } func (mi *MessageInfo) mergePointer(dst, src pointer, opts mergeOptions) { mi.init() if dst.IsNil() { panic(fmt.Sprintf("invalid value: merging into nil message")) } if src.IsNil() { return } var presenceSrc presence var presenceDst presence if mi.presenceOffset.IsValid() { presenceSrc = src.Apply(mi.presenceOffset).PresenceInfo() presenceDst = dst.Apply(mi.presenceOffset).PresenceInfo() } for _, f := range mi.orderedCoderFields { if f.funcs.merge == nil { continue } sfptr := src.Apply(f.offset) if f.presenceIndex != noPresence { if !presenceSrc.Present(f.presenceIndex) { continue } dfptr := dst.Apply(f.offset) if f.isLazy { if sfptr.AtomicGetPointer().IsNil() { mi.lazyUnmarshal(src, f.num) } if presenceDst.Present(f.presenceIndex) && dfptr.AtomicGetPointer().IsNil() { mi.lazyUnmarshal(dst, f.num) } } f.funcs.merge(dst.Apply(f.offset), sfptr, f, opts) presenceDst.SetPresentUnatomic(f.presenceIndex, mi.presenceSize) continue } if f.isPointer && sfptr.Elem().IsNil() { continue } f.funcs.merge(dst.Apply(f.offset), sfptr, f, opts) } if mi.extensionOffset.IsValid() { sext := src.Apply(mi.extensionOffset).Extensions() dext := dst.Apply(mi.extensionOffset).Extensions() if *dext == nil { *dext = make(map[int32]ExtensionField) } for num, sx := range *sext { xt := sx.Type() xi := getExtensionFieldInfo(xt) if xi.funcs.merge == nil { continue } dx := (*dext)[num] var dv protoreflect.Value if dx.Type() == sx.Type() { dv = dx.Value() } if !dv.IsValid() && xi.unmarshalNeedsValue { dv = xt.New() } dv = xi.funcs.merge(dv, sx.Value(), opts) dx.Set(sx.Type(), dv) (*dext)[num] = dx } } if mi.unknownOffset.IsValid() { su := mi.getUnknownBytes(src) if su != nil && len(*su) > 0 { du := mi.mutableUnknownBytes(dst) *du = append(*du, *su...) } } } func mergeScalarValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { return src } func mergeBytesValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { return protoreflect.ValueOfBytes(append(emptyBuf[:], src.Bytes()...)) } func mergeListValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { dstl := dst.List() srcl := src.List() for i, llen := 0, srcl.Len(); i < llen; i++ { dstl.Append(srcl.Get(i)) } return dst } func mergeBytesListValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { dstl := dst.List() srcl := src.List() for i, llen := 0, srcl.Len(); i < llen; i++ { sb := srcl.Get(i).Bytes() db := append(emptyBuf[:], sb...) dstl.Append(protoreflect.ValueOfBytes(db)) } return dst } func mergeMessageListValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { dstl := dst.List() srcl := src.List() for i, llen := 0, srcl.Len(); i < llen; i++ { sm := srcl.Get(i).Message() dm := proto.Clone(sm.Interface()).ProtoReflect() dstl.Append(protoreflect.ValueOfMessage(dm)) } return dst } func mergeMessageValue(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value { opts.Merge(dst.Message().Interface(), src.Message().Interface()) return dst } func mergeMessage(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { if f.mi != nil { if dst.Elem().IsNil() { dst.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } f.mi.mergePointer(dst.Elem(), src.Elem(), opts) } else { dm := dst.AsValueOf(f.ft).Elem() sm := src.AsValueOf(f.ft).Elem() if dm.IsNil() { dm.Set(reflect.New(f.ft.Elem())) } opts.Merge(asMessage(dm), asMessage(sm)) } } func mergeMessageSlice(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { for _, sp := range src.PointerSlice() { dm := reflect.New(f.ft.Elem().Elem()) if f.mi != nil { f.mi.mergePointer(pointerOfValue(dm), sp, opts) } else { opts.Merge(asMessage(dm), asMessage(sp.AsValueOf(f.ft.Elem().Elem()))) } dst.AppendPointerSlice(pointerOfValue(dm)) } } func mergeBytes(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Bytes() = append(emptyBuf[:], *src.Bytes()...) } func mergeBytesNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Bytes() if len(v) > 0 { *dst.Bytes() = append(emptyBuf[:], v...) } } func mergeBytesSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.BytesSlice() for _, v := range *src.BytesSlice() { *ds = append(*ds, append(emptyBuf[:], v...)) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/lazy.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/lazy.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "math/bits" "os" "reflect" "sort" "sync/atomic" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/protolazy" "google.golang.org/protobuf/reflect/protoreflect" preg "google.golang.org/protobuf/reflect/protoregistry" piface "google.golang.org/protobuf/runtime/protoiface" ) var enableLazy int32 = func() int32 { if os.Getenv("GOPROTODEBUG") == "nolazy" { return 0 } return 1 }() // EnableLazyUnmarshal enables lazy unmarshaling. func EnableLazyUnmarshal(enable bool) { if enable { atomic.StoreInt32(&enableLazy, 1) return } atomic.StoreInt32(&enableLazy, 0) } // LazyEnabled reports whether lazy unmarshalling is currently enabled. func LazyEnabled() bool { return atomic.LoadInt32(&enableLazy) != 0 } // UnmarshalField unmarshals a field in a message. func UnmarshalField(m interface{}, num protowire.Number) { switch m := m.(type) { case *messageState: m.messageInfo().lazyUnmarshal(m.pointer(), num) case *messageReflectWrapper: m.messageInfo().lazyUnmarshal(m.pointer(), num) default: panic(fmt.Sprintf("unsupported wrapper type %T", m)) } } func (mi *MessageInfo) lazyUnmarshal(p pointer, num protoreflect.FieldNumber) { var f *coderFieldInfo if int(num) < len(mi.denseCoderFields) { f = mi.denseCoderFields[num] } else { f = mi.coderFields[num] } if f == nil { panic(fmt.Sprintf("lazyUnmarshal: field info for %v.%v", mi.Desc.FullName(), num)) } lazy := *p.Apply(mi.lazyOffset).LazyInfoPtr() start, end, found, _, multipleEntries := lazy.FindFieldInProto(uint32(num)) if !found && multipleEntries == nil { panic(fmt.Sprintf("lazyUnmarshal: can't find field data for %v.%v", mi.Desc.FullName(), num)) } // The actual pointer in the message can not be set until the whole struct is filled in, otherwise we will have races. // Create another pointer and set it atomically, if we won the race and the pointer in the original message is still nil. fp := pointerOfValue(reflect.New(f.ft)) if multipleEntries != nil { for _, entry := range multipleEntries { mi.unmarshalField(lazy.Buffer()[entry.Start:entry.End], fp, f, lazy, lazy.UnmarshalFlags()) } } else { mi.unmarshalField(lazy.Buffer()[start:end], fp, f, lazy, lazy.UnmarshalFlags()) } p.Apply(f.offset).AtomicSetPointerIfNil(fp.Elem()) } func (mi *MessageInfo) unmarshalField(b []byte, p pointer, f *coderFieldInfo, lazyInfo *protolazy.XXX_lazyUnmarshalInfo, flags piface.UnmarshalInputFlags) error { opts := lazyUnmarshalOptions opts.flags |= flags for len(b) > 0 { // Parse the tag (field number and wire type). var tag uint64 if b[0] < 0x80 { tag = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int tag, n = protowire.ConsumeVarint(b) if n < 0 { return errors.New("invalid wire data") } b = b[n:] } var num protowire.Number if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { return errors.New("invalid wire data") } else { num = protowire.Number(n) } wtyp := protowire.Type(tag & 7) if num == f.num { o, err := f.funcs.unmarshal(b, p, wtyp, f, opts) if err == nil { b = b[o.n:] continue } if err != errUnknown { return err } } n := protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return errors.New("invalid wire data") } b = b[n:] } return nil } func (mi *MessageInfo) skipField(b []byte, f *coderFieldInfo, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, _ ValidationStatus) { fmi := f.validation.mi if fmi == nil { fd := mi.Desc.Fields().ByNumber(f.num) if fd == nil { return out, ValidationUnknown } messageName := fd.Message().FullName() messageType, err := preg.GlobalTypes.FindMessageByName(messageName) if err != nil { return out, ValidationUnknown } var ok bool fmi, ok = messageType.(*MessageInfo) if !ok { return out, ValidationUnknown } } fmi.init() switch f.validation.typ { case validationTypeMessage: if wtyp != protowire.BytesType { return out, ValidationWrongWireType } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, ValidationInvalid } out, st := fmi.validate(v, 0, opts) out.n = n return out, st case validationTypeGroup: if wtyp != protowire.StartGroupType { return out, ValidationWrongWireType } out, st := fmi.validate(b, f.num, opts) return out, st default: return out, ValidationUnknown } } // unmarshalPointerLazy is similar to unmarshalPointerEager, but it // specifically handles lazy unmarshalling. it expects lazyOffset and // presenceOffset to both be valid. func (mi *MessageInfo) unmarshalPointerLazy(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { initialized := true var requiredMask uint64 var lazy **protolazy.XXX_lazyUnmarshalInfo var presence presence var lazyIndex []protolazy.IndexEntry var lastNum protowire.Number outOfOrder := false lazyDecode := false presence = p.Apply(mi.presenceOffset).PresenceInfo() lazy = p.Apply(mi.lazyOffset).LazyInfoPtr() if !presence.AnyPresent(mi.presenceSize) { if opts.CanBeLazy() { // If the message contains existing data, we need to merge into it. // Lazy unmarshaling doesn't merge, so only enable it when the // message is empty (has no presence bitmap). lazyDecode = true if *lazy == nil { *lazy = &protolazy.XXX_lazyUnmarshalInfo{} } (*lazy).SetUnmarshalFlags(opts.flags) if !opts.AliasBuffer() { // Make a copy of the buffer for lazy unmarshaling. // Set the AliasBuffer flag so recursive unmarshal // operations reuse the copy. b = append([]byte{}, b...) opts.flags |= piface.UnmarshalAliasBuffer } (*lazy).SetBuffer(b) } } // Track special handling of lazy fields. // // In the common case, all fields are lazyValidateOnly (and lazyFields remains nil). // In the event that validation for a field fails, this map tracks handling of the field. type lazyAction uint8 const ( lazyValidateOnly lazyAction = iota // validate the field only lazyUnmarshalNow // eagerly unmarshal the field lazyUnmarshalLater // unmarshal the field after the message is fully processed ) var lazyFields map[*coderFieldInfo]lazyAction var exts *map[int32]ExtensionField start := len(b) pos := 0 for len(b) > 0 { // Parse the tag (field number and wire type). var tag uint64 if b[0] < 0x80 { tag = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int tag, n = protowire.ConsumeVarint(b) if n < 0 { return out, errDecode } b = b[n:] } var num protowire.Number if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { return out, errors.New("invalid field number") } else { num = protowire.Number(n) } wtyp := protowire.Type(tag & 7) if wtyp == protowire.EndGroupType { if num != groupTag { return out, errors.New("mismatching end group marker") } groupTag = 0 break } var f *coderFieldInfo if int(num) < len(mi.denseCoderFields) { f = mi.denseCoderFields[num] } else { f = mi.coderFields[num] } var n int err := errUnknown discardUnknown := false Field: switch { case f != nil: if f.funcs.unmarshal == nil { break } if f.isLazy && lazyDecode { switch { case lazyFields == nil || lazyFields[f] == lazyValidateOnly: // Attempt to validate this field and leave it for later lazy unmarshaling. o, valid := mi.skipField(b, f, wtyp, opts) switch valid { case ValidationValid: // Skip over the valid field and continue. err = nil presence.SetPresentUnatomic(f.presenceIndex, mi.presenceSize) requiredMask |= f.validation.requiredBit if !o.initialized { initialized = false } n = o.n break Field case ValidationInvalid: return out, errors.New("invalid proto wire format") case ValidationWrongWireType: break Field case ValidationUnknown: if lazyFields == nil { lazyFields = make(map[*coderFieldInfo]lazyAction) } if presence.Present(f.presenceIndex) { // We were unable to determine if the field is valid or not, // and we've already skipped over at least one instance of this // field. Clear the presence bit (so if we stop decoding early, // we don't leave a partially-initialized field around) and flag // the field for unmarshaling before we return. presence.ClearPresent(f.presenceIndex) lazyFields[f] = lazyUnmarshalLater discardUnknown = true break Field } else { // We were unable to determine if the field is valid or not, // but this is the first time we've seen it. Flag it as needing // eager unmarshaling and fall through to the eager unmarshal case below. lazyFields[f] = lazyUnmarshalNow } } case lazyFields[f] == lazyUnmarshalLater: // This field will be unmarshaled in a separate pass below. // Skip over it here. discardUnknown = true break Field default: // Eagerly unmarshal the field. } } if f.isLazy && !lazyDecode && presence.Present(f.presenceIndex) { if p.Apply(f.offset).AtomicGetPointer().IsNil() { mi.lazyUnmarshal(p, f.num) } } var o unmarshalOutput o, err = f.funcs.unmarshal(b, p.Apply(f.offset), wtyp, f, opts) n = o.n if err != nil { break } requiredMask |= f.validation.requiredBit if f.funcs.isInit != nil && !o.initialized { initialized = false } if f.presenceIndex != noPresence { presence.SetPresentUnatomic(f.presenceIndex, mi.presenceSize) } default: // Possible extension. if exts == nil && mi.extensionOffset.IsValid() { exts = p.Apply(mi.extensionOffset).Extensions() if *exts == nil { *exts = make(map[int32]ExtensionField) } } if exts == nil { break } var o unmarshalOutput o, err = mi.unmarshalExtension(b, num, wtyp, *exts, opts) if err != nil { break } n = o.n if !o.initialized { initialized = false } } if err != nil { if err != errUnknown { return out, err } n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return out, errDecode } if !discardUnknown && !opts.DiscardUnknown() && mi.unknownOffset.IsValid() { u := mi.mutableUnknownBytes(p) *u = protowire.AppendTag(*u, num, wtyp) *u = append(*u, b[:n]...) } } b = b[n:] end := start - len(b) if lazyDecode && f != nil && f.isLazy { if num != lastNum { lazyIndex = append(lazyIndex, protolazy.IndexEntry{ FieldNum: uint32(num), Start: uint32(pos), End: uint32(end), }) } else { i := len(lazyIndex) - 1 lazyIndex[i].End = uint32(end) lazyIndex[i].MultipleContiguous = true } } if num < lastNum { outOfOrder = true } pos = end lastNum = num } if groupTag != 0 { return out, errors.New("missing end group marker") } if lazyFields != nil { // Some fields failed validation, and now need to be unmarshaled. for f, action := range lazyFields { if action != lazyUnmarshalLater { continue } initialized = false if *lazy == nil { *lazy = &protolazy.XXX_lazyUnmarshalInfo{} } if err := mi.unmarshalField((*lazy).Buffer(), p.Apply(f.offset), f, *lazy, opts.flags); err != nil { return out, err } presence.SetPresentUnatomic(f.presenceIndex, mi.presenceSize) } } if lazyDecode { if outOfOrder { sort.Slice(lazyIndex, func(i, j int) bool { return lazyIndex[i].FieldNum < lazyIndex[j].FieldNum || (lazyIndex[i].FieldNum == lazyIndex[j].FieldNum && lazyIndex[i].Start < lazyIndex[j].Start) }) } if *lazy == nil { *lazy = &protolazy.XXX_lazyUnmarshalInfo{} } (*lazy).SetIndex(lazyIndex) } if mi.numRequiredFields > 0 && bits.OnesCount64(requiredMask) != int(mi.numRequiredFields) { initialized = false } if initialized { out.initialized = true } out.n = start - len(b) return out, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/checkinit.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/checkinit.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "sync" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) func (mi *MessageInfo) checkInitialized(in protoiface.CheckInitializedInput) (protoiface.CheckInitializedOutput, error) { var p pointer if ms, ok := in.Message.(*messageState); ok { p = ms.pointer() } else { p = in.Message.(*messageReflectWrapper).pointer() } return protoiface.CheckInitializedOutput{}, mi.checkInitializedPointer(p) } func (mi *MessageInfo) checkInitializedPointer(p pointer) error { mi.init() if !mi.needsInitCheck { return nil } if p.IsNil() { for _, f := range mi.orderedCoderFields { if f.isRequired { return errors.RequiredNotSet(string(mi.Desc.Fields().ByNumber(f.num).FullName())) } } return nil } var presence presence if mi.presenceOffset.IsValid() { presence = p.Apply(mi.presenceOffset).PresenceInfo() } if mi.extensionOffset.IsValid() { e := p.Apply(mi.extensionOffset).Extensions() if err := mi.isInitExtensions(e); err != nil { return err } } for _, f := range mi.orderedCoderFields { if !f.isRequired && f.funcs.isInit == nil { continue } if f.presenceIndex != noPresence { if !presence.Present(f.presenceIndex) { if f.isRequired { return errors.RequiredNotSet(string(mi.Desc.Fields().ByNumber(f.num).FullName())) } continue } if f.funcs.isInit != nil { f.mi.init() if f.mi.needsInitCheck { if f.isLazy && p.Apply(f.offset).AtomicGetPointer().IsNil() { lazy := *p.Apply(mi.lazyOffset).LazyInfoPtr() if !lazy.AllowedPartial() { // Nothing to see here, it was checked on unmarshal continue } mi.lazyUnmarshal(p, f.num) } if err := f.funcs.isInit(p.Apply(f.offset), f); err != nil { return err } } } continue } fptr := p.Apply(f.offset) if f.isPointer && fptr.Elem().IsNil() { if f.isRequired { return errors.RequiredNotSet(string(mi.Desc.Fields().ByNumber(f.num).FullName())) } continue } if f.funcs.isInit == nil { continue } if err := f.funcs.isInit(fptr, f); err != nil { return err } } return nil } func (mi *MessageInfo) isInitExtensions(ext *map[int32]ExtensionField) error { if ext == nil { return nil } for _, x := range *ext { ei := getExtensionFieldInfo(x.Type()) if ei.funcs.isInit == nil || x.isUnexpandedLazy() { continue } v := x.Value() if !v.IsValid() { continue } if err := ei.funcs.isInit(v); err != nil { return err } } return nil } var ( needsInitCheckMu sync.Mutex needsInitCheckMap sync.Map ) // needsInitCheck reports whether a message needs to be checked for partial initialization. // // It returns true if the message transitively includes any required or extension fields. func needsInitCheck(md protoreflect.MessageDescriptor) bool { if v, ok := needsInitCheckMap.Load(md); ok { if has, ok := v.(bool); ok { return has } } needsInitCheckMu.Lock() defer needsInitCheckMu.Unlock() return needsInitCheckLocked(md) } func needsInitCheckLocked(md protoreflect.MessageDescriptor) (has bool) { if v, ok := needsInitCheckMap.Load(md); ok { // If has is true, we've previously determined that this message // needs init checks. // // If has is false, we've previously determined that it can never // be uninitialized. // // If has is not a bool, we've just encountered a cycle in the // message graph. In this case, it is safe to return false: If // the message does have required fields, we'll detect them later // in the graph traversal. has, ok := v.(bool) return ok && has } needsInitCheckMap.Store(md, struct{}{}) // avoid cycles while descending into this message defer func() { needsInitCheckMap.Store(md, has) }() if md.RequiredNumbers().Len() > 0 { return true } if md.ExtensionRanges().Len() > 0 { return true } for i := 0; i < md.Fields().Len(); i++ { fd := md.Fields().Get(i) // Map keys are never messages, so just consider the map value. if fd.IsMap() { fd = fd.MapValue() } fmd := fd.Message() if fmd != nil && needsInitCheckLocked(fmd) { return true } } return false }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "math" "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) type fieldInfo struct { fieldDesc protoreflect.FieldDescriptor // These fields are used for protobuf reflection support. has func(pointer) bool clear func(pointer) get func(pointer) protoreflect.Value set func(pointer, protoreflect.Value) mutable func(pointer) protoreflect.Value newMessage func() protoreflect.Message newField func() protoreflect.Value } func fieldInfoForMissing(fd protoreflect.FieldDescriptor) fieldInfo { // This never occurs for generated message types. // It implies that a hand-crafted type has missing Go fields // for specific protobuf message fields. return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { return false }, clear: func(p pointer) { panic("missing Go struct field for " + string(fd.FullName())) }, get: func(p pointer) protoreflect.Value { return fd.Default() }, set: func(p pointer, v protoreflect.Value) { panic("missing Go struct field for " + string(fd.FullName())) }, mutable: func(p pointer) protoreflect.Value { panic("missing Go struct field for " + string(fd.FullName())) }, newMessage: func() protoreflect.Message { panic("missing Go struct field for " + string(fd.FullName())) }, newField: func() protoreflect.Value { if v := fd.Default(); v.IsValid() { return v } panic("missing Go struct field for " + string(fd.FullName())) }, } } func fieldInfoForOneof(fd protoreflect.FieldDescriptor, fs reflect.StructField, x exporter, ot reflect.Type) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Interface { panic(fmt.Sprintf("field %v has invalid type: got %v, want interface kind", fd.FullName(), ft)) } if ot.Kind() != reflect.Struct { panic(fmt.Sprintf("field %v has invalid type: got %v, want struct kind", fd.FullName(), ot)) } if !reflect.PtrTo(ot).Implements(ft) { panic(fmt.Sprintf("field %v has invalid type: %v does not implement %v", fd.FullName(), ot, ft)) } conv := NewConverter(ot.Field(0).Type, fd) isMessage := fd.Message() != nil // TODO: Implement unsafe fast path? fieldOffset := offsetOf(fs) return fieldInfo{ // NOTE: The logic below intentionally assumes that oneof fields are // well-formatted. That is, the oneof interface never contains a // typed nil pointer to one of the wrapper structs. fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { return false } return true }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() || rv.Elem().Type().Elem() != ot { // NOTE: We intentionally don't check for rv.Elem().IsNil() // so that (*OneofWrapperType)(nil) gets cleared to nil. return } rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { return conv.Zero() } rv = rv.Elem().Elem().Field(0) return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { rv.Set(reflect.New(ot)) } rv = rv.Elem().Elem().Field(0) rv.Set(conv.GoValueOf(v)) }, mutable: func(p pointer) protoreflect.Value { if !isMessage { panic(fmt.Sprintf("field %v with invalid Mutable call on field with non-composite type", fd.FullName())) } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() || rv.Elem().Type().Elem() != ot || rv.Elem().IsNil() { rv.Set(reflect.New(ot)) } rv = rv.Elem().Elem().Field(0) if rv.Kind() == reflect.Ptr && rv.IsNil() { rv.Set(conv.GoValueOf(protoreflect.ValueOfMessage(conv.New().Message()))) } return conv.PBValueOf(rv) }, newMessage: func() protoreflect.Message { return conv.New().Message() }, newField: func() protoreflect.Value { return conv.New() }, } } func fieldInfoForMap(fd protoreflect.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Map { panic(fmt.Sprintf("field %v has invalid type: got %v, want map kind", fd.FullName(), ft)) } conv := NewConverter(ft, fd) // TODO: Implement unsafe fast path? fieldOffset := offsetOf(fs) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return rv.Len() > 0 }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() pv := conv.GoValueOf(v) if pv.IsNil() { panic(fmt.Sprintf("map field %v cannot be set with read-only value", fd.FullName())) } rv.Set(pv) }, mutable: func(p pointer) protoreflect.Value { v := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if v.IsNil() { v.Set(reflect.MakeMap(fs.Type)) } return conv.PBValueOf(v) }, newField: func() protoreflect.Value { return conv.New() }, } } func fieldInfoForList(fd protoreflect.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Slice { panic(fmt.Sprintf("field %v has invalid type: got %v, want slice kind", fd.FullName(), ft)) } conv := NewConverter(reflect.PtrTo(ft), fd) // TODO: Implement unsafe fast path? fieldOffset := offsetOf(fs) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return rv.Len() > 0 }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type) if rv.Elem().Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() pv := conv.GoValueOf(v) if pv.IsNil() { panic(fmt.Sprintf("list field %v cannot be set with read-only value", fd.FullName())) } rv.Set(pv.Elem()) }, mutable: func(p pointer) protoreflect.Value { v := p.Apply(fieldOffset).AsValueOf(fs.Type) return conv.PBValueOf(v) }, newField: func() protoreflect.Value { return conv.New() }, } } var ( nilBytes = reflect.ValueOf([]byte(nil)) emptyBytes = reflect.ValueOf([]byte{}) ) func fieldInfoForScalar(fd protoreflect.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { ft := fs.Type nullable := fd.HasPresence() isBytes := ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 var getter func(p pointer) protoreflect.Value if nullable { if ft.Kind() != reflect.Ptr && ft.Kind() != reflect.Slice { // This never occurs for generated message types. // Despite the protobuf type system specifying presence, // the Go field type cannot represent it. nullable = false } if ft.Kind() == reflect.Ptr { ft = ft.Elem() } } conv := NewConverter(ft, fd) fieldOffset := offsetOf(fs) // Generate specialized getter functions to avoid going through reflect.Value if nullable { getter = getterForNullableScalar(fd, fs, conv, fieldOffset) } else { getter = getterForDirectScalar(fd, fs, conv, fieldOffset) } return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } if nullable { return !p.Apply(fieldOffset).Elem().IsNil() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() switch rv.Kind() { case reflect.Bool: return rv.Bool() case reflect.Int32, reflect.Int64: return rv.Int() != 0 case reflect.Uint32, reflect.Uint64: return rv.Uint() != 0 case reflect.Float32, reflect.Float64: return rv.Float() != 0 || math.Signbit(rv.Float()) case reflect.String, reflect.Slice: return rv.Len() > 0 default: panic(fmt.Sprintf("field %v has invalid type: %v", fd.FullName(), rv.Type())) // should never happen } }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: getter, // TODO: Implement unsafe fast path for set? set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if nullable && rv.Kind() == reflect.Ptr { if rv.IsNil() { rv.Set(reflect.New(ft)) } rv = rv.Elem() } rv.Set(conv.GoValueOf(v)) if isBytes && rv.Len() == 0 { if nullable { rv.Set(emptyBytes) // preserve presence } else { rv.Set(nilBytes) // do not preserve presence } } }, newField: func() protoreflect.Value { return conv.New() }, } } func fieldInfoForMessage(fd protoreflect.FieldDescriptor, fs reflect.StructField, x exporter) fieldInfo { ft := fs.Type conv := NewConverter(ft, fd) // TODO: Implement unsafe fast path? fieldOffset := offsetOf(fs) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if fs.Type.Kind() != reflect.Ptr { return !rv.IsZero() } return !rv.IsNil() }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(conv.GoValueOf(v)) if fs.Type.Kind() == reflect.Ptr && rv.IsNil() { panic(fmt.Sprintf("field %v has invalid nil pointer", fd.FullName())) } }, mutable: func(p pointer) protoreflect.Value { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if fs.Type.Kind() == reflect.Ptr && rv.IsNil() { rv.Set(conv.GoValueOf(conv.New())) } return conv.PBValueOf(rv) }, newMessage: func() protoreflect.Message { return conv.New().Message() }, newField: func() protoreflect.Value { return conv.New() }, } } type oneofInfo struct { oneofDesc protoreflect.OneofDescriptor which func(pointer) protoreflect.FieldNumber } func makeOneofInfo(od protoreflect.OneofDescriptor, si structInfo, x exporter) *oneofInfo { oi := &oneofInfo{oneofDesc: od} if od.IsSynthetic() { fs := si.fieldsByNumber[od.Fields().Get(0).Number()] fieldOffset := offsetOf(fs) oi.which = func(p pointer) protoreflect.FieldNumber { if p.IsNil() { return 0 } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { // valid on either *T or []byte return 0 } return od.Fields().Get(0).Number() } } else { fs := si.oneofsByName[od.Name()] fieldOffset := offsetOf(fs) oi.which = func(p pointer) protoreflect.FieldNumber { if p.IsNil() { return 0 } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { return 0 } rv = rv.Elem() if rv.IsNil() { return 0 } return si.oneofWrappersByType[rv.Type().Elem()] } } return oi }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_field_gen.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package impl import ( "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) func getterForNullableScalar(fd protoreflect.FieldDescriptor, fs reflect.StructField, conv Converter, fieldOffset offset) func(p pointer) protoreflect.Value { ft := fs.Type if ft.Kind() == reflect.Ptr { ft = ft.Elem() } if fd.Kind() == protoreflect.EnumKind { elemType := fs.Type.Elem() // Enums for nullable types. return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).Elem().AsValueOf(elemType) if rv.IsNil() { return conv.Zero() } return conv.PBValueOf(rv.Elem()) } } switch ft.Kind() { case reflect.Bool: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).BoolPtr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfBool(**x) } case reflect.Int32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Int32Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfInt32(**x) } case reflect.Uint32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Uint32Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfUint32(**x) } case reflect.Int64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Int64Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfInt64(**x) } case reflect.Uint64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Uint64Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfUint64(**x) } case reflect.Float32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Float32Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfFloat32(**x) } case reflect.Float64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Float64Ptr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfFloat64(**x) } case reflect.String: if fd.Kind() == protoreflect.BytesKind { return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).StringPtr() if *x == nil { return conv.Zero() } if len(**x) == 0 { return protoreflect.ValueOfBytes(nil) } return protoreflect.ValueOfBytes([]byte(**x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).StringPtr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfString(**x) } case reflect.Slice: if fd.Kind() == protoreflect.StringKind { return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() if len(*x) == 0 { return conv.Zero() } return protoreflect.ValueOfString(string(*x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() if *x == nil { return conv.Zero() } return protoreflect.ValueOfBytes(*x) } } panic("unexpected protobuf kind: " + ft.Kind().String()) } func getterForDirectScalar(fd protoreflect.FieldDescriptor, fs reflect.StructField, conv Converter, fieldOffset offset) func(p pointer) protoreflect.Value { ft := fs.Type if fd.Kind() == protoreflect.EnumKind { // Enums for non nullable types. return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return conv.PBValueOf(rv) } } switch ft.Kind() { case reflect.Bool: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Bool() return protoreflect.ValueOfBool(*x) } case reflect.Int32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Int32() return protoreflect.ValueOfInt32(*x) } case reflect.Uint32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Uint32() return protoreflect.ValueOfUint32(*x) } case reflect.Int64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Int64() return protoreflect.ValueOfInt64(*x) } case reflect.Uint64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Uint64() return protoreflect.ValueOfUint64(*x) } case reflect.Float32: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Float32() return protoreflect.ValueOfFloat32(*x) } case reflect.Float64: return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Float64() return protoreflect.ValueOfFloat64(*x) } case reflect.String: if fd.Kind() == protoreflect.BytesKind { return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).String() if len(*x) == 0 { return protoreflect.ValueOfBytes(nil) } return protoreflect.ValueOfBytes([]byte(*x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).String() return protoreflect.ValueOfString(*x) } case reflect.Slice: if fd.Kind() == protoreflect.StringKind { return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() return protoreflect.ValueOfString(string(*x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() return protoreflect.ValueOfBytes(*x) } } panic("unexpected protobuf kind: " + ft.Kind().String()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert_list.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert_list.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) func newListConverter(t reflect.Type, fd protoreflect.FieldDescriptor) Converter { switch { case t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Slice: return &listPtrConverter{t, newSingularConverter(t.Elem().Elem(), fd)} case t.Kind() == reflect.Slice: return &listConverter{t, newSingularConverter(t.Elem(), fd)} } panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) } type listConverter struct { goType reflect.Type // []T c Converter } func (c *listConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } pv := reflect.New(c.goType) pv.Elem().Set(v) return protoreflect.ValueOfList(&listReflect{pv, c.c}) } func (c *listConverter) GoValueOf(v protoreflect.Value) reflect.Value { rv := v.List().(*listReflect).v if rv.IsNil() { return reflect.Zero(c.goType) } return rv.Elem() } func (c *listConverter) IsValidPB(v protoreflect.Value) bool { list, ok := v.Interface().(*listReflect) if !ok { return false } return list.v.Type().Elem() == c.goType } func (c *listConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *listConverter) New() protoreflect.Value { return protoreflect.ValueOfList(&listReflect{reflect.New(c.goType), c.c}) } func (c *listConverter) Zero() protoreflect.Value { return protoreflect.ValueOfList(&listReflect{reflect.Zero(reflect.PtrTo(c.goType)), c.c}) } type listPtrConverter struct { goType reflect.Type // *[]T c Converter } func (c *listPtrConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfList(&listReflect{v, c.c}) } func (c *listPtrConverter) GoValueOf(v protoreflect.Value) reflect.Value { return v.List().(*listReflect).v } func (c *listPtrConverter) IsValidPB(v protoreflect.Value) bool { list, ok := v.Interface().(*listReflect) if !ok { return false } return list.v.Type() == c.goType } func (c *listPtrConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *listPtrConverter) New() protoreflect.Value { return c.PBValueOf(reflect.New(c.goType.Elem())) } func (c *listPtrConverter) Zero() protoreflect.Value { return c.PBValueOf(reflect.Zero(c.goType)) } type listReflect struct { v reflect.Value // *[]T conv Converter } func (ls *listReflect) Len() int { if ls.v.IsNil() { return 0 } return ls.v.Elem().Len() } func (ls *listReflect) Get(i int) protoreflect.Value { return ls.conv.PBValueOf(ls.v.Elem().Index(i)) } func (ls *listReflect) Set(i int, v protoreflect.Value) { ls.v.Elem().Index(i).Set(ls.conv.GoValueOf(v)) } func (ls *listReflect) Append(v protoreflect.Value) { ls.v.Elem().Set(reflect.Append(ls.v.Elem(), ls.conv.GoValueOf(v))) } func (ls *listReflect) AppendMutable() protoreflect.Value { if _, ok := ls.conv.(*messageConverter); !ok { panic("invalid AppendMutable on list with non-message type") } v := ls.NewElement() ls.Append(v) return v } func (ls *listReflect) Truncate(i int) { ls.v.Elem().Set(ls.v.Elem().Slice(0, i)) } func (ls *listReflect) NewElement() protoreflect.Value { return ls.conv.New() } func (ls *listReflect) IsValid() bool { return !ls.v.IsNil() } func (ls *listReflect) protoUnwrap() any { return ls.v.Interface() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_opaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_opaque.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "math" "reflect" "strings" "sync/atomic" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/reflect/protoreflect" ) type opaqueStructInfo struct { structInfo } // isOpaque determines whether a protobuf message type is on the Opaque API. It // checks whether the type is a Go struct that protoc-gen-go would generate. // // This function only detects newly generated messages from the v2 // implementation of protoc-gen-go. It is unable to classify generated messages // that are too old or those that are generated by a different generator // such as protoc-gen-gogo. func isOpaque(t reflect.Type) bool { // The current detection mechanism is to simply check the first field // for a struct tag with the "protogen" key. if t.Kind() == reflect.Struct && t.NumField() > 0 { pgt := t.Field(0).Tag.Get("protogen") return strings.HasPrefix(pgt, "opaque.") } return false } func opaqueInitHook(mi *MessageInfo) bool { mt := mi.GoReflectType.Elem() si := opaqueStructInfo{ structInfo: mi.makeStructInfo(mt), } if !isOpaque(mt) { return false } defer atomic.StoreUint32(&mi.initDone, 1) mi.fields = map[protoreflect.FieldNumber]*fieldInfo{} fds := mi.Desc.Fields() for i := 0; i < fds.Len(); i++ { fd := fds.Get(i) fs := si.fieldsByNumber[fd.Number()] var fi fieldInfo usePresence, _ := filedesc.UsePresenceForField(fd) switch { case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): // Oneofs are no different for opaque. fi = fieldInfoForOneof(fd, si.oneofsByName[fd.ContainingOneof().Name()], mi.Exporter, si.oneofWrappersByNumber[fd.Number()]) case fd.IsMap(): fi = mi.fieldInfoForMapOpaque(si, fd, fs) case fd.IsList() && fd.Message() == nil && usePresence: fi = mi.fieldInfoForScalarListOpaque(si, fd, fs) case fd.IsList() && fd.Message() == nil: // Proto3 lists without presence can use same access methods as open fi = fieldInfoForList(fd, fs, mi.Exporter) case fd.IsList() && usePresence: fi = mi.fieldInfoForMessageListOpaque(si, fd, fs) case fd.IsList(): // Proto3 opaque messages that does not need presence bitmap. // Different representation than open struct, but same logic fi = mi.fieldInfoForMessageListOpaqueNoPresence(si, fd, fs) case fd.Message() != nil && usePresence: fi = mi.fieldInfoForMessageOpaque(si, fd, fs) case fd.Message() != nil: // Proto3 messages without presence can use same access methods as open fi = fieldInfoForMessage(fd, fs, mi.Exporter) default: fi = mi.fieldInfoForScalarOpaque(si, fd, fs) } mi.fields[fd.Number()] = &fi } mi.oneofs = map[protoreflect.Name]*oneofInfo{} for i := 0; i < mi.Desc.Oneofs().Len(); i++ { od := mi.Desc.Oneofs().Get(i) mi.oneofs[od.Name()] = makeOneofInfoOpaque(mi, od, si.structInfo, mi.Exporter) } mi.denseFields = make([]*fieldInfo, fds.Len()*2) for i := 0; i < fds.Len(); i++ { if fd := fds.Get(i); int(fd.Number()) < len(mi.denseFields) { mi.denseFields[fd.Number()] = mi.fields[fd.Number()] } } for i := 0; i < fds.Len(); { fd := fds.Get(i) if od := fd.ContainingOneof(); od != nil && !fd.ContainingOneof().IsSynthetic() { mi.rangeInfos = append(mi.rangeInfos, mi.oneofs[od.Name()]) i += od.Fields().Len() } else { mi.rangeInfos = append(mi.rangeInfos, mi.fields[fd.Number()]) i++ } } mi.makeExtensionFieldsFunc(mt, si.structInfo) mi.makeUnknownFieldsFunc(mt, si.structInfo) mi.makeOpaqueCoderMethods(mt, si) mi.makeFieldTypes(si.structInfo) return true } func makeOneofInfoOpaque(mi *MessageInfo, od protoreflect.OneofDescriptor, si structInfo, x exporter) *oneofInfo { oi := &oneofInfo{oneofDesc: od} if od.IsSynthetic() { fd := od.Fields().Get(0) index, _ := presenceIndex(mi.Desc, fd) oi.which = func(p pointer) protoreflect.FieldNumber { if p.IsNil() { return 0 } if !mi.present(p, index) { return 0 } return od.Fields().Get(0).Number() } return oi } // Dispatch to non-opaque oneof implementation for non-synthetic oneofs. return makeOneofInfo(od, si, x) } func (mi *MessageInfo) fieldInfoForMapOpaque(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Map { panic(fmt.Sprintf("invalid type: got %v, want map kind", ft)) } fieldOffset := offsetOf(fs) conv := NewConverter(ft, fd) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } // Don't bother checking presence bits, since we need to // look at the map length even if the presence bit is set. rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return rv.Len() > 0 }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { pv := conv.GoValueOf(v) if pv.IsNil() { panic(fmt.Sprintf("invalid value: setting map field to read-only value")) } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(pv) }, mutable: func(p pointer) protoreflect.Value { v := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if v.IsNil() { v.Set(reflect.MakeMap(fs.Type)) } return conv.PBValueOf(v) }, newField: func() protoreflect.Value { return conv.New() }, } } func (mi *MessageInfo) fieldInfoForScalarListOpaque(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Slice { panic(fmt.Sprintf("invalid type: got %v, want slice kind", ft)) } conv := NewConverter(reflect.PtrTo(ft), fd) fieldOffset := offsetOf(fs) index, _ := presenceIndex(mi.Desc, fd) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return rv.Len() > 0 }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type) if rv.Elem().Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { pv := conv.GoValueOf(v) if pv.IsNil() { panic(fmt.Sprintf("invalid value: setting repeated field to read-only value")) } mi.setPresent(p, index) rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(pv.Elem()) }, mutable: func(p pointer) protoreflect.Value { mi.setPresent(p, index) return conv.PBValueOf(p.Apply(fieldOffset).AsValueOf(fs.Type)) }, newField: func() protoreflect.Value { return conv.New() }, } } func (mi *MessageInfo) fieldInfoForMessageListOpaque(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Ptr || ft.Elem().Kind() != reflect.Slice { panic(fmt.Sprintf("invalid type: got %v, want slice kind", ft)) } conv := NewConverter(ft, fd) fieldOffset := offsetOf(fs) index, _ := presenceIndex(mi.Desc, fd) fieldNumber := fd.Number() return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } if !mi.present(p, index) { return false } sp := p.Apply(fieldOffset).AtomicGetPointer() if sp.IsNil() { // Lazily unmarshal this field. mi.lazyUnmarshal(p, fieldNumber) sp = p.Apply(fieldOffset).AtomicGetPointer() } rv := sp.AsValueOf(fs.Type.Elem()) return rv.Elem().Len() > 0 }, clear: func(p pointer) { fp := p.Apply(fieldOffset) sp := fp.AtomicGetPointer() if sp.IsNil() { sp = fp.AtomicSetPointerIfNil(pointerOfValue(reflect.New(fs.Type.Elem()))) mi.setPresent(p, index) } rv := sp.AsValueOf(fs.Type.Elem()) rv.Elem().Set(reflect.Zero(rv.Type().Elem())) }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } if !mi.present(p, index) { return conv.Zero() } sp := p.Apply(fieldOffset).AtomicGetPointer() if sp.IsNil() { // Lazily unmarshal this field. mi.lazyUnmarshal(p, fieldNumber) sp = p.Apply(fieldOffset).AtomicGetPointer() } rv := sp.AsValueOf(fs.Type.Elem()) if rv.Elem().Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { fp := p.Apply(fieldOffset) sp := fp.AtomicGetPointer() if sp.IsNil() { sp = fp.AtomicSetPointerIfNil(pointerOfValue(reflect.New(fs.Type.Elem()))) mi.setPresent(p, index) } rv := sp.AsValueOf(fs.Type.Elem()) val := conv.GoValueOf(v) if val.IsNil() { panic(fmt.Sprintf("invalid value: setting repeated field to read-only value")) } else { rv.Elem().Set(val.Elem()) } }, mutable: func(p pointer) protoreflect.Value { fp := p.Apply(fieldOffset) sp := fp.AtomicGetPointer() if sp.IsNil() { if mi.present(p, index) { // Lazily unmarshal this field. mi.lazyUnmarshal(p, fieldNumber) sp = p.Apply(fieldOffset).AtomicGetPointer() } else { sp = fp.AtomicSetPointerIfNil(pointerOfValue(reflect.New(fs.Type.Elem()))) mi.setPresent(p, index) } } rv := sp.AsValueOf(fs.Type.Elem()) return conv.PBValueOf(rv) }, newField: func() protoreflect.Value { return conv.New() }, } } func (mi *MessageInfo) fieldInfoForMessageListOpaqueNoPresence(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type if ft.Kind() != reflect.Ptr || ft.Elem().Kind() != reflect.Slice { panic(fmt.Sprintf("invalid type: got %v, want slice kind", ft)) } conv := NewConverter(ft, fd) fieldOffset := offsetOf(fs) return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { return false } return rv.Elem().Len() > 0 }, clear: func(p pointer) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if !rv.IsNil() { rv.Elem().Set(reflect.Zero(rv.Type().Elem())) } }, get: func(p pointer) protoreflect.Value { if p.IsNil() { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { return conv.Zero() } if rv.Elem().Len() == 0 { return conv.Zero() } return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { rv.Set(reflect.New(fs.Type.Elem())) } val := conv.GoValueOf(v) if val.IsNil() { panic(fmt.Sprintf("invalid value: setting repeated field to read-only value")) } else { rv.Elem().Set(val.Elem()) } }, mutable: func(p pointer) protoreflect.Value { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if rv.IsNil() { rv.Set(reflect.New(fs.Type.Elem())) } return conv.PBValueOf(rv) }, newField: func() protoreflect.Value { return conv.New() }, } } func (mi *MessageInfo) fieldInfoForScalarOpaque(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type nullable := fd.HasPresence() if oneof := fd.ContainingOneof(); oneof != nil && oneof.IsSynthetic() { nullable = true } deref := false if nullable && ft.Kind() == reflect.Ptr { ft = ft.Elem() deref = true } conv := NewConverter(ft, fd) fieldOffset := offsetOf(fs) index, _ := presenceIndex(mi.Desc, fd) var getter func(p pointer) protoreflect.Value if !nullable { getter = getterForDirectScalar(fd, fs, conv, fieldOffset) } else { getter = getterForOpaqueNullableScalar(mi, index, fd, fs, conv, fieldOffset) } return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } if nullable { return mi.present(p, index) } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() switch rv.Kind() { case reflect.Bool: return rv.Bool() case reflect.Int32, reflect.Int64: return rv.Int() != 0 case reflect.Uint32, reflect.Uint64: return rv.Uint() != 0 case reflect.Float32, reflect.Float64: return rv.Float() != 0 || math.Signbit(rv.Float()) case reflect.String, reflect.Slice: return rv.Len() > 0 default: panic(fmt.Sprintf("invalid type: %v", rv.Type())) // should never happen } }, clear: func(p pointer) { if nullable { mi.clearPresent(p, index) } // This is only valuable for bytes and strings, but we do it unconditionally. rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() rv.Set(reflect.Zero(rv.Type())) }, get: getter, // TODO: Implement unsafe fast path for set? set: func(p pointer, v protoreflect.Value) { rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() if deref { if rv.IsNil() { rv.Set(reflect.New(ft)) } rv = rv.Elem() } rv.Set(conv.GoValueOf(v)) if nullable && rv.Kind() == reflect.Slice && rv.IsNil() { rv.Set(emptyBytes) } if nullable { mi.setPresent(p, index) } }, newField: func() protoreflect.Value { return conv.New() }, } } func (mi *MessageInfo) fieldInfoForMessageOpaque(si opaqueStructInfo, fd protoreflect.FieldDescriptor, fs reflect.StructField) fieldInfo { ft := fs.Type conv := NewConverter(ft, fd) fieldOffset := offsetOf(fs) index, _ := presenceIndex(mi.Desc, fd) fieldNumber := fd.Number() elemType := fs.Type.Elem() return fieldInfo{ fieldDesc: fd, has: func(p pointer) bool { if p.IsNil() { return false } return mi.present(p, index) }, clear: func(p pointer) { mi.clearPresent(p, index) p.Apply(fieldOffset).AtomicSetNilPointer() }, get: func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } fp := p.Apply(fieldOffset) mp := fp.AtomicGetPointer() if mp.IsNil() { // Lazily unmarshal this field. mi.lazyUnmarshal(p, fieldNumber) mp = fp.AtomicGetPointer() } rv := mp.AsValueOf(elemType) return conv.PBValueOf(rv) }, set: func(p pointer, v protoreflect.Value) { val := pointerOfValue(conv.GoValueOf(v)) if val.IsNil() { panic("invalid nil pointer") } p.Apply(fieldOffset).AtomicSetPointer(val) mi.setPresent(p, index) }, mutable: func(p pointer) protoreflect.Value { fp := p.Apply(fieldOffset) mp := fp.AtomicGetPointer() if mp.IsNil() { if mi.present(p, index) { // Lazily unmarshal this field. mi.lazyUnmarshal(p, fieldNumber) mp = fp.AtomicGetPointer() } else { mp = pointerOfValue(conv.GoValueOf(conv.New())) fp.AtomicSetPointer(mp) mi.setPresent(p, index) } } return conv.PBValueOf(mp.AsValueOf(fs.Type.Elem())) }, newMessage: func() protoreflect.Message { return conv.New().Message() }, newField: func() protoreflect.Value { return conv.New() }, } } // A presenceList wraps a List, updating presence bits as necessary when the // list contents change. type presenceList struct { pvalueList setPresence func(bool) } type pvalueList interface { protoreflect.List //Unwrapper } func (list presenceList) Append(v protoreflect.Value) { list.pvalueList.Append(v) list.setPresence(true) } func (list presenceList) Truncate(i int) { list.pvalueList.Truncate(i) list.setPresence(i > 0) } // presenceIndex returns the index to pass to presence functions. // // TODO: field.Desc.Index() would be simpler, and would give space to record the presence of oneof fields. func presenceIndex(md protoreflect.MessageDescriptor, fd protoreflect.FieldDescriptor) (uint32, presenceSize) { found := false var index, numIndices uint32 for i := 0; i < md.Fields().Len(); i++ { f := md.Fields().Get(i) if f == fd { found = true index = numIndices } if f.ContainingOneof() == nil || isLastOneofField(f) { numIndices++ } } if !found { panic(fmt.Sprintf("BUG: %v not in %v", fd.Name(), md.FullName())) } return index, presenceSize(numIndices) } func isLastOneofField(fd protoreflect.FieldDescriptor) bool { fields := fd.ContainingOneof().Fields() return fields.Get(fields.Len()-1) == fd } func (mi *MessageInfo) setPresent(p pointer, index uint32) { p.Apply(mi.presenceOffset).PresenceInfo().SetPresent(index, mi.presenceSize) } func (mi *MessageInfo) clearPresent(p pointer, index uint32) { p.Apply(mi.presenceOffset).PresenceInfo().ClearPresent(index) } func (mi *MessageInfo) present(p pointer, index uint32) bool { return p.Apply(mi.presenceOffset).PresenceInfo().Present(index) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe_opaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe_opaque.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "sync/atomic" "unsafe" ) func (p pointer) AtomicGetPointer() pointer { return pointer{p: atomic.LoadPointer((*unsafe.Pointer)(p.p))} } func (p pointer) AtomicSetPointer(v pointer) { atomic.StorePointer((*unsafe.Pointer)(p.p), v.p) } func (p pointer) AtomicSetNilPointer() { atomic.StorePointer((*unsafe.Pointer)(p.p), unsafe.Pointer(nil)) } func (p pointer) AtomicSetPointerIfNil(v pointer) pointer { if atomic.CompareAndSwapPointer((*unsafe.Pointer)(p.p), unsafe.Pointer(nil), v.p) { return v } return pointer{p: atomic.LoadPointer((*unsafe.Pointer)(p.p))} } type atomicV1MessageInfo struct{ p Pointer } func (mi *atomicV1MessageInfo) Get() Pointer { return Pointer(atomic.LoadPointer((*unsafe.Pointer)(&mi.p))) } func (mi *atomicV1MessageInfo) SetIfNil(p Pointer) Pointer { if atomic.CompareAndSwapPointer((*unsafe.Pointer)(&mi.p), nil, unsafe.Pointer(p)) { return p } return mi.Get() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_unsafe.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl // When using unsafe pointers, we can just treat enum values as int32s. var ( coderEnumNoZero = coderInt32NoZero coderEnum = coderInt32 coderEnumPtr = coderInt32Ptr coderEnumSlice = coderInt32Slice coderEnumPackedSlice = coderInt32PackedSlice )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/validate.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/validate.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "math" "math/bits" "reflect" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/runtime/protoiface" ) // ValidationStatus is the result of validating the wire-format encoding of a message. type ValidationStatus int const ( // ValidationUnknown indicates that unmarshaling the message might succeed or fail. // The validator was unable to render a judgement. // // The only causes of this status are an aberrant message type appearing somewhere // in the message or a failure in the extension resolver. ValidationUnknown ValidationStatus = iota + 1 // ValidationInvalid indicates that unmarshaling the message will fail. ValidationInvalid // ValidationValid indicates that unmarshaling the message will succeed. ValidationValid // ValidationWrongWireType indicates that a validated field does not have // the expected wire type. ValidationWrongWireType ) func (v ValidationStatus) String() string { switch v { case ValidationUnknown: return "ValidationUnknown" case ValidationInvalid: return "ValidationInvalid" case ValidationValid: return "ValidationValid" default: return fmt.Sprintf("ValidationStatus(%d)", int(v)) } } // Validate determines whether the contents of the buffer are a valid wire encoding // of the message type. // // This function is exposed for testing. func Validate(mt protoreflect.MessageType, in protoiface.UnmarshalInput) (out protoiface.UnmarshalOutput, _ ValidationStatus) { mi, ok := mt.(*MessageInfo) if !ok { return out, ValidationUnknown } if in.Resolver == nil { in.Resolver = protoregistry.GlobalTypes } o, st := mi.validate(in.Buf, 0, unmarshalOptions{ flags: in.Flags, resolver: in.Resolver, }) if o.initialized { out.Flags |= protoiface.UnmarshalInitialized } return out, st } type validationInfo struct { mi *MessageInfo typ validationType keyType, valType validationType // For non-required fields, requiredBit is 0. // // For required fields, requiredBit's nth bit is set, where n is a // unique index in the range [0, MessageInfo.numRequiredFields). // // If there are more than 64 required fields, requiredBit is 0. requiredBit uint64 } type validationType uint8 const ( validationTypeOther validationType = iota validationTypeMessage validationTypeGroup validationTypeMap validationTypeRepeatedVarint validationTypeRepeatedFixed32 validationTypeRepeatedFixed64 validationTypeVarint validationTypeFixed32 validationTypeFixed64 validationTypeBytes validationTypeUTF8String validationTypeMessageSetItem ) func newFieldValidationInfo(mi *MessageInfo, si structInfo, fd protoreflect.FieldDescriptor, ft reflect.Type) validationInfo { var vi validationInfo switch { case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): switch fd.Kind() { case protoreflect.MessageKind: vi.typ = validationTypeMessage if ot, ok := si.oneofWrappersByNumber[fd.Number()]; ok { vi.mi = getMessageInfo(ot.Field(0).Type) } case protoreflect.GroupKind: vi.typ = validationTypeGroup if ot, ok := si.oneofWrappersByNumber[fd.Number()]; ok { vi.mi = getMessageInfo(ot.Field(0).Type) } case protoreflect.StringKind: if strs.EnforceUTF8(fd) { vi.typ = validationTypeUTF8String } } default: vi = newValidationInfo(fd, ft) } if fd.Cardinality() == protoreflect.Required { // Avoid overflow. The required field check is done with a 64-bit mask, with // any message containing more than 64 required fields always reported as // potentially uninitialized, so it is not important to get a precise count // of the required fields past 64. if mi.numRequiredFields < math.MaxUint8 { mi.numRequiredFields++ vi.requiredBit = 1 << (mi.numRequiredFields - 1) } } return vi } func newValidationInfo(fd protoreflect.FieldDescriptor, ft reflect.Type) validationInfo { var vi validationInfo switch { case fd.IsList(): switch fd.Kind() { case protoreflect.MessageKind: vi.typ = validationTypeMessage if ft.Kind() == reflect.Ptr { // Repeated opaque message fields are *[]*T. ft = ft.Elem() } if ft.Kind() == reflect.Slice { vi.mi = getMessageInfo(ft.Elem()) } case protoreflect.GroupKind: vi.typ = validationTypeGroup if ft.Kind() == reflect.Ptr { // Repeated opaque message fields are *[]*T. ft = ft.Elem() } if ft.Kind() == reflect.Slice { vi.mi = getMessageInfo(ft.Elem()) } case protoreflect.StringKind: vi.typ = validationTypeBytes if strs.EnforceUTF8(fd) { vi.typ = validationTypeUTF8String } default: switch wireTypes[fd.Kind()] { case protowire.VarintType: vi.typ = validationTypeRepeatedVarint case protowire.Fixed32Type: vi.typ = validationTypeRepeatedFixed32 case protowire.Fixed64Type: vi.typ = validationTypeRepeatedFixed64 } } case fd.IsMap(): vi.typ = validationTypeMap switch fd.MapKey().Kind() { case protoreflect.StringKind: if strs.EnforceUTF8(fd) { vi.keyType = validationTypeUTF8String } } switch fd.MapValue().Kind() { case protoreflect.MessageKind: vi.valType = validationTypeMessage if ft.Kind() == reflect.Map { vi.mi = getMessageInfo(ft.Elem()) } case protoreflect.StringKind: if strs.EnforceUTF8(fd) { vi.valType = validationTypeUTF8String } } default: switch fd.Kind() { case protoreflect.MessageKind: vi.typ = validationTypeMessage vi.mi = getMessageInfo(ft) case protoreflect.GroupKind: vi.typ = validationTypeGroup vi.mi = getMessageInfo(ft) case protoreflect.StringKind: vi.typ = validationTypeBytes if strs.EnforceUTF8(fd) { vi.typ = validationTypeUTF8String } default: switch wireTypes[fd.Kind()] { case protowire.VarintType: vi.typ = validationTypeVarint case protowire.Fixed32Type: vi.typ = validationTypeFixed32 case protowire.Fixed64Type: vi.typ = validationTypeFixed64 case protowire.BytesType: vi.typ = validationTypeBytes } } } return vi } func (mi *MessageInfo) validate(b []byte, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, result ValidationStatus) { mi.init() type validationState struct { typ validationType keyType, valType validationType endGroup protowire.Number mi *MessageInfo tail []byte requiredMask uint64 } // Pre-allocate some slots to avoid repeated slice reallocation. states := make([]validationState, 0, 16) states = append(states, validationState{ typ: validationTypeMessage, mi: mi, }) if groupTag > 0 { states[0].typ = validationTypeGroup states[0].endGroup = groupTag } initialized := true start := len(b) State: for len(states) > 0 { st := &states[len(states)-1] for len(b) > 0 { // Parse the tag (field number and wire type). var tag uint64 if b[0] < 0x80 { tag = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int tag, n = protowire.ConsumeVarint(b) if n < 0 { return out, ValidationInvalid } b = b[n:] } var num protowire.Number if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { return out, ValidationInvalid } else { num = protowire.Number(n) } wtyp := protowire.Type(tag & 7) if wtyp == protowire.EndGroupType { if st.endGroup == num { goto PopState } return out, ValidationInvalid } var vi validationInfo switch { case st.typ == validationTypeMap: switch num { case genid.MapEntry_Key_field_number: vi.typ = st.keyType case genid.MapEntry_Value_field_number: vi.typ = st.valType vi.mi = st.mi vi.requiredBit = 1 } case flags.ProtoLegacy && st.mi.isMessageSet: switch num { case messageset.FieldItem: vi.typ = validationTypeMessageSetItem } default: var f *coderFieldInfo if int(num) < len(st.mi.denseCoderFields) { f = st.mi.denseCoderFields[num] } else { f = st.mi.coderFields[num] } if f != nil { vi = f.validation break } // Possible extension field. // // TODO: We should return ValidationUnknown when: // 1. The resolver is not frozen. (More extensions may be added to it.) // 2. The resolver returns preg.NotFound. // In this case, a type added to the resolver in the future could cause // unmarshaling to begin failing. Supporting this requires some way to // determine if the resolver is frozen. xt, err := opts.resolver.FindExtensionByNumber(st.mi.Desc.FullName(), num) if err != nil && err != protoregistry.NotFound { return out, ValidationUnknown } if err == nil { vi = getExtensionFieldInfo(xt).validation } } if vi.requiredBit != 0 { // Check that the field has a compatible wire type. // We only need to consider non-repeated field types, // since repeated fields (and maps) can never be required. ok := false switch vi.typ { case validationTypeVarint: ok = wtyp == protowire.VarintType case validationTypeFixed32: ok = wtyp == protowire.Fixed32Type case validationTypeFixed64: ok = wtyp == protowire.Fixed64Type case validationTypeBytes, validationTypeUTF8String, validationTypeMessage: ok = wtyp == protowire.BytesType case validationTypeGroup: ok = wtyp == protowire.StartGroupType } if ok { st.requiredMask |= vi.requiredBit } } switch wtyp { case protowire.VarintType: if len(b) >= 10 { switch { case b[0] < 0x80: b = b[1:] case b[1] < 0x80: b = b[2:] case b[2] < 0x80: b = b[3:] case b[3] < 0x80: b = b[4:] case b[4] < 0x80: b = b[5:] case b[5] < 0x80: b = b[6:] case b[6] < 0x80: b = b[7:] case b[7] < 0x80: b = b[8:] case b[8] < 0x80: b = b[9:] case b[9] < 0x80 && b[9] < 2: b = b[10:] default: return out, ValidationInvalid } } else { switch { case len(b) > 0 && b[0] < 0x80: b = b[1:] case len(b) > 1 && b[1] < 0x80: b = b[2:] case len(b) > 2 && b[2] < 0x80: b = b[3:] case len(b) > 3 && b[3] < 0x80: b = b[4:] case len(b) > 4 && b[4] < 0x80: b = b[5:] case len(b) > 5 && b[5] < 0x80: b = b[6:] case len(b) > 6 && b[6] < 0x80: b = b[7:] case len(b) > 7 && b[7] < 0x80: b = b[8:] case len(b) > 8 && b[8] < 0x80: b = b[9:] case len(b) > 9 && b[9] < 2: b = b[10:] default: return out, ValidationInvalid } } continue State case protowire.BytesType: var size uint64 if len(b) >= 1 && b[0] < 0x80 { size = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { size = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int size, n = protowire.ConsumeVarint(b) if n < 0 { return out, ValidationInvalid } b = b[n:] } if size > uint64(len(b)) { return out, ValidationInvalid } v := b[:size] b = b[size:] switch vi.typ { case validationTypeMessage: if vi.mi == nil { return out, ValidationUnknown } vi.mi.init() fallthrough case validationTypeMap: if vi.mi != nil { vi.mi.init() } states = append(states, validationState{ typ: vi.typ, keyType: vi.keyType, valType: vi.valType, mi: vi.mi, tail: b, }) b = v continue State case validationTypeRepeatedVarint: // Packed field. for len(v) > 0 { _, n := protowire.ConsumeVarint(v) if n < 0 { return out, ValidationInvalid } v = v[n:] } case validationTypeRepeatedFixed32: // Packed field. if len(v)%4 != 0 { return out, ValidationInvalid } case validationTypeRepeatedFixed64: // Packed field. if len(v)%8 != 0 { return out, ValidationInvalid } case validationTypeUTF8String: if !utf8.Valid(v) { return out, ValidationInvalid } } case protowire.Fixed32Type: if len(b) < 4 { return out, ValidationInvalid } b = b[4:] case protowire.Fixed64Type: if len(b) < 8 { return out, ValidationInvalid } b = b[8:] case protowire.StartGroupType: switch { case vi.typ == validationTypeGroup: if vi.mi == nil { return out, ValidationUnknown } vi.mi.init() states = append(states, validationState{ typ: validationTypeGroup, mi: vi.mi, endGroup: num, }) continue State case flags.ProtoLegacy && vi.typ == validationTypeMessageSetItem: typeid, v, n, err := messageset.ConsumeFieldValue(b, false) if err != nil { return out, ValidationInvalid } xt, err := opts.resolver.FindExtensionByNumber(st.mi.Desc.FullName(), typeid) switch { case err == protoregistry.NotFound: b = b[n:] case err != nil: return out, ValidationUnknown default: xvi := getExtensionFieldInfo(xt).validation if xvi.mi != nil { xvi.mi.init() } states = append(states, validationState{ typ: xvi.typ, mi: xvi.mi, tail: b[n:], }) b = v continue State } default: n := protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return out, ValidationInvalid } b = b[n:] } default: return out, ValidationInvalid } } if st.endGroup != 0 { return out, ValidationInvalid } if len(b) != 0 { return out, ValidationInvalid } b = st.tail PopState: numRequiredFields := 0 switch st.typ { case validationTypeMessage, validationTypeGroup: numRequiredFields = int(st.mi.numRequiredFields) case validationTypeMap: // If this is a map field with a message value that contains // required fields, require that the value be present. if st.mi != nil && st.mi.numRequiredFields > 0 { numRequiredFields = 1 } } // If there are more than 64 required fields, this check will // always fail and we will report that the message is potentially // uninitialized. if numRequiredFields > 0 && bits.OnesCount64(st.requiredMask) != numRequiredFields { initialized = false } states = states[:len(states)-1] } out.n = start - len(b) if initialized { out.initialized = true } return out, ValidationValid }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_message.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/descopts" ptag "google.golang.org/protobuf/internal/encoding/tag" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // legacyWrapMessage wraps v as a protoreflect.Message, // where v must be a *struct kind and not implement the v2 API already. func legacyWrapMessage(v reflect.Value) protoreflect.Message { t := v.Type() if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { return aberrantMessage{v: v} } mt := legacyLoadMessageInfo(t, "") return mt.MessageOf(v.Interface()) } // legacyLoadMessageType dynamically loads a protoreflect.Type for t, // where t must be not implement the v2 API already. // The provided name is used if it cannot be determined from the message. func legacyLoadMessageType(t reflect.Type, name protoreflect.FullName) protoreflect.MessageType { if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { return aberrantMessageType{t} } return legacyLoadMessageInfo(t, name) } var legacyMessageTypeCache sync.Map // map[reflect.Type]*MessageInfo // legacyLoadMessageInfo dynamically loads a *MessageInfo for t, // where t must be a *struct kind and not implement the v2 API already. // The provided name is used if it cannot be determined from the message. func legacyLoadMessageInfo(t reflect.Type, name protoreflect.FullName) *MessageInfo { // Fast-path: check if a MessageInfo is cached for this concrete type. if mt, ok := legacyMessageTypeCache.Load(t); ok { return mt.(*MessageInfo) } // Slow-path: derive message descriptor and initialize MessageInfo. mi := &MessageInfo{ Desc: legacyLoadMessageDesc(t, name), GoReflectType: t, } var hasMarshal, hasUnmarshal bool v := reflect.Zero(t).Interface() if _, hasMarshal = v.(legacyMarshaler); hasMarshal { mi.methods.Marshal = legacyMarshal // We have no way to tell whether the type's Marshal method // supports deterministic serialization or not, but this // preserves the v1 implementation's behavior of always // calling Marshal methods when present. mi.methods.Flags |= protoiface.SupportMarshalDeterministic } if _, hasUnmarshal = v.(legacyUnmarshaler); hasUnmarshal { mi.methods.Unmarshal = legacyUnmarshal } if _, hasMerge := v.(legacyMerger); hasMerge || (hasMarshal && hasUnmarshal) { mi.methods.Merge = legacyMerge } if mi, ok := legacyMessageTypeCache.LoadOrStore(t, mi); ok { return mi.(*MessageInfo) } return mi } var legacyMessageDescCache sync.Map // map[reflect.Type]protoreflect.MessageDescriptor // LegacyLoadMessageDesc returns an MessageDescriptor derived from the Go type, // which should be a *struct kind and must not implement the v2 API already. // // This is exported for testing purposes. func LegacyLoadMessageDesc(t reflect.Type) protoreflect.MessageDescriptor { return legacyLoadMessageDesc(t, "") } func legacyLoadMessageDesc(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor { // Fast-path: check if a MessageDescriptor is cached for this concrete type. if mi, ok := legacyMessageDescCache.Load(t); ok { return mi.(protoreflect.MessageDescriptor) } // Slow-path: initialize MessageDescriptor from the raw descriptor. mv := reflect.Zero(t).Interface() if _, ok := mv.(protoreflect.ProtoMessage); ok { panic(fmt.Sprintf("%v already implements proto.Message", t)) } mdV1, ok := mv.(messageV1) if !ok { return aberrantLoadMessageDesc(t, name) } // If this is a dynamic message type where there isn't a 1-1 mapping between // Go and protobuf types, calling the Descriptor method on the zero value of // the message type isn't likely to work. If it panics, swallow the panic and // continue as if the Descriptor method wasn't present. b, idxs := func() ([]byte, []int) { defer func() { recover() }() return mdV1.Descriptor() }() if b == nil { return aberrantLoadMessageDesc(t, name) } // If the Go type has no fields, then this might be a proto3 empty message // from before the size cache was added. If there are any fields, check to // see that at least one of them looks like something we generated. if t.Elem().Kind() == reflect.Struct { if nfield := t.Elem().NumField(); nfield > 0 { hasProtoField := false for i := 0; i < nfield; i++ { f := t.Elem().Field(i) if f.Tag.Get("protobuf") != "" || f.Tag.Get("protobuf_oneof") != "" || strings.HasPrefix(f.Name, "XXX_") { hasProtoField = true break } } if !hasProtoField { return aberrantLoadMessageDesc(t, name) } } } md := legacyLoadFileDesc(b).Messages().Get(idxs[0]) for _, i := range idxs[1:] { md = md.Messages().Get(i) } if name != "" && md.FullName() != name { panic(fmt.Sprintf("mismatching message name: got %v, want %v", md.FullName(), name)) } if md, ok := legacyMessageDescCache.LoadOrStore(t, md); ok { return md.(protoreflect.MessageDescriptor) } return md } var ( aberrantMessageDescLock sync.Mutex aberrantMessageDescCache map[reflect.Type]protoreflect.MessageDescriptor ) // aberrantLoadMessageDesc returns an MessageDescriptor derived from the Go type, // which must not implement protoreflect.ProtoMessage or messageV1. // // This is a best-effort derivation of the message descriptor using the protobuf // tags on the struct fields. func aberrantLoadMessageDesc(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor { aberrantMessageDescLock.Lock() defer aberrantMessageDescLock.Unlock() if aberrantMessageDescCache == nil { aberrantMessageDescCache = make(map[reflect.Type]protoreflect.MessageDescriptor) } return aberrantLoadMessageDescReentrant(t, name) } func aberrantLoadMessageDescReentrant(t reflect.Type, name protoreflect.FullName) protoreflect.MessageDescriptor { // Fast-path: check if an MessageDescriptor is cached for this concrete type. if md, ok := aberrantMessageDescCache[t]; ok { return md } // Slow-path: construct a descriptor from the Go struct type (best-effort). // Cache the MessageDescriptor early on so that we can resolve internal // cyclic references. md := &filedesc.Message{L2: new(filedesc.MessageL2)} md.L0.FullName = aberrantDeriveMessageName(t, name) md.L0.ParentFile = filedesc.SurrogateProto2 aberrantMessageDescCache[t] = md if t.Kind() != reflect.Ptr || t.Elem().Kind() != reflect.Struct { return md } // Try to determine if the message is using proto3 by checking scalars. for i := 0; i < t.Elem().NumField(); i++ { f := t.Elem().Field(i) if tag := f.Tag.Get("protobuf"); tag != "" { switch f.Type.Kind() { case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: md.L0.ParentFile = filedesc.SurrogateProto3 } for _, s := range strings.Split(tag, ",") { if s == "proto3" { md.L0.ParentFile = filedesc.SurrogateProto3 } } } } md.L1.EditionFeatures = md.L0.ParentFile.L1.EditionFeatures // Obtain a list of oneof wrapper types. var oneofWrappers []reflect.Type methods := make([]reflect.Method, 0, 2) if m, ok := t.MethodByName("XXX_OneofFuncs"); ok { methods = append(methods, m) } if m, ok := t.MethodByName("XXX_OneofWrappers"); ok { methods = append(methods, m) } for _, fn := range methods { for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) { if vs, ok := v.Interface().([]any); ok { for _, v := range vs { oneofWrappers = append(oneofWrappers, reflect.TypeOf(v)) } } } } // Obtain a list of the extension ranges. if fn, ok := t.MethodByName("ExtensionRangeArray"); ok { vs := fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))})[0] for i := 0; i < vs.Len(); i++ { v := vs.Index(i) md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, [2]protoreflect.FieldNumber{ protoreflect.FieldNumber(v.FieldByName("Start").Int()), protoreflect.FieldNumber(v.FieldByName("End").Int() + 1), }) md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, nil) } } // Derive the message fields by inspecting the struct fields. for i := 0; i < t.Elem().NumField(); i++ { f := t.Elem().Field(i) if tag := f.Tag.Get("protobuf"); tag != "" { tagKey := f.Tag.Get("protobuf_key") tagVal := f.Tag.Get("protobuf_val") aberrantAppendField(md, f.Type, tag, tagKey, tagVal) } if tag := f.Tag.Get("protobuf_oneof"); tag != "" { n := len(md.L2.Oneofs.List) md.L2.Oneofs.List = append(md.L2.Oneofs.List, filedesc.Oneof{}) od := &md.L2.Oneofs.List[n] od.L0.FullName = md.FullName().Append(protoreflect.Name(tag)) od.L0.ParentFile = md.L0.ParentFile od.L1.EditionFeatures = md.L1.EditionFeatures od.L0.Parent = md od.L0.Index = n for _, t := range oneofWrappers { if t.Implements(f.Type) { f := t.Elem().Field(0) if tag := f.Tag.Get("protobuf"); tag != "" { aberrantAppendField(md, f.Type, tag, "", "") fd := &md.L2.Fields.List[len(md.L2.Fields.List)-1] fd.L1.ContainingOneof = od fd.L1.EditionFeatures = od.L1.EditionFeatures od.L1.Fields.List = append(od.L1.Fields.List, fd) } } } } } return md } func aberrantDeriveMessageName(t reflect.Type, name protoreflect.FullName) protoreflect.FullName { if name.IsValid() { return name } func() { defer func() { recover() }() // swallow possible nil panics if m, ok := reflect.Zero(t).Interface().(interface{ XXX_MessageName() string }); ok { name = protoreflect.FullName(m.XXX_MessageName()) } }() if name.IsValid() { return name } if t.Kind() == reflect.Ptr { t = t.Elem() } return AberrantDeriveFullName(t) } func aberrantAppendField(md *filedesc.Message, goType reflect.Type, tag, tagKey, tagVal string) { t := goType isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 if isOptional || isRepeated { t = t.Elem() } fd := ptag.Unmarshal(tag, t, placeholderEnumValues{}).(*filedesc.Field) // Append field descriptor to the message. n := len(md.L2.Fields.List) md.L2.Fields.List = append(md.L2.Fields.List, *fd) fd = &md.L2.Fields.List[n] fd.L0.FullName = md.FullName().Append(fd.Name()) fd.L0.ParentFile = md.L0.ParentFile fd.L0.Parent = md fd.L0.Index = n if fd.L1.EditionFeatures.IsPacked { fd.L1.Options = func() protoreflect.ProtoMessage { opts := descopts.Field.ProtoReflect().New() if fd.L1.EditionFeatures.IsPacked { opts.Set(opts.Descriptor().Fields().ByName("packed"), protoreflect.ValueOfBool(fd.L1.EditionFeatures.IsPacked)) } return opts.Interface() } } // Populate Enum and Message. if fd.Enum() == nil && fd.Kind() == protoreflect.EnumKind { switch v := reflect.Zero(t).Interface().(type) { case protoreflect.Enum: fd.L1.Enum = v.Descriptor() default: fd.L1.Enum = LegacyLoadEnumDesc(t) } } if fd.Message() == nil && (fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind) { switch v := reflect.Zero(t).Interface().(type) { case protoreflect.ProtoMessage: fd.L1.Message = v.ProtoReflect().Descriptor() case messageV1: fd.L1.Message = LegacyLoadMessageDesc(t) default: if t.Kind() == reflect.Map { n := len(md.L1.Messages.List) md.L1.Messages.List = append(md.L1.Messages.List, filedesc.Message{L2: new(filedesc.MessageL2)}) md2 := &md.L1.Messages.List[n] md2.L0.FullName = md.FullName().Append(protoreflect.Name(strs.MapEntryName(string(fd.Name())))) md2.L0.ParentFile = md.L0.ParentFile md2.L0.Parent = md md2.L0.Index = n md2.L1.EditionFeatures = md.L1.EditionFeatures md2.L1.IsMapEntry = true md2.L2.Options = func() protoreflect.ProtoMessage { opts := descopts.Message.ProtoReflect().New() opts.Set(opts.Descriptor().Fields().ByName("map_entry"), protoreflect.ValueOfBool(true)) return opts.Interface() } aberrantAppendField(md2, t.Key(), tagKey, "", "") aberrantAppendField(md2, t.Elem(), tagVal, "", "") fd.L1.Message = md2 break } fd.L1.Message = aberrantLoadMessageDescReentrant(t, "") } } } type placeholderEnumValues struct { protoreflect.EnumValueDescriptors } func (placeholderEnumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor { return filedesc.PlaceholderEnumValue(protoreflect.FullName(fmt.Sprintf("UNKNOWN_%d", n))) } // legacyMarshaler is the proto.Marshaler interface superseded by protoiface.Methoder. type legacyMarshaler interface { Marshal() ([]byte, error) } // legacyUnmarshaler is the proto.Unmarshaler interface superseded by protoiface.Methoder. type legacyUnmarshaler interface { Unmarshal([]byte) error } // legacyMerger is the proto.Merger interface superseded by protoiface.Methoder. type legacyMerger interface { Merge(protoiface.MessageV1) } var aberrantProtoMethods = &protoiface.Methods{ Marshal: legacyMarshal, Unmarshal: legacyUnmarshal, Merge: legacyMerge, // We have no way to tell whether the type's Marshal method // supports deterministic serialization or not, but this // preserves the v1 implementation's behavior of always // calling Marshal methods when present. Flags: protoiface.SupportMarshalDeterministic, } func legacyMarshal(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) { v := in.Message.(unwrapper).protoUnwrap() marshaler, ok := v.(legacyMarshaler) if !ok { return protoiface.MarshalOutput{}, errors.New("%T does not implement Marshal", v) } out, err := marshaler.Marshal() if in.Buf != nil { out = append(in.Buf, out...) } return protoiface.MarshalOutput{ Buf: out, }, err } func legacyUnmarshal(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { v := in.Message.(unwrapper).protoUnwrap() unmarshaler, ok := v.(legacyUnmarshaler) if !ok { return protoiface.UnmarshalOutput{}, errors.New("%T does not implement Unmarshal", v) } return protoiface.UnmarshalOutput{}, unmarshaler.Unmarshal(in.Buf) } func legacyMerge(in protoiface.MergeInput) protoiface.MergeOutput { // Check whether this supports the legacy merger. dstv := in.Destination.(unwrapper).protoUnwrap() merger, ok := dstv.(legacyMerger) if ok { merger.Merge(Export{}.ProtoMessageV1Of(in.Source)) return protoiface.MergeOutput{Flags: protoiface.MergeComplete} } // If legacy merger is unavailable, implement merge in terms of // a marshal and unmarshal operation. srcv := in.Source.(unwrapper).protoUnwrap() marshaler, ok := srcv.(legacyMarshaler) if !ok { return protoiface.MergeOutput{} } dstv = in.Destination.(unwrapper).protoUnwrap() unmarshaler, ok := dstv.(legacyUnmarshaler) if !ok { return protoiface.MergeOutput{} } if !in.Source.IsValid() { // Legacy Marshal methods may not function on nil messages. // Check for a typed nil source only after we confirm that // legacy Marshal/Unmarshal methods are present, for // consistency. return protoiface.MergeOutput{Flags: protoiface.MergeComplete} } b, err := marshaler.Marshal() if err != nil { return protoiface.MergeOutput{} } err = unmarshaler.Unmarshal(b) if err != nil { return protoiface.MergeOutput{} } return protoiface.MergeOutput{Flags: protoiface.MergeComplete} } // aberrantMessageType implements MessageType for all types other than pointer-to-struct. type aberrantMessageType struct { t reflect.Type } func (mt aberrantMessageType) New() protoreflect.Message { if mt.t.Kind() == reflect.Ptr { return aberrantMessage{reflect.New(mt.t.Elem())} } return aberrantMessage{reflect.Zero(mt.t)} } func (mt aberrantMessageType) Zero() protoreflect.Message { return aberrantMessage{reflect.Zero(mt.t)} } func (mt aberrantMessageType) GoType() reflect.Type { return mt.t } func (mt aberrantMessageType) Descriptor() protoreflect.MessageDescriptor { return LegacyLoadMessageDesc(mt.t) } // aberrantMessage implements Message for all types other than pointer-to-struct. // // When the underlying type implements legacyMarshaler or legacyUnmarshaler, // the aberrant Message can be marshaled or unmarshaled. Otherwise, there is // not much that can be done with values of this type. type aberrantMessage struct { v reflect.Value } // Reset implements the v1 proto.Message.Reset method. func (m aberrantMessage) Reset() { if mr, ok := m.v.Interface().(interface{ Reset() }); ok { mr.Reset() return } if m.v.Kind() == reflect.Ptr && !m.v.IsNil() { m.v.Elem().Set(reflect.Zero(m.v.Type().Elem())) } } func (m aberrantMessage) ProtoReflect() protoreflect.Message { return m } func (m aberrantMessage) Descriptor() protoreflect.MessageDescriptor { return LegacyLoadMessageDesc(m.v.Type()) } func (m aberrantMessage) Type() protoreflect.MessageType { return aberrantMessageType{m.v.Type()} } func (m aberrantMessage) New() protoreflect.Message { if m.v.Type().Kind() == reflect.Ptr { return aberrantMessage{reflect.New(m.v.Type().Elem())} } return aberrantMessage{reflect.Zero(m.v.Type())} } func (m aberrantMessage) Interface() protoreflect.ProtoMessage { return m } func (m aberrantMessage) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { return } func (m aberrantMessage) Has(protoreflect.FieldDescriptor) bool { return false } func (m aberrantMessage) Clear(protoreflect.FieldDescriptor) { panic("invalid Message.Clear on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { if fd.Default().IsValid() { return fd.Default() } panic("invalid Message.Get on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) Set(protoreflect.FieldDescriptor, protoreflect.Value) { panic("invalid Message.Set on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) Mutable(protoreflect.FieldDescriptor) protoreflect.Value { panic("invalid Message.Mutable on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) NewField(protoreflect.FieldDescriptor) protoreflect.Value { panic("invalid Message.NewField on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) WhichOneof(protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { panic("invalid Message.WhichOneof descriptor on " + string(m.Descriptor().FullName())) } func (m aberrantMessage) GetUnknown() protoreflect.RawFields { return nil } func (m aberrantMessage) SetUnknown(protoreflect.RawFields) { // SetUnknown discards its input on messages which don't support unknown field storage. } func (m aberrantMessage) IsValid() bool { if m.v.Kind() == reflect.Ptr { return !m.v.IsNil() } return false } func (m aberrantMessage) ProtoMethods() *protoiface.Methods { return aberrantProtoMethods } func (m aberrantMessage) protoUnwrap() any { return m.v.Interface() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/equal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/equal.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "bytes" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) func equal(in protoiface.EqualInput) protoiface.EqualOutput { return protoiface.EqualOutput{Equal: equalMessage(in.MessageA, in.MessageB)} } // equalMessage is a fast-path variant of protoreflect.equalMessage. // It takes advantage of the internal messageState type to avoid // unnecessary allocations, type assertions. func equalMessage(mx, my protoreflect.Message) bool { if mx == nil || my == nil { return mx == my } if mx.Descriptor() != my.Descriptor() { return false } msx, ok := mx.(*messageState) if !ok { return protoreflect.ValueOfMessage(mx).Equal(protoreflect.ValueOfMessage(my)) } msy, ok := my.(*messageState) if !ok { return protoreflect.ValueOfMessage(mx).Equal(protoreflect.ValueOfMessage(my)) } mi := msx.messageInfo() miy := msy.messageInfo() if mi != miy { return protoreflect.ValueOfMessage(mx).Equal(protoreflect.ValueOfMessage(my)) } mi.init() // Compares regular fields // Modified Message.Range code that compares two messages of the same type // while going over the fields. for _, ri := range mi.rangeInfos { var fd protoreflect.FieldDescriptor var vx, vy protoreflect.Value switch ri := ri.(type) { case *fieldInfo: hx := ri.has(msx.pointer()) hy := ri.has(msy.pointer()) if hx != hy { return false } if !hx { continue } fd = ri.fieldDesc vx = ri.get(msx.pointer()) vy = ri.get(msy.pointer()) case *oneofInfo: fnx := ri.which(msx.pointer()) fny := ri.which(msy.pointer()) if fnx != fny { return false } if fnx <= 0 { continue } fi := mi.fields[fnx] fd = fi.fieldDesc vx = fi.get(msx.pointer()) vy = fi.get(msy.pointer()) } if !equalValue(fd, vx, vy) { return false } } // Compare extensions. // This is more complicated because mx or my could have empty/nil extension maps, // however some populated extension map values are equal to nil extension maps. emx := mi.extensionMap(msx.pointer()) emy := mi.extensionMap(msy.pointer()) if emx != nil { for k, x := range *emx { xd := x.Type().TypeDescriptor() xv := x.Value() var y ExtensionField ok := false if emy != nil { y, ok = (*emy)[k] } // We need to treat empty lists as equal to nil values if emy == nil || !ok { if xd.IsList() && xv.List().Len() == 0 { continue } return false } if !equalValue(xd, xv, y.Value()) { return false } } } if emy != nil { // emy may have extensions emx does not have, need to check them as well for k, y := range *emy { if emx != nil { // emx has the field, so we already checked it if _, ok := (*emx)[k]; ok { continue } } // Empty lists are equal to nil if y.Type().TypeDescriptor().IsList() && y.Value().List().Len() == 0 { continue } // Cant be equal if the extension is populated return false } } return equalUnknown(mx.GetUnknown(), my.GetUnknown()) } func equalValue(fd protoreflect.FieldDescriptor, vx, vy protoreflect.Value) bool { // slow path if fd.Kind() != protoreflect.MessageKind { return vx.Equal(vy) } // fast path special cases if fd.IsMap() { if fd.MapValue().Kind() == protoreflect.MessageKind { return equalMessageMap(vx.Map(), vy.Map()) } return vx.Equal(vy) } if fd.IsList() { return equalMessageList(vx.List(), vy.List()) } return equalMessage(vx.Message(), vy.Message()) } // Mostly copied from protoreflect.equalMap. // This variant only works for messages as map types. // All other map types should be handled via Value.Equal. func equalMessageMap(mx, my protoreflect.Map) bool { if mx.Len() != my.Len() { return false } equal := true mx.Range(func(k protoreflect.MapKey, vx protoreflect.Value) bool { if !my.Has(k) { equal = false return false } vy := my.Get(k) equal = equalMessage(vx.Message(), vy.Message()) return equal }) return equal } // Mostly copied from protoreflect.equalList. // The only change is the usage of equalImpl instead of protoreflect.equalValue. func equalMessageList(lx, ly protoreflect.List) bool { if lx.Len() != ly.Len() { return false } for i := 0; i < lx.Len(); i++ { // We only operate on messages here since equalImpl will not call us in any other case. if !equalMessage(lx.Get(i).Message(), ly.Get(i).Message()) { return false } } return true } // equalUnknown compares unknown fields by direct comparison on the raw bytes // of each individual field number. // Copied from protoreflect.equalUnknown. func equalUnknown(x, y protoreflect.RawFields) bool { if len(x) != len(y) { return false } if bytes.Equal([]byte(x), []byte(y)) { return true } mx := make(map[protoreflect.FieldNumber]protoreflect.RawFields) my := make(map[protoreflect.FieldNumber]protoreflect.RawFields) for len(x) > 0 { fnum, _, n := protowire.ConsumeField(x) mx[fnum] = append(mx[fnum], x[:n]...) x = x[n:] } for len(y) > 0 { fnum, _, n := protowire.ConsumeField(y) my[fnum] = append(my[fnum], y[:n]...) y = y[n:] } if len(mx) != len(my) { return false } for k, v1 := range mx { if v2, ok := my[k]; !ok || !bytes.Equal([]byte(v1), []byte(v2)) { return false } } return true }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_gen.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package impl import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/reflect/protoreflect" ) // sizeBool returns the size of wire encoding a bool pointer as a Bool. func sizeBool(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Bool() return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } // appendBool wire encodes a bool pointer as a Bool. func appendBool(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Bool() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } // consumeBool wire decodes a bool pointer as a Bool. func consumeBool(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } *p.Bool() = protowire.DecodeBool(v) out.n = n return out, nil } var coderBool = pointerCoderFuncs{ size: sizeBool, marshal: appendBool, unmarshal: consumeBool, merge: mergeBool, } // sizeBoolNoZero returns the size of wire encoding a bool pointer as a Bool. // The zero value is not encoded. func sizeBoolNoZero(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Bool() if v == false { return 0 } return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } // appendBoolNoZero wire encodes a bool pointer as a Bool. // The zero value is not encoded. func appendBoolNoZero(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Bool() if v == false { return b, nil } b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } var coderBoolNoZero = pointerCoderFuncs{ size: sizeBoolNoZero, marshal: appendBoolNoZero, unmarshal: consumeBool, merge: mergeBoolNoZero, } // sizeBoolPtr returns the size of wire encoding a *bool pointer as a Bool. // It panics if the pointer is nil. func sizeBoolPtr(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := **p.BoolPtr() return f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } // appendBoolPtr wire encodes a *bool pointer as a Bool. // It panics if the pointer is nil. func appendBoolPtr(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := **p.BoolPtr() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) return b, nil } // consumeBoolPtr wire decodes a *bool pointer as a Bool. func consumeBoolPtr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } vp := p.BoolPtr() if *vp == nil { *vp = new(bool) } **vp = protowire.DecodeBool(v) out.n = n return out, nil } var coderBoolPtr = pointerCoderFuncs{ size: sizeBoolPtr, marshal: appendBoolPtr, unmarshal: consumeBoolPtr, merge: mergeBoolPtr, } // sizeBoolSlice returns the size of wire encoding a []bool pointer as a repeated Bool. func sizeBoolSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := *p.BoolSlice() for _, v := range s { size += f.tagsize + protowire.SizeVarint(protowire.EncodeBool(v)) } return size } // appendBoolSlice encodes a []bool pointer as a repeated Bool. func appendBoolSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := *p.BoolSlice() for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v)) } return b, nil } // consumeBoolSlice wire decodes a []bool pointer as a repeated Bool. func consumeBoolSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { sp := p.BoolSlice() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } count := 0 for _, v := range b { if v < 0x80 { count++ } } if count > 0 { p.growBoolSlice(count) } s := *sp for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } s = append(s, protowire.DecodeBool(v)) b = b[n:] } *sp = s out.n = n return out, nil } if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } *sp = append(*sp, protowire.DecodeBool(v)) out.n = n return out, nil } var coderBoolSlice = pointerCoderFuncs{ size: sizeBoolSlice, marshal: appendBoolSlice, unmarshal: consumeBoolSlice, merge: mergeBoolSlice, } // sizeBoolPackedSlice returns the size of wire encoding a []bool pointer as a packed repeated Bool. func sizeBoolPackedSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := *p.BoolSlice() if len(s) == 0 { return 0 } n := 0 for _, v := range s { n += protowire.SizeVarint(protowire.EncodeBool(v)) } return f.tagsize + protowire.SizeBytes(n) } // appendBoolPackedSlice encodes a []bool pointer as a packed repeated Bool. func appendBoolPackedSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := *p.BoolSlice() if len(s) == 0 { return b, nil } b = protowire.AppendVarint(b, f.wiretag) n := 0 for _, v := range s { n += protowire.SizeVarint(protowire.EncodeBool(v)) } b = protowire.AppendVarint(b, uint64(n)) for _, v := range s { b = protowire.AppendVarint(b, protowire.EncodeBool(v)) } return b, nil } var coderBoolPackedSlice = pointerCoderFuncs{ size: sizeBoolPackedSlice, marshal: appendBoolPackedSlice, unmarshal: consumeBoolSlice, merge: mergeBoolSlice, } // sizeBoolValue returns the size of wire encoding a bool value as a Bool. func sizeBoolValue(v protoreflect.Value, tagsize int, opts marshalOptions) int { return tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } // appendBoolValue encodes a bool value as a Bool. func appendBoolValue(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) return b, nil } // consumeBoolValue decodes a bool value as a Bool. func consumeBoolValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } out.n = n return protoreflect.ValueOfBool(protowire.DecodeBool(v)), out, nil } var coderBoolValue = valueCoderFuncs{ size: sizeBoolValue, marshal: appendBoolValue, unmarshal: consumeBoolValue, merge: mergeScalarValue, } // sizeBoolSliceValue returns the size of wire encoding a []bool value as a repeated Bool. func sizeBoolSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) size += tagsize + protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } return size } // appendBoolSliceValue encodes a []bool value as a repeated Bool. func appendBoolSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) } return b, nil } // consumeBoolSliceValue wire decodes a []bool value as a repeated Bool. func consumeBoolSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, errDecode } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) b = b[n:] } out.n = n return listv, out, nil } if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) out.n = n return listv, out, nil } var coderBoolSliceValue = valueCoderFuncs{ size: sizeBoolSliceValue, marshal: appendBoolSliceValue, unmarshal: consumeBoolSliceValue, merge: mergeListValue, } // sizeBoolPackedSliceValue returns the size of wire encoding a []bool value as a packed repeated Bool. func sizeBoolPackedSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() llen := list.Len() if llen == 0 { return 0 } n := 0 for i, llen := 0, llen; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } return tagsize + protowire.SizeBytes(n) } // appendBoolPackedSliceValue encodes a []bool value as a packed repeated Bool. func appendBoolPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() llen := list.Len() if llen == 0 { return b, nil } b = protowire.AppendVarint(b, wiretag) n := 0 for i := 0; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(protowire.EncodeBool(v.Bool())) } b = protowire.AppendVarint(b, uint64(n)) for i := 0; i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) } return b, nil } var coderBoolPackedSliceValue = valueCoderFuncs{ size: sizeBoolPackedSliceValue, marshal: appendBoolPackedSliceValue, unmarshal: consumeBoolSliceValue, merge: mergeListValue, } // sizeEnumValue returns the size of wire encoding a value as a Enum. func sizeEnumValue(v protoreflect.Value, tagsize int, opts marshalOptions) int { return tagsize + protowire.SizeVarint(uint64(v.Enum())) } // appendEnumValue encodes a value as a Enum. func appendEnumValue(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(v.Enum())) return b, nil } // consumeEnumValue decodes a value as a Enum. func consumeEnumValue(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } out.n = n return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), out, nil } var coderEnumValue = valueCoderFuncs{ size: sizeEnumValue, marshal: appendEnumValue, unmarshal: consumeEnumValue, merge: mergeScalarValue, } // sizeEnumSliceValue returns the size of wire encoding a [] value as a repeated Enum. func sizeEnumSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) size += tagsize + protowire.SizeVarint(uint64(v.Enum())) } return size } // appendEnumSliceValue encodes a [] value as a repeated Enum. func appendEnumSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(v.Enum())) } return b, nil } // consumeEnumSliceValue wire decodes a [] value as a repeated Enum. func consumeEnumSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, errDecode } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) b = b[n:] } out.n = n return listv, out, nil } if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) out.n = n return listv, out, nil } var coderEnumSliceValue = valueCoderFuncs{ size: sizeEnumSliceValue, marshal: appendEnumSliceValue, unmarshal: consumeEnumSliceValue, merge: mergeListValue, } // sizeEnumPackedSliceValue returns the size of wire encoding a [] value as a packed repeated Enum. func sizeEnumPackedSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() llen := list.Len() if llen == 0 { return 0 } n := 0 for i, llen := 0, llen; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(uint64(v.Enum())) } return tagsize + protowire.SizeBytes(n) } // appendEnumPackedSliceValue encodes a [] value as a packed repeated Enum. func appendEnumPackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() llen := list.Len() if llen == 0 { return b, nil } b = protowire.AppendVarint(b, wiretag) n := 0 for i := 0; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(uint64(v.Enum())) } b = protowire.AppendVarint(b, uint64(n)) for i := 0; i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, uint64(v.Enum())) } return b, nil } var coderEnumPackedSliceValue = valueCoderFuncs{ size: sizeEnumPackedSliceValue, marshal: appendEnumPackedSliceValue, unmarshal: consumeEnumSliceValue, merge: mergeListValue, } // sizeInt32 returns the size of wire encoding a int32 pointer as a Int32. func sizeInt32(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Int32() return f.tagsize + protowire.SizeVarint(uint64(v)) } // appendInt32 wire encodes a int32 pointer as a Int32. func appendInt32(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Int32() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(v)) return b, nil } // consumeInt32 wire decodes a int32 pointer as a Int32. func consumeInt32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } *p.Int32() = int32(v) out.n = n return out, nil } var coderInt32 = pointerCoderFuncs{ size: sizeInt32, marshal: appendInt32, unmarshal: consumeInt32, merge: mergeInt32, } // sizeInt32NoZero returns the size of wire encoding a int32 pointer as a Int32. // The zero value is not encoded. func sizeInt32NoZero(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Int32() if v == 0 { return 0 } return f.tagsize + protowire.SizeVarint(uint64(v)) } // appendInt32NoZero wire encodes a int32 pointer as a Int32. // The zero value is not encoded. func appendInt32NoZero(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Int32() if v == 0 { return b, nil } b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(v)) return b, nil } var coderInt32NoZero = pointerCoderFuncs{ size: sizeInt32NoZero, marshal: appendInt32NoZero, unmarshal: consumeInt32, merge: mergeInt32NoZero, } // sizeInt32Ptr returns the size of wire encoding a *int32 pointer as a Int32. // It panics if the pointer is nil. func sizeInt32Ptr(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := **p.Int32Ptr() return f.tagsize + protowire.SizeVarint(uint64(v)) } // appendInt32Ptr wire encodes a *int32 pointer as a Int32. // It panics if the pointer is nil. func appendInt32Ptr(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := **p.Int32Ptr() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(v)) return b, nil } // consumeInt32Ptr wire decodes a *int32 pointer as a Int32. func consumeInt32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } vp := p.Int32Ptr() if *vp == nil { *vp = new(int32) } **vp = int32(v) out.n = n return out, nil } var coderInt32Ptr = pointerCoderFuncs{ size: sizeInt32Ptr, marshal: appendInt32Ptr, unmarshal: consumeInt32Ptr, merge: mergeInt32Ptr, } // sizeInt32Slice returns the size of wire encoding a []int32 pointer as a repeated Int32. func sizeInt32Slice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := *p.Int32Slice() for _, v := range s { size += f.tagsize + protowire.SizeVarint(uint64(v)) } return size } // appendInt32Slice encodes a []int32 pointer as a repeated Int32. func appendInt32Slice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := *p.Int32Slice() for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(v)) } return b, nil } // consumeInt32Slice wire decodes a []int32 pointer as a repeated Int32. func consumeInt32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { sp := p.Int32Slice() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } count := 0 for _, v := range b { if v < 0x80 { count++ } } if count > 0 { p.growInt32Slice(count) } s := *sp for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } s = append(s, int32(v)) b = b[n:] } *sp = s out.n = n return out, nil } if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } *sp = append(*sp, int32(v)) out.n = n return out, nil } var coderInt32Slice = pointerCoderFuncs{ size: sizeInt32Slice, marshal: appendInt32Slice, unmarshal: consumeInt32Slice, merge: mergeInt32Slice, } // sizeInt32PackedSlice returns the size of wire encoding a []int32 pointer as a packed repeated Int32. func sizeInt32PackedSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := *p.Int32Slice() if len(s) == 0 { return 0 } n := 0 for _, v := range s { n += protowire.SizeVarint(uint64(v)) } return f.tagsize + protowire.SizeBytes(n) } // appendInt32PackedSlice encodes a []int32 pointer as a packed repeated Int32. func appendInt32PackedSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := *p.Int32Slice() if len(s) == 0 { return b, nil } b = protowire.AppendVarint(b, f.wiretag) n := 0 for _, v := range s { n += protowire.SizeVarint(uint64(v)) } b = protowire.AppendVarint(b, uint64(n)) for _, v := range s { b = protowire.AppendVarint(b, uint64(v)) } return b, nil } var coderInt32PackedSlice = pointerCoderFuncs{ size: sizeInt32PackedSlice, marshal: appendInt32PackedSlice, unmarshal: consumeInt32Slice, merge: mergeInt32Slice, } // sizeInt32Value returns the size of wire encoding a int32 value as a Int32. func sizeInt32Value(v protoreflect.Value, tagsize int, opts marshalOptions) int { return tagsize + protowire.SizeVarint(uint64(int32(v.Int()))) } // appendInt32Value encodes a int32 value as a Int32. func appendInt32Value(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(int32(v.Int()))) return b, nil } // consumeInt32Value decodes a int32 value as a Int32. func consumeInt32Value(b []byte, _ protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } out.n = n return protoreflect.ValueOfInt32(int32(v)), out, nil } var coderInt32Value = valueCoderFuncs{ size: sizeInt32Value, marshal: appendInt32Value, unmarshal: consumeInt32Value, merge: mergeScalarValue, } // sizeInt32SliceValue returns the size of wire encoding a []int32 value as a repeated Int32. func sizeInt32SliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) size += tagsize + protowire.SizeVarint(uint64(int32(v.Int()))) } return size } // appendInt32SliceValue encodes a []int32 value as a repeated Int32. func appendInt32SliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(int32(v.Int()))) } return b, nil } // consumeInt32SliceValue wire decodes a []int32 value as a repeated Int32. func consumeInt32SliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, errDecode } for len(b) > 0 { var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) b = b[n:] } out.n = n return listv, out, nil } if wtyp != protowire.VarintType { return protoreflect.Value{}, out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return protoreflect.Value{}, out, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) out.n = n return listv, out, nil } var coderInt32SliceValue = valueCoderFuncs{ size: sizeInt32SliceValue, marshal: appendInt32SliceValue, unmarshal: consumeInt32SliceValue, merge: mergeListValue, } // sizeInt32PackedSliceValue returns the size of wire encoding a []int32 value as a packed repeated Int32. func sizeInt32PackedSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) (size int) { list := listv.List() llen := list.Len() if llen == 0 { return 0 } n := 0 for i, llen := 0, llen; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(uint64(int32(v.Int()))) } return tagsize + protowire.SizeBytes(n) } // appendInt32PackedSliceValue encodes a []int32 value as a packed repeated Int32. func appendInt32PackedSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() llen := list.Len() if llen == 0 { return b, nil } b = protowire.AppendVarint(b, wiretag) n := 0 for i := 0; i < llen; i++ { v := list.Get(i) n += protowire.SizeVarint(uint64(int32(v.Int()))) } b = protowire.AppendVarint(b, uint64(n)) for i := 0; i < llen; i++ { v := list.Get(i) b = protowire.AppendVarint(b, uint64(int32(v.Int()))) } return b, nil } var coderInt32PackedSliceValue = valueCoderFuncs{ size: sizeInt32PackedSliceValue, marshal: appendInt32PackedSliceValue, unmarshal: consumeInt32SliceValue, merge: mergeListValue, } // sizeSint32 returns the size of wire encoding a int32 pointer as a Sint32. func sizeSint32(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Int32() return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) } // appendSint32 wire encodes a int32 pointer as a Sint32. func appendSint32(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Int32() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) return b, nil } // consumeSint32 wire decodes a int32 pointer as a Sint32. func consumeSint32(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } *p.Int32() = int32(protowire.DecodeZigZag(v & math.MaxUint32)) out.n = n return out, nil } var coderSint32 = pointerCoderFuncs{ size: sizeSint32, marshal: appendSint32, unmarshal: consumeSint32, merge: mergeInt32, } // sizeSint32NoZero returns the size of wire encoding a int32 pointer as a Sint32. // The zero value is not encoded. func sizeSint32NoZero(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := *p.Int32() if v == 0 { return 0 } return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) } // appendSint32NoZero wire encodes a int32 pointer as a Sint32. // The zero value is not encoded. func appendSint32NoZero(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := *p.Int32() if v == 0 { return b, nil } b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) return b, nil } var coderSint32NoZero = pointerCoderFuncs{ size: sizeSint32NoZero, marshal: appendSint32NoZero, unmarshal: consumeSint32, merge: mergeInt32NoZero, } // sizeSint32Ptr returns the size of wire encoding a *int32 pointer as a Sint32. // It panics if the pointer is nil. func sizeSint32Ptr(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { v := **p.Int32Ptr() return f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) } // appendSint32Ptr wire encodes a *int32 pointer as a Sint32. // It panics if the pointer is nil. func appendSint32Ptr(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { v := **p.Int32Ptr() b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) return b, nil } // consumeSint32Ptr wire decodes a *int32 pointer as a Sint32. func consumeSint32Ptr(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.VarintType { return out, errUnknown } var v uint64 var n int if len(b) >= 1 && b[0] < 0x80 { v = uint64(b[0]) n = 1 } else if len(b) >= 2 && b[1] < 128 { v = uint64(b[0]&0x7f) + uint64(b[1])<<7 n = 2 } else { v, n = protowire.ConsumeVarint(b) } if n < 0 { return out, errDecode } vp := p.Int32Ptr() if *vp == nil { *vp = new(int32) } **vp = int32(protowire.DecodeZigZag(v & math.MaxUint32)) out.n = n return out, nil } var coderSint32Ptr = pointerCoderFuncs{ size: sizeSint32Ptr, marshal: appendSint32Ptr, unmarshal: consumeSint32Ptr, merge: mergeInt32Ptr, } // sizeSint32Slice returns the size of wire encoding a []int32 pointer as a repeated Sint32. func sizeSint32Slice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := *p.Int32Slice() for _, v := range s { size += f.tagsize + protowire.SizeVarint(protowire.EncodeZigZag(int64(v))) } return size } // appendSint32Slice encodes a []int32 pointer as a repeated Sint32. func appendSint32Slice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := *p.Int32Slice() for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(v))) } return b, nil } // consumeSint32Slice wire decodes a []int32 pointer as a repeated Sint32. func consumeSint32Slice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { sp := p.Int32Slice() if wtyp == protowire.BytesType { b, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } count := 0 for _, v := range b { if v < 0x80 { count++ } } if count > 0 { p.growInt32Slice(count) } s := *sp for len(b) > 0 { var v uint64 var n int
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/pointer_unsafe.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "sync/atomic" "unsafe" "google.golang.org/protobuf/internal/protolazy" ) const UnsafeEnabled = true // Pointer is an opaque pointer type. type Pointer unsafe.Pointer // offset represents the offset to a struct field, accessible from a pointer. // The offset is the byte offset to the field from the start of the struct. type offset uintptr // offsetOf returns a field offset for the struct field. func offsetOf(f reflect.StructField) offset { return offset(f.Offset) } // IsValid reports whether the offset is valid. func (f offset) IsValid() bool { return f != invalidOffset } // invalidOffset is an invalid field offset. var invalidOffset = ^offset(0) // zeroOffset is a noop when calling pointer.Apply. var zeroOffset = offset(0) // pointer is a pointer to a message struct or field. type pointer struct{ p unsafe.Pointer } // pointerOf returns p as a pointer. func pointerOf(p Pointer) pointer { return pointer{p: unsafe.Pointer(p)} } // pointerOfValue returns v as a pointer. func pointerOfValue(v reflect.Value) pointer { return pointer{p: unsafe.Pointer(v.Pointer())} } // pointerOfIface returns the pointer portion of an interface. func pointerOfIface(v any) pointer { type ifaceHeader struct { Type unsafe.Pointer Data unsafe.Pointer } return pointer{p: (*ifaceHeader)(unsafe.Pointer(&v)).Data} } // IsNil reports whether the pointer is nil. func (p pointer) IsNil() bool { return p.p == nil } // Apply adds an offset to the pointer to derive a new pointer // to a specified field. The pointer must be valid and pointing at a struct. func (p pointer) Apply(f offset) pointer { if p.IsNil() { panic("invalid nil pointer") } return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))} } // AsValueOf treats p as a pointer to an object of type t and returns the value. // It is equivalent to reflect.ValueOf(p.AsIfaceOf(t)) func (p pointer) AsValueOf(t reflect.Type) reflect.Value { return reflect.NewAt(t, p.p) } // AsIfaceOf treats p as a pointer to an object of type t and returns the value. // It is equivalent to p.AsValueOf(t).Interface() func (p pointer) AsIfaceOf(t reflect.Type) any { // TODO: Use tricky unsafe magic to directly create ifaceHeader. return p.AsValueOf(t).Interface() } func (p pointer) Bool() *bool { return (*bool)(p.p) } func (p pointer) BoolPtr() **bool { return (**bool)(p.p) } func (p pointer) BoolSlice() *[]bool { return (*[]bool)(p.p) } func (p pointer) Int32() *int32 { return (*int32)(p.p) } func (p pointer) Int32Ptr() **int32 { return (**int32)(p.p) } func (p pointer) Int32Slice() *[]int32 { return (*[]int32)(p.p) } func (p pointer) Int64() *int64 { return (*int64)(p.p) } func (p pointer) Int64Ptr() **int64 { return (**int64)(p.p) } func (p pointer) Int64Slice() *[]int64 { return (*[]int64)(p.p) } func (p pointer) Uint32() *uint32 { return (*uint32)(p.p) } func (p pointer) Uint32Ptr() **uint32 { return (**uint32)(p.p) } func (p pointer) Uint32Slice() *[]uint32 { return (*[]uint32)(p.p) } func (p pointer) Uint64() *uint64 { return (*uint64)(p.p) } func (p pointer) Uint64Ptr() **uint64 { return (**uint64)(p.p) } func (p pointer) Uint64Slice() *[]uint64 { return (*[]uint64)(p.p) } func (p pointer) Float32() *float32 { return (*float32)(p.p) } func (p pointer) Float32Ptr() **float32 { return (**float32)(p.p) } func (p pointer) Float32Slice() *[]float32 { return (*[]float32)(p.p) } func (p pointer) Float64() *float64 { return (*float64)(p.p) } func (p pointer) Float64Ptr() **float64 { return (**float64)(p.p) } func (p pointer) Float64Slice() *[]float64 { return (*[]float64)(p.p) } func (p pointer) String() *string { return (*string)(p.p) } func (p pointer) StringPtr() **string { return (**string)(p.p) } func (p pointer) StringSlice() *[]string { return (*[]string)(p.p) } func (p pointer) Bytes() *[]byte { return (*[]byte)(p.p) } func (p pointer) BytesPtr() **[]byte { return (**[]byte)(p.p) } func (p pointer) BytesSlice() *[][]byte { return (*[][]byte)(p.p) } func (p pointer) Extensions() *map[int32]ExtensionField { return (*map[int32]ExtensionField)(p.p) } func (p pointer) LazyInfoPtr() **protolazy.XXX_lazyUnmarshalInfo { return (**protolazy.XXX_lazyUnmarshalInfo)(p.p) } func (p pointer) PresenceInfo() presence { return presence{P: p.p} } func (p pointer) Elem() pointer { return pointer{p: *(*unsafe.Pointer)(p.p)} } // PointerSlice loads []*T from p as a []pointer. // The value returned is aliased with the original slice. // This behavior differs from the implementation in pointer_reflect.go. func (p pointer) PointerSlice() []pointer { // Super-tricky - p should point to a []*T where T is a // message type. We load it as []pointer. return *(*[]pointer)(p.p) } // AppendPointerSlice appends v to p, which must be a []*T. func (p pointer) AppendPointerSlice(v pointer) { *(*[]pointer)(p.p) = append(*(*[]pointer)(p.p), v) } // SetPointer sets *p to v. func (p pointer) SetPointer(v pointer) { *(*unsafe.Pointer)(p.p) = (unsafe.Pointer)(v.p) } func (p pointer) growBoolSlice(addCap int) { sp := p.BoolSlice() s := make([]bool, 0, addCap+len(*sp)) s = s[:len(*sp)] copy(s, *sp) *sp = s } func (p pointer) growInt32Slice(addCap int) { sp := p.Int32Slice() s := make([]int32, 0, addCap+len(*sp)) s = s[:len(*sp)] copy(s, *sp) *sp = s } func (p pointer) growUint32Slice(addCap int) { p.growInt32Slice(addCap) } func (p pointer) growFloat32Slice(addCap int) { p.growInt32Slice(addCap) } func (p pointer) growInt64Slice(addCap int) { sp := p.Int64Slice() s := make([]int64, 0, addCap+len(*sp)) s = s[:len(*sp)] copy(s, *sp) *sp = s } func (p pointer) growUint64Slice(addCap int) { p.growInt64Slice(addCap) } func (p pointer) growFloat64Slice(addCap int) { p.growInt64Slice(addCap) } // Static check that MessageState does not exceed the size of a pointer. const _ = uint(unsafe.Sizeof(unsafe.Pointer(nil)) - unsafe.Sizeof(MessageState{})) func (Export) MessageStateOf(p Pointer) *messageState { // Super-tricky - see documentation on MessageState. return (*messageState)(unsafe.Pointer(p)) } func (ms *messageState) pointer() pointer { // Super-tricky - see documentation on MessageState. return pointer{p: unsafe.Pointer(ms)} } func (ms *messageState) messageInfo() *MessageInfo { mi := ms.LoadMessageInfo() if mi == nil { panic("invalid nil message info; this suggests memory corruption due to a race or shallow copy on the message struct") } return mi } func (ms *messageState) LoadMessageInfo() *MessageInfo { return (*MessageInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)))) } func (ms *messageState) StoreMessageInfo(mi *MessageInfo) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(&ms.atomicMessageInfo)), unsafe.Pointer(mi)) } type atomicNilMessage struct{ p unsafe.Pointer } // p is a *messageReflectWrapper func (m *atomicNilMessage) Init(mi *MessageInfo) *messageReflectWrapper { if p := atomic.LoadPointer(&m.p); p != nil { return (*messageReflectWrapper)(p) } w := &messageReflectWrapper{mi: mi} atomic.CompareAndSwapPointer(&m.p, nil, (unsafe.Pointer)(w)) return (*messageReflectWrapper)(atomic.LoadPointer(&m.p)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) // unwrapper unwraps the value to the underlying value. // This is implemented by List and Map. type unwrapper interface { protoUnwrap() any } // A Converter coverts to/from Go reflect.Value types and protobuf protoreflect.Value types. type Converter interface { // PBValueOf converts a reflect.Value to a protoreflect.Value. PBValueOf(reflect.Value) protoreflect.Value // GoValueOf converts a protoreflect.Value to a reflect.Value. GoValueOf(protoreflect.Value) reflect.Value // IsValidPB returns whether a protoreflect.Value is compatible with this type. IsValidPB(protoreflect.Value) bool // IsValidGo returns whether a reflect.Value is compatible with this type. IsValidGo(reflect.Value) bool // New returns a new field value. // For scalars, it returns the default value of the field. // For composite types, it returns a new mutable value. New() protoreflect.Value // Zero returns a new field value. // For scalars, it returns the default value of the field. // For composite types, it returns an immutable, empty value. Zero() protoreflect.Value } // NewConverter matches a Go type with a protobuf field and returns a Converter // that converts between the two. Enums must be a named int32 kind that // implements protoreflect.Enum, and messages must be pointer to a named // struct type that implements protoreflect.ProtoMessage. // // This matcher deliberately supports a wider range of Go types than what // protoc-gen-go historically generated to be able to automatically wrap some // v1 messages generated by other forks of protoc-gen-go. func NewConverter(t reflect.Type, fd protoreflect.FieldDescriptor) Converter { switch { case fd.IsList(): return newListConverter(t, fd) case fd.IsMap(): return newMapConverter(t, fd) default: return newSingularConverter(t, fd) } } var ( boolType = reflect.TypeOf(bool(false)) int32Type = reflect.TypeOf(int32(0)) int64Type = reflect.TypeOf(int64(0)) uint32Type = reflect.TypeOf(uint32(0)) uint64Type = reflect.TypeOf(uint64(0)) float32Type = reflect.TypeOf(float32(0)) float64Type = reflect.TypeOf(float64(0)) stringType = reflect.TypeOf(string("")) bytesType = reflect.TypeOf([]byte(nil)) byteType = reflect.TypeOf(byte(0)) ) var ( boolZero = protoreflect.ValueOfBool(false) int32Zero = protoreflect.ValueOfInt32(0) int64Zero = protoreflect.ValueOfInt64(0) uint32Zero = protoreflect.ValueOfUint32(0) uint64Zero = protoreflect.ValueOfUint64(0) float32Zero = protoreflect.ValueOfFloat32(0) float64Zero = protoreflect.ValueOfFloat64(0) stringZero = protoreflect.ValueOfString("") bytesZero = protoreflect.ValueOfBytes(nil) ) func newSingularConverter(t reflect.Type, fd protoreflect.FieldDescriptor) Converter { defVal := func(fd protoreflect.FieldDescriptor, zero protoreflect.Value) protoreflect.Value { if fd.Cardinality() == protoreflect.Repeated { // Default isn't defined for repeated fields. return zero } return fd.Default() } switch fd.Kind() { case protoreflect.BoolKind: if t.Kind() == reflect.Bool { return &boolConverter{t, defVal(fd, boolZero)} } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if t.Kind() == reflect.Int32 { return &int32Converter{t, defVal(fd, int32Zero)} } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if t.Kind() == reflect.Int64 { return &int64Converter{t, defVal(fd, int64Zero)} } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if t.Kind() == reflect.Uint32 { return &uint32Converter{t, defVal(fd, uint32Zero)} } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if t.Kind() == reflect.Uint64 { return &uint64Converter{t, defVal(fd, uint64Zero)} } case protoreflect.FloatKind: if t.Kind() == reflect.Float32 { return &float32Converter{t, defVal(fd, float32Zero)} } case protoreflect.DoubleKind: if t.Kind() == reflect.Float64 { return &float64Converter{t, defVal(fd, float64Zero)} } case protoreflect.StringKind: if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) { return &stringConverter{t, defVal(fd, stringZero)} } case protoreflect.BytesKind: if t.Kind() == reflect.String || (t.Kind() == reflect.Slice && t.Elem() == byteType) { return &bytesConverter{t, defVal(fd, bytesZero)} } case protoreflect.EnumKind: // Handle enums, which must be a named int32 type. if t.Kind() == reflect.Int32 { return newEnumConverter(t, fd) } case protoreflect.MessageKind, protoreflect.GroupKind: return newMessageConverter(t) } panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) } type boolConverter struct { goType reflect.Type def protoreflect.Value } func (c *boolConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfBool(v.Bool()) } func (c *boolConverter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(v.Bool()).Convert(c.goType) } func (c *boolConverter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(bool) return ok } func (c *boolConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *boolConverter) New() protoreflect.Value { return c.def } func (c *boolConverter) Zero() protoreflect.Value { return c.def } type int32Converter struct { goType reflect.Type def protoreflect.Value } func (c *int32Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfInt32(int32(v.Int())) } func (c *int32Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(int32(v.Int())).Convert(c.goType) } func (c *int32Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(int32) return ok } func (c *int32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *int32Converter) New() protoreflect.Value { return c.def } func (c *int32Converter) Zero() protoreflect.Value { return c.def } type int64Converter struct { goType reflect.Type def protoreflect.Value } func (c *int64Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfInt64(int64(v.Int())) } func (c *int64Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(int64(v.Int())).Convert(c.goType) } func (c *int64Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(int64) return ok } func (c *int64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *int64Converter) New() protoreflect.Value { return c.def } func (c *int64Converter) Zero() protoreflect.Value { return c.def } type uint32Converter struct { goType reflect.Type def protoreflect.Value } func (c *uint32Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfUint32(uint32(v.Uint())) } func (c *uint32Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(uint32(v.Uint())).Convert(c.goType) } func (c *uint32Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(uint32) return ok } func (c *uint32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *uint32Converter) New() protoreflect.Value { return c.def } func (c *uint32Converter) Zero() protoreflect.Value { return c.def } type uint64Converter struct { goType reflect.Type def protoreflect.Value } func (c *uint64Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfUint64(uint64(v.Uint())) } func (c *uint64Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(uint64(v.Uint())).Convert(c.goType) } func (c *uint64Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(uint64) return ok } func (c *uint64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *uint64Converter) New() protoreflect.Value { return c.def } func (c *uint64Converter) Zero() protoreflect.Value { return c.def } type float32Converter struct { goType reflect.Type def protoreflect.Value } func (c *float32Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfFloat32(float32(v.Float())) } func (c *float32Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(float32(v.Float())).Convert(c.goType) } func (c *float32Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(float32) return ok } func (c *float32Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *float32Converter) New() protoreflect.Value { return c.def } func (c *float32Converter) Zero() protoreflect.Value { return c.def } type float64Converter struct { goType reflect.Type def protoreflect.Value } func (c *float64Converter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfFloat64(float64(v.Float())) } func (c *float64Converter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(float64(v.Float())).Convert(c.goType) } func (c *float64Converter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(float64) return ok } func (c *float64Converter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *float64Converter) New() protoreflect.Value { return c.def } func (c *float64Converter) Zero() protoreflect.Value { return c.def } type stringConverter struct { goType reflect.Type def protoreflect.Value } func (c *stringConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfString(v.Convert(stringType).String()) } func (c *stringConverter) GoValueOf(v protoreflect.Value) reflect.Value { // protoreflect.Value.String never panics, so we go through an interface // conversion here to check the type. s := v.Interface().(string) if c.goType.Kind() == reflect.Slice && s == "" { return reflect.Zero(c.goType) // ensure empty string is []byte(nil) } return reflect.ValueOf(s).Convert(c.goType) } func (c *stringConverter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(string) return ok } func (c *stringConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *stringConverter) New() protoreflect.Value { return c.def } func (c *stringConverter) Zero() protoreflect.Value { return c.def } type bytesConverter struct { goType reflect.Type def protoreflect.Value } func (c *bytesConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } if c.goType.Kind() == reflect.String && v.Len() == 0 { return protoreflect.ValueOfBytes(nil) // ensure empty string is []byte(nil) } return protoreflect.ValueOfBytes(v.Convert(bytesType).Bytes()) } func (c *bytesConverter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(v.Bytes()).Convert(c.goType) } func (c *bytesConverter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().([]byte) return ok } func (c *bytesConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *bytesConverter) New() protoreflect.Value { return c.def } func (c *bytesConverter) Zero() protoreflect.Value { return c.def } type enumConverter struct { goType reflect.Type def protoreflect.Value } func newEnumConverter(goType reflect.Type, fd protoreflect.FieldDescriptor) Converter { var def protoreflect.Value if fd.Cardinality() == protoreflect.Repeated { def = protoreflect.ValueOfEnum(fd.Enum().Values().Get(0).Number()) } else { def = fd.Default() } return &enumConverter{goType, def} } func (c *enumConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v.Int())) } func (c *enumConverter) GoValueOf(v protoreflect.Value) reflect.Value { return reflect.ValueOf(v.Enum()).Convert(c.goType) } func (c *enumConverter) IsValidPB(v protoreflect.Value) bool { _, ok := v.Interface().(protoreflect.EnumNumber) return ok } func (c *enumConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *enumConverter) New() protoreflect.Value { return c.def } func (c *enumConverter) Zero() protoreflect.Value { return c.def } type messageConverter struct { goType reflect.Type } func newMessageConverter(goType reflect.Type) Converter { return &messageConverter{goType} } func (c *messageConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } if c.isNonPointer() { if v.CanAddr() { v = v.Addr() // T => *T } else { v = reflect.Zero(reflect.PtrTo(v.Type())) } } if m, ok := v.Interface().(protoreflect.ProtoMessage); ok { return protoreflect.ValueOfMessage(m.ProtoReflect()) } return protoreflect.ValueOfMessage(legacyWrapMessage(v)) } func (c *messageConverter) GoValueOf(v protoreflect.Value) reflect.Value { m := v.Message() var rv reflect.Value if u, ok := m.(unwrapper); ok { rv = reflect.ValueOf(u.protoUnwrap()) } else { rv = reflect.ValueOf(m.Interface()) } if c.isNonPointer() { if rv.Type() != reflect.PtrTo(c.goType) { panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), reflect.PtrTo(c.goType))) } if !rv.IsNil() { rv = rv.Elem() // *T => T } else { rv = reflect.Zero(rv.Type().Elem()) } } if rv.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", rv.Type(), c.goType)) } return rv } func (c *messageConverter) IsValidPB(v protoreflect.Value) bool { m := v.Message() var rv reflect.Value if u, ok := m.(unwrapper); ok { rv = reflect.ValueOf(u.protoUnwrap()) } else { rv = reflect.ValueOf(m.Interface()) } if c.isNonPointer() { return rv.Type() == reflect.PtrTo(c.goType) } return rv.Type() == c.goType } func (c *messageConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *messageConverter) New() protoreflect.Value { if c.isNonPointer() { return c.PBValueOf(reflect.New(c.goType).Elem()) } return c.PBValueOf(reflect.New(c.goType.Elem())) } func (c *messageConverter) Zero() protoreflect.Value { return c.PBValueOf(reflect.Zero(c.goType)) } // isNonPointer reports whether the type is a non-pointer type. // This never occurs for generated message types. func (c *messageConverter) isNonPointer() bool { return c.goType.Kind() != reflect.Ptr }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_message_opaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_message_opaque.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "sort" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/reflect/protoreflect" piface "google.golang.org/protobuf/runtime/protoiface" ) func (mi *MessageInfo) makeOpaqueCoderMethods(t reflect.Type, si opaqueStructInfo) { mi.sizecacheOffset = si.sizecacheOffset mi.unknownOffset = si.unknownOffset mi.unknownPtrKind = si.unknownType.Kind() == reflect.Ptr mi.extensionOffset = si.extensionOffset mi.lazyOffset = si.lazyOffset mi.presenceOffset = si.presenceOffset mi.coderFields = make(map[protowire.Number]*coderFieldInfo) fields := mi.Desc.Fields() for i := 0; i < fields.Len(); i++ { fd := fields.Get(i) fs := si.fieldsByNumber[fd.Number()] if fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic() { fs = si.oneofsByName[fd.ContainingOneof().Name()] } ft := fs.Type var wiretag uint64 if !fd.IsPacked() { wiretag = protowire.EncodeTag(fd.Number(), wireTypes[fd.Kind()]) } else { wiretag = protowire.EncodeTag(fd.Number(), protowire.BytesType) } var fieldOffset offset var funcs pointerCoderFuncs var childMessage *MessageInfo switch { case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): fieldOffset = offsetOf(fs) case fd.Message() != nil && !fd.IsMap(): fieldOffset = offsetOf(fs) if fd.IsList() { childMessage, funcs = makeOpaqueRepeatedMessageFieldCoder(fd, ft) } else { childMessage, funcs = makeOpaqueMessageFieldCoder(fd, ft) } default: fieldOffset = offsetOf(fs) childMessage, funcs = fieldCoder(fd, ft) } cf := &coderFieldInfo{ num: fd.Number(), offset: fieldOffset, wiretag: wiretag, ft: ft, tagsize: protowire.SizeVarint(wiretag), funcs: funcs, mi: childMessage, validation: newFieldValidationInfo(mi, si.structInfo, fd, ft), isPointer: (fd.Cardinality() == protoreflect.Repeated || fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind), isRequired: fd.Cardinality() == protoreflect.Required, presenceIndex: noPresence, } // TODO: Use presence for all fields. // // In some cases, such as maps, presence means only "might be set" rather // than "is definitely set", but every field should have a presence bit to // permit us to skip over definitely-unset fields at marshal time. var hasPresence bool hasPresence, cf.isLazy = filedesc.UsePresenceForField(fd) if hasPresence { cf.presenceIndex, mi.presenceSize = presenceIndex(mi.Desc, fd) } mi.orderedCoderFields = append(mi.orderedCoderFields, cf) mi.coderFields[cf.num] = cf } for i, oneofs := 0, mi.Desc.Oneofs(); i < oneofs.Len(); i++ { if od := oneofs.Get(i); !od.IsSynthetic() { mi.initOneofFieldCoders(od, si.structInfo) } } if messageset.IsMessageSet(mi.Desc) { if !mi.extensionOffset.IsValid() { panic(fmt.Sprintf("%v: MessageSet with no extensions field", mi.Desc.FullName())) } if !mi.unknownOffset.IsValid() { panic(fmt.Sprintf("%v: MessageSet with no unknown field", mi.Desc.FullName())) } mi.isMessageSet = true } sort.Slice(mi.orderedCoderFields, func(i, j int) bool { return mi.orderedCoderFields[i].num < mi.orderedCoderFields[j].num }) var maxDense protoreflect.FieldNumber for _, cf := range mi.orderedCoderFields { if cf.num >= 16 && cf.num >= 2*maxDense { break } maxDense = cf.num } mi.denseCoderFields = make([]*coderFieldInfo, maxDense+1) for _, cf := range mi.orderedCoderFields { if int(cf.num) > len(mi.denseCoderFields) { break } mi.denseCoderFields[cf.num] = cf } // To preserve compatibility with historic wire output, marshal oneofs last. if mi.Desc.Oneofs().Len() > 0 { sort.Slice(mi.orderedCoderFields, func(i, j int) bool { fi := fields.ByNumber(mi.orderedCoderFields[i].num) fj := fields.ByNumber(mi.orderedCoderFields[j].num) return order.LegacyFieldOrder(fi, fj) }) } mi.needsInitCheck = needsInitCheck(mi.Desc) if mi.methods.Marshal == nil && mi.methods.Size == nil { mi.methods.Flags |= piface.SupportMarshalDeterministic mi.methods.Marshal = mi.marshal mi.methods.Size = mi.size } if mi.methods.Unmarshal == nil { mi.methods.Flags |= piface.SupportUnmarshalDiscardUnknown mi.methods.Unmarshal = mi.unmarshal } if mi.methods.CheckInitialized == nil { mi.methods.CheckInitialized = mi.checkInitialized } if mi.methods.Merge == nil { mi.methods.Merge = mi.merge } if mi.methods.Equal == nil { mi.methods.Equal = equal } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/merge_gen.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package impl import () func mergeBool(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Bool() = *src.Bool() } func mergeBoolNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Bool() if v != false { *dst.Bool() = v } } func mergeBoolPtr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.BoolPtr() if p != nil { v := *p *dst.BoolPtr() = &v } } func mergeBoolSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.BoolSlice() ss := src.BoolSlice() *ds = append(*ds, *ss...) } func mergeInt32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Int32() = *src.Int32() } func mergeInt32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Int32() if v != 0 { *dst.Int32() = v } } func mergeInt32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Int32Ptr() if p != nil { v := *p *dst.Int32Ptr() = &v } } func mergeInt32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Int32Slice() ss := src.Int32Slice() *ds = append(*ds, *ss...) } func mergeUint32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Uint32() = *src.Uint32() } func mergeUint32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Uint32() if v != 0 { *dst.Uint32() = v } } func mergeUint32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Uint32Ptr() if p != nil { v := *p *dst.Uint32Ptr() = &v } } func mergeUint32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Uint32Slice() ss := src.Uint32Slice() *ds = append(*ds, *ss...) } func mergeInt64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Int64() = *src.Int64() } func mergeInt64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Int64() if v != 0 { *dst.Int64() = v } } func mergeInt64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Int64Ptr() if p != nil { v := *p *dst.Int64Ptr() = &v } } func mergeInt64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Int64Slice() ss := src.Int64Slice() *ds = append(*ds, *ss...) } func mergeUint64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Uint64() = *src.Uint64() } func mergeUint64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Uint64() if v != 0 { *dst.Uint64() = v } } func mergeUint64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Uint64Ptr() if p != nil { v := *p *dst.Uint64Ptr() = &v } } func mergeUint64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Uint64Slice() ss := src.Uint64Slice() *ds = append(*ds, *ss...) } func mergeFloat32(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Float32() = *src.Float32() } func mergeFloat32NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Float32() if v != 0 { *dst.Float32() = v } } func mergeFloat32Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Float32Ptr() if p != nil { v := *p *dst.Float32Ptr() = &v } } func mergeFloat32Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Float32Slice() ss := src.Float32Slice() *ds = append(*ds, *ss...) } func mergeFloat64(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.Float64() = *src.Float64() } func mergeFloat64NoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.Float64() if v != 0 { *dst.Float64() = v } } func mergeFloat64Ptr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.Float64Ptr() if p != nil { v := *p *dst.Float64Ptr() = &v } } func mergeFloat64Slice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.Float64Slice() ss := src.Float64Slice() *ds = append(*ds, *ss...) } func mergeString(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { *dst.String() = *src.String() } func mergeStringNoZero(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { v := *src.String() if v != "" { *dst.String() = v } } func mergeStringPtr(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { p := *src.StringPtr() if p != nil { v := *p *dst.StringPtr() = &v } } func mergeStringSlice(dst, src pointer, _ *coderFieldInfo, _ mergeOptions) { ds := dst.StringSlice() ss := src.StringSlice() *ds = append(*ds, *ss...) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_tables.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_tables.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // pointerCoderFuncs is a set of pointer encoding functions. type pointerCoderFuncs struct { mi *MessageInfo size func(p pointer, f *coderFieldInfo, opts marshalOptions) int marshal func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) unmarshal func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) isInit func(p pointer, f *coderFieldInfo) error merge func(dst, src pointer, f *coderFieldInfo, opts mergeOptions) } // valueCoderFuncs is a set of protoreflect.Value encoding functions. type valueCoderFuncs struct { size func(v protoreflect.Value, tagsize int, opts marshalOptions) int marshal func(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) unmarshal func(b []byte, v protoreflect.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (protoreflect.Value, unmarshalOutput, error) isInit func(v protoreflect.Value) error merge func(dst, src protoreflect.Value, opts mergeOptions) protoreflect.Value } // fieldCoder returns pointer functions for a field, used for operating on // struct fields. func fieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) (*MessageInfo, pointerCoderFuncs) { switch { case fd.IsMap(): return encoderFuncsForMap(fd, ft) case fd.Cardinality() == protoreflect.Repeated && !fd.IsPacked(): // Repeated fields (not packed). if ft.Kind() != reflect.Slice { break } ft := ft.Elem() switch fd.Kind() { case protoreflect.BoolKind: if ft.Kind() == reflect.Bool { return nil, coderBoolSlice } case protoreflect.EnumKind: if ft.Kind() == reflect.Int32 { return nil, coderEnumSlice } case protoreflect.Int32Kind: if ft.Kind() == reflect.Int32 { return nil, coderInt32Slice } case protoreflect.Sint32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSint32Slice } case protoreflect.Uint32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderUint32Slice } case protoreflect.Int64Kind: if ft.Kind() == reflect.Int64 { return nil, coderInt64Slice } case protoreflect.Sint64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSint64Slice } case protoreflect.Uint64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderUint64Slice } case protoreflect.Sfixed32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSfixed32Slice } case protoreflect.Fixed32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderFixed32Slice } case protoreflect.FloatKind: if ft.Kind() == reflect.Float32 { return nil, coderFloatSlice } case protoreflect.Sfixed64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSfixed64Slice } case protoreflect.Fixed64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderFixed64Slice } case protoreflect.DoubleKind: if ft.Kind() == reflect.Float64 { return nil, coderDoubleSlice } case protoreflect.StringKind: if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { return nil, coderStringSliceValidateUTF8 } if ft.Kind() == reflect.String { return nil, coderStringSlice } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { return nil, coderBytesSliceValidateUTF8 } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytesSlice } case protoreflect.BytesKind: if ft.Kind() == reflect.String { return nil, coderStringSlice } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytesSlice } case protoreflect.MessageKind: return getMessageInfo(ft), makeMessageSliceFieldCoder(fd, ft) case protoreflect.GroupKind: return getMessageInfo(ft), makeGroupSliceFieldCoder(fd, ft) } case fd.Cardinality() == protoreflect.Repeated && fd.IsPacked(): // Packed repeated fields. // // Only repeated fields of primitive numeric types // (Varint, Fixed32, or Fixed64 wire type) can be packed. if ft.Kind() != reflect.Slice { break } ft := ft.Elem() switch fd.Kind() { case protoreflect.BoolKind: if ft.Kind() == reflect.Bool { return nil, coderBoolPackedSlice } case protoreflect.EnumKind: if ft.Kind() == reflect.Int32 { return nil, coderEnumPackedSlice } case protoreflect.Int32Kind: if ft.Kind() == reflect.Int32 { return nil, coderInt32PackedSlice } case protoreflect.Sint32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSint32PackedSlice } case protoreflect.Uint32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderUint32PackedSlice } case protoreflect.Int64Kind: if ft.Kind() == reflect.Int64 { return nil, coderInt64PackedSlice } case protoreflect.Sint64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSint64PackedSlice } case protoreflect.Uint64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderUint64PackedSlice } case protoreflect.Sfixed32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSfixed32PackedSlice } case protoreflect.Fixed32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderFixed32PackedSlice } case protoreflect.FloatKind: if ft.Kind() == reflect.Float32 { return nil, coderFloatPackedSlice } case protoreflect.Sfixed64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSfixed64PackedSlice } case protoreflect.Fixed64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderFixed64PackedSlice } case protoreflect.DoubleKind: if ft.Kind() == reflect.Float64 { return nil, coderDoublePackedSlice } } case fd.Kind() == protoreflect.MessageKind: return getMessageInfo(ft), makeMessageFieldCoder(fd, ft) case fd.Kind() == protoreflect.GroupKind: return getMessageInfo(ft), makeGroupFieldCoder(fd, ft) case !fd.HasPresence() && fd.ContainingOneof() == nil: // Populated oneof fields always encode even if set to the zero value, // which normally are not encoded in proto3. switch fd.Kind() { case protoreflect.BoolKind: if ft.Kind() == reflect.Bool { return nil, coderBoolNoZero } case protoreflect.EnumKind: if ft.Kind() == reflect.Int32 { return nil, coderEnumNoZero } case protoreflect.Int32Kind: if ft.Kind() == reflect.Int32 { return nil, coderInt32NoZero } case protoreflect.Sint32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSint32NoZero } case protoreflect.Uint32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderUint32NoZero } case protoreflect.Int64Kind: if ft.Kind() == reflect.Int64 { return nil, coderInt64NoZero } case protoreflect.Sint64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSint64NoZero } case protoreflect.Uint64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderUint64NoZero } case protoreflect.Sfixed32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSfixed32NoZero } case protoreflect.Fixed32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderFixed32NoZero } case protoreflect.FloatKind: if ft.Kind() == reflect.Float32 { return nil, coderFloatNoZero } case protoreflect.Sfixed64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSfixed64NoZero } case protoreflect.Fixed64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderFixed64NoZero } case protoreflect.DoubleKind: if ft.Kind() == reflect.Float64 { return nil, coderDoubleNoZero } case protoreflect.StringKind: if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { return nil, coderStringNoZeroValidateUTF8 } if ft.Kind() == reflect.String { return nil, coderStringNoZero } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { return nil, coderBytesNoZeroValidateUTF8 } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytesNoZero } case protoreflect.BytesKind: if ft.Kind() == reflect.String { return nil, coderStringNoZero } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytesNoZero } } case ft.Kind() == reflect.Ptr: ft := ft.Elem() switch fd.Kind() { case protoreflect.BoolKind: if ft.Kind() == reflect.Bool { return nil, coderBoolPtr } case protoreflect.EnumKind: if ft.Kind() == reflect.Int32 { return nil, coderEnumPtr } case protoreflect.Int32Kind: if ft.Kind() == reflect.Int32 { return nil, coderInt32Ptr } case protoreflect.Sint32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSint32Ptr } case protoreflect.Uint32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderUint32Ptr } case protoreflect.Int64Kind: if ft.Kind() == reflect.Int64 { return nil, coderInt64Ptr } case protoreflect.Sint64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSint64Ptr } case protoreflect.Uint64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderUint64Ptr } case protoreflect.Sfixed32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSfixed32Ptr } case protoreflect.Fixed32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderFixed32Ptr } case protoreflect.FloatKind: if ft.Kind() == reflect.Float32 { return nil, coderFloatPtr } case protoreflect.Sfixed64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSfixed64Ptr } case protoreflect.Fixed64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderFixed64Ptr } case protoreflect.DoubleKind: if ft.Kind() == reflect.Float64 { return nil, coderDoublePtr } case protoreflect.StringKind: if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { return nil, coderStringPtrValidateUTF8 } if ft.Kind() == reflect.String { return nil, coderStringPtr } case protoreflect.BytesKind: if ft.Kind() == reflect.String { return nil, coderStringPtr } } default: switch fd.Kind() { case protoreflect.BoolKind: if ft.Kind() == reflect.Bool { return nil, coderBool } case protoreflect.EnumKind: if ft.Kind() == reflect.Int32 { return nil, coderEnum } case protoreflect.Int32Kind: if ft.Kind() == reflect.Int32 { return nil, coderInt32 } case protoreflect.Sint32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSint32 } case protoreflect.Uint32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderUint32 } case protoreflect.Int64Kind: if ft.Kind() == reflect.Int64 { return nil, coderInt64 } case protoreflect.Sint64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSint64 } case protoreflect.Uint64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderUint64 } case protoreflect.Sfixed32Kind: if ft.Kind() == reflect.Int32 { return nil, coderSfixed32 } case protoreflect.Fixed32Kind: if ft.Kind() == reflect.Uint32 { return nil, coderFixed32 } case protoreflect.FloatKind: if ft.Kind() == reflect.Float32 { return nil, coderFloat } case protoreflect.Sfixed64Kind: if ft.Kind() == reflect.Int64 { return nil, coderSfixed64 } case protoreflect.Fixed64Kind: if ft.Kind() == reflect.Uint64 { return nil, coderFixed64 } case protoreflect.DoubleKind: if ft.Kind() == reflect.Float64 { return nil, coderDouble } case protoreflect.StringKind: if ft.Kind() == reflect.String && strs.EnforceUTF8(fd) { return nil, coderStringValidateUTF8 } if ft.Kind() == reflect.String { return nil, coderString } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 && strs.EnforceUTF8(fd) { return nil, coderBytesValidateUTF8 } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytes } case protoreflect.BytesKind: if ft.Kind() == reflect.String { return nil, coderString } if ft.Kind() == reflect.Slice && ft.Elem().Kind() == reflect.Uint8 { return nil, coderBytes } } } panic(fmt.Sprintf("invalid type: no encoder for %v %v %v/%v", fd.FullName(), fd.Cardinality(), fd.Kind(), ft)) } // encoderFuncsForValue returns value functions for a field, used for // extension values and map encoding. func encoderFuncsForValue(fd protoreflect.FieldDescriptor) valueCoderFuncs { switch { case fd.Cardinality() == protoreflect.Repeated && !fd.IsPacked(): switch fd.Kind() { case protoreflect.BoolKind: return coderBoolSliceValue case protoreflect.EnumKind: return coderEnumSliceValue case protoreflect.Int32Kind: return coderInt32SliceValue case protoreflect.Sint32Kind: return coderSint32SliceValue case protoreflect.Uint32Kind: return coderUint32SliceValue case protoreflect.Int64Kind: return coderInt64SliceValue case protoreflect.Sint64Kind: return coderSint64SliceValue case protoreflect.Uint64Kind: return coderUint64SliceValue case protoreflect.Sfixed32Kind: return coderSfixed32SliceValue case protoreflect.Fixed32Kind: return coderFixed32SliceValue case protoreflect.FloatKind: return coderFloatSliceValue case protoreflect.Sfixed64Kind: return coderSfixed64SliceValue case protoreflect.Fixed64Kind: return coderFixed64SliceValue case protoreflect.DoubleKind: return coderDoubleSliceValue case protoreflect.StringKind: // We don't have a UTF-8 validating coder for repeated string fields. // Value coders are used for extensions and maps. // Extensions are never proto3, and maps never contain lists. return coderStringSliceValue case protoreflect.BytesKind: return coderBytesSliceValue case protoreflect.MessageKind: return coderMessageSliceValue case protoreflect.GroupKind: return coderGroupSliceValue } case fd.Cardinality() == protoreflect.Repeated && fd.IsPacked(): switch fd.Kind() { case protoreflect.BoolKind: return coderBoolPackedSliceValue case protoreflect.EnumKind: return coderEnumPackedSliceValue case protoreflect.Int32Kind: return coderInt32PackedSliceValue case protoreflect.Sint32Kind: return coderSint32PackedSliceValue case protoreflect.Uint32Kind: return coderUint32PackedSliceValue case protoreflect.Int64Kind: return coderInt64PackedSliceValue case protoreflect.Sint64Kind: return coderSint64PackedSliceValue case protoreflect.Uint64Kind: return coderUint64PackedSliceValue case protoreflect.Sfixed32Kind: return coderSfixed32PackedSliceValue case protoreflect.Fixed32Kind: return coderFixed32PackedSliceValue case protoreflect.FloatKind: return coderFloatPackedSliceValue case protoreflect.Sfixed64Kind: return coderSfixed64PackedSliceValue case protoreflect.Fixed64Kind: return coderFixed64PackedSliceValue case protoreflect.DoubleKind: return coderDoublePackedSliceValue } default: switch fd.Kind() { default: case protoreflect.BoolKind: return coderBoolValue case protoreflect.EnumKind: return coderEnumValue case protoreflect.Int32Kind: return coderInt32Value case protoreflect.Sint32Kind: return coderSint32Value case protoreflect.Uint32Kind: return coderUint32Value case protoreflect.Int64Kind: return coderInt64Value case protoreflect.Sint64Kind: return coderSint64Value case protoreflect.Uint64Kind: return coderUint64Value case protoreflect.Sfixed32Kind: return coderSfixed32Value case protoreflect.Fixed32Kind: return coderFixed32Value case protoreflect.FloatKind: return coderFloatValue case protoreflect.Sfixed64Kind: return coderSfixed64Value case protoreflect.Fixed64Kind: return coderFixed64Value case protoreflect.DoubleKind: return coderDoubleValue case protoreflect.StringKind: if strs.EnforceUTF8(fd) { return coderStringValueValidateUTF8 } return coderStringValue case protoreflect.BytesKind: return coderBytesValue case protoreflect.MessageKind: return coderMessageValue case protoreflect.GroupKind: return coderGroupValue } } panic(fmt.Sprintf("invalid field: no encoder for %v %v %v", fd.FullName(), fd.Cardinality(), fd.Kind())) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_export.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "encoding/binary" "encoding/json" "hash/crc32" "math" "reflect" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // These functions exist to support exported APIs in generated protobufs. // While these are deprecated, they cannot be removed for compatibility reasons. // LegacyEnumName returns the name of enums used in legacy code. func (Export) LegacyEnumName(ed protoreflect.EnumDescriptor) string { return legacyEnumName(ed) } // LegacyMessageTypeOf returns the protoreflect.MessageType for m, // with name used as the message name if necessary. func (Export) LegacyMessageTypeOf(m protoiface.MessageV1, name protoreflect.FullName) protoreflect.MessageType { if mv := (Export{}).protoMessageV2Of(m); mv != nil { return mv.ProtoReflect().Type() } return legacyLoadMessageType(reflect.TypeOf(m), name) } // UnmarshalJSONEnum unmarshals an enum from a JSON-encoded input. // The input can either be a string representing the enum value by name, // or a number representing the enum number itself. func (Export) UnmarshalJSONEnum(ed protoreflect.EnumDescriptor, b []byte) (protoreflect.EnumNumber, error) { if b[0] == '"' { var name protoreflect.Name if err := json.Unmarshal(b, &name); err != nil { return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b) } ev := ed.Values().ByName(name) if ev == nil { return 0, errors.New("invalid value for enum %v: %s", ed.FullName(), name) } return ev.Number(), nil } else { var num protoreflect.EnumNumber if err := json.Unmarshal(b, &num); err != nil { return 0, errors.New("invalid input for enum %v: %s", ed.FullName(), b) } return num, nil } } // CompressGZIP compresses the input as a GZIP-encoded file. // The current implementation does no compression. func (Export) CompressGZIP(in []byte) (out []byte) { // RFC 1952, section 2.3.1. var gzipHeader = [10]byte{0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff} // RFC 1951, section 3.2.4. var blockHeader [5]byte const maxBlockSize = math.MaxUint16 numBlocks := 1 + len(in)/maxBlockSize // RFC 1952, section 2.3.1. var gzipFooter [8]byte binary.LittleEndian.PutUint32(gzipFooter[0:4], crc32.ChecksumIEEE(in)) binary.LittleEndian.PutUint32(gzipFooter[4:8], uint32(len(in))) // Encode the input without compression using raw DEFLATE blocks. out = make([]byte, 0, len(gzipHeader)+len(blockHeader)*numBlocks+len(in)+len(gzipFooter)) out = append(out, gzipHeader[:]...) for blockHeader[0] == 0 { blockSize := maxBlockSize if blockSize > len(in) { blockHeader[0] = 0x01 // final bit per RFC 1951, section 3.2.3. blockSize = len(in) } binary.LittleEndian.PutUint16(blockHeader[1:3], uint16(blockSize)) binary.LittleEndian.PutUint16(blockHeader[3:5], ^uint16(blockSize)) out = append(out, blockHeader[:]...) out = append(out, in[:blockSize]...) in = in[blockSize:] } out = append(out, gzipFooter[:]...) return out }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_file.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "bytes" "compress/gzip" "io" "sync" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Every enum and message type generated by protoc-gen-go since commit 2fc053c5 // on February 25th, 2016 has had a method to get the raw descriptor. // Types that were not generated by protoc-gen-go or were generated prior // to that version are not supported. // // The []byte returned is the encoded form of a FileDescriptorProto message // compressed using GZIP. The []int is the path from the top-level file // to the specific message or enum declaration. type ( enumV1 interface { EnumDescriptor() ([]byte, []int) } messageV1 interface { Descriptor() ([]byte, []int) } ) var legacyFileDescCache sync.Map // map[*byte]protoreflect.FileDescriptor // legacyLoadFileDesc unmarshals b as a compressed FileDescriptorProto message. // // This assumes that b is immutable and that b does not refer to part of a // concatenated series of GZIP files (which would require shenanigans that // rely on the concatenation properties of both protobufs and GZIP). // File descriptors generated by protoc-gen-go do not rely on that property. func legacyLoadFileDesc(b []byte) protoreflect.FileDescriptor { // Fast-path: check whether we already have a cached file descriptor. if fd, ok := legacyFileDescCache.Load(&b[0]); ok { return fd.(protoreflect.FileDescriptor) } // Slow-path: decompress and unmarshal the file descriptor proto. zr, err := gzip.NewReader(bytes.NewReader(b)) if err != nil { panic(err) } b2, err := io.ReadAll(zr) if err != nil { panic(err) } fd := filedesc.Builder{ RawDescriptor: b2, FileRegistry: resolverOnly{protoregistry.GlobalFiles}, // do not register back to global registry }.Build().File if fd, ok := legacyFileDescCache.LoadOrStore(&b[0], fd); ok { return fd.(protoreflect.FileDescriptor) } return fd } type resolverOnly struct { reg *protoregistry.Files } func (r resolverOnly) FindFileByPath(path string) (protoreflect.FileDescriptor, error) { return r.reg.FindFileByPath(path) } func (r resolverOnly) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { return r.reg.FindDescriptorByName(name) } func (resolverOnly) RegisterFile(protoreflect.FileDescriptor) error { return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_field.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_field.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) type errInvalidUTF8 struct{} func (errInvalidUTF8) Error() string { return "string field contains invalid UTF-8" } func (errInvalidUTF8) InvalidUTF8() bool { return true } func (errInvalidUTF8) Unwrap() error { return errors.Error } // initOneofFieldCoders initializes the fast-path functions for the fields in a oneof. // // For size, marshal, and isInit operations, functions are set only on the first field // in the oneof. The functions are called when the oneof is non-nil, and will dispatch // to the appropriate field-specific function as necessary. // // The unmarshal function is set on each field individually as usual. func (mi *MessageInfo) initOneofFieldCoders(od protoreflect.OneofDescriptor, si structInfo) { fs := si.oneofsByName[od.Name()] ft := fs.Type oneofFields := make(map[reflect.Type]*coderFieldInfo) needIsInit := false fields := od.Fields() for i, lim := 0, fields.Len(); i < lim; i++ { fd := od.Fields().Get(i) num := fd.Number() // Make a copy of the original coderFieldInfo for use in unmarshaling. // // oneofFields[oneofType].funcs.marshal is the field-specific marshal function. // // mi.coderFields[num].marshal is set on only the first field in the oneof, // and dispatches to the field-specific marshaler in oneofFields. cf := *mi.coderFields[num] ot := si.oneofWrappersByNumber[num] cf.ft = ot.Field(0).Type cf.mi, cf.funcs = fieldCoder(fd, cf.ft) oneofFields[ot] = &cf if cf.funcs.isInit != nil { needIsInit = true } mi.coderFields[num].funcs.unmarshal = func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { var vw reflect.Value // pointer to wrapper type vi := p.AsValueOf(ft).Elem() // oneof field value of interface kind if !vi.IsNil() && !vi.Elem().IsNil() && vi.Elem().Elem().Type() == ot { vw = vi.Elem() } else { vw = reflect.New(ot) } out, err := cf.funcs.unmarshal(b, pointerOfValue(vw).Apply(zeroOffset), wtyp, &cf, opts) if err != nil { return out, err } if cf.funcs.isInit == nil { out.initialized = true } vi.Set(vw) return out, nil } } getInfo := func(p pointer) (pointer, *coderFieldInfo) { v := p.AsValueOf(ft).Elem() if v.IsNil() { return pointer{}, nil } v = v.Elem() // interface -> *struct if v.IsNil() { return pointer{}, nil } return pointerOfValue(v).Apply(zeroOffset), oneofFields[v.Elem().Type()] } first := mi.coderFields[od.Fields().Get(0).Number()] first.funcs.size = func(p pointer, _ *coderFieldInfo, opts marshalOptions) int { p, info := getInfo(p) if info == nil || info.funcs.size == nil { return 0 } return info.funcs.size(p, info, opts) } first.funcs.marshal = func(b []byte, p pointer, _ *coderFieldInfo, opts marshalOptions) ([]byte, error) { p, info := getInfo(p) if info == nil || info.funcs.marshal == nil { return b, nil } return info.funcs.marshal(b, p, info, opts) } first.funcs.merge = func(dst, src pointer, _ *coderFieldInfo, opts mergeOptions) { srcp, srcinfo := getInfo(src) if srcinfo == nil || srcinfo.funcs.merge == nil { return } dstp, dstinfo := getInfo(dst) if dstinfo != srcinfo { dst.AsValueOf(ft).Elem().Set(reflect.New(src.AsValueOf(ft).Elem().Elem().Elem().Type())) dstp = pointerOfValue(dst.AsValueOf(ft).Elem().Elem()).Apply(zeroOffset) } srcinfo.funcs.merge(dstp, srcp, srcinfo, opts) } if needIsInit { first.funcs.isInit = func(p pointer, _ *coderFieldInfo) error { p, info := getInfo(p) if info == nil || info.funcs.isInit == nil { return nil } return info.funcs.isInit(p, info) } } } func makeMessageFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { if mi := getMessageInfo(ft); mi != nil { funcs := pointerCoderFuncs{ size: sizeMessageInfo, marshal: appendMessageInfo, unmarshal: consumeMessageInfo, merge: mergeMessage, } if needsInitCheck(mi.Desc) { funcs.isInit = isInitMessageInfo } return funcs } else { return pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { m := asMessage(p.AsValueOf(ft).Elem()) return sizeMessage(m, f.tagsize, opts) }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { m := asMessage(p.AsValueOf(ft).Elem()) return appendMessage(b, m, f.wiretag, opts) }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { mp := p.AsValueOf(ft).Elem() if mp.IsNil() { mp.Set(reflect.New(ft.Elem())) } return consumeMessage(b, asMessage(mp), wtyp, opts) }, isInit: func(p pointer, f *coderFieldInfo) error { m := asMessage(p.AsValueOf(ft).Elem()) return proto.CheckInitialized(m) }, merge: mergeMessage, } } } func sizeMessageInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { return protowire.SizeBytes(f.mi.sizePointer(p.Elem(), opts)) + f.tagsize } func appendMessageInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { calculatedSize := f.mi.sizePointer(p.Elem(), opts) b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(calculatedSize)) before := len(b) b, err := f.mi.marshalAppendPointer(b, p.Elem(), opts) if measuredSize := len(b) - before; calculatedSize != measuredSize && err == nil { return nil, errors.MismatchedSizeCalculation(calculatedSize, measuredSize) } return b, err } func consumeMessageInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } if p.Elem().IsNil() { p.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } o, err := f.mi.unmarshalPointer(v, p.Elem(), 0, opts) if err != nil { return out, err } out.n = n out.initialized = o.initialized return out, nil } func isInitMessageInfo(p pointer, f *coderFieldInfo) error { return f.mi.checkInitializedPointer(p.Elem()) } func sizeMessage(m proto.Message, tagsize int, opts marshalOptions) int { return protowire.SizeBytes(opts.Options().Size(m)) + tagsize } func appendMessage(b []byte, m proto.Message, wiretag uint64, opts marshalOptions) ([]byte, error) { mopts := opts.Options() calculatedSize := mopts.Size(m) b = protowire.AppendVarint(b, wiretag) b = protowire.AppendVarint(b, uint64(calculatedSize)) before := len(b) b, err := mopts.MarshalAppend(b, m) if measuredSize := len(b) - before; calculatedSize != measuredSize && err == nil { return nil, errors.MismatchedSizeCalculation(calculatedSize, measuredSize) } return b, err } func consumeMessage(b []byte, m proto.Message, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: v, Message: m.ProtoReflect(), }) if err != nil { return out, err } out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return out, nil } func sizeMessageValue(v protoreflect.Value, tagsize int, opts marshalOptions) int { m := v.Message().Interface() return sizeMessage(m, tagsize, opts) } func appendMessageValue(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { m := v.Message().Interface() return appendMessage(b, m, wiretag, opts) } func consumeMessageValue(b []byte, v protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (protoreflect.Value, unmarshalOutput, error) { m := v.Message().Interface() out, err := consumeMessage(b, m, wtyp, opts) return v, out, err } func isInitMessageValue(v protoreflect.Value) error { m := v.Message().Interface() return proto.CheckInitialized(m) } var coderMessageValue = valueCoderFuncs{ size: sizeMessageValue, marshal: appendMessageValue, unmarshal: consumeMessageValue, isInit: isInitMessageValue, merge: mergeMessageValue, } func sizeGroupValue(v protoreflect.Value, tagsize int, opts marshalOptions) int { m := v.Message().Interface() return sizeGroup(m, tagsize, opts) } func appendGroupValue(b []byte, v protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { m := v.Message().Interface() return appendGroup(b, m, wiretag, opts) } func consumeGroupValue(b []byte, v protoreflect.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (protoreflect.Value, unmarshalOutput, error) { m := v.Message().Interface() out, err := consumeGroup(b, m, num, wtyp, opts) return v, out, err } var coderGroupValue = valueCoderFuncs{ size: sizeGroupValue, marshal: appendGroupValue, unmarshal: consumeGroupValue, isInit: isInitMessageValue, merge: mergeMessageValue, } func makeGroupFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { num := fd.Number() if mi := getMessageInfo(ft); mi != nil { funcs := pointerCoderFuncs{ size: sizeGroupType, marshal: appendGroupType, unmarshal: consumeGroupType, merge: mergeMessage, } if needsInitCheck(mi.Desc) { funcs.isInit = isInitMessageInfo } return funcs } else { return pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { m := asMessage(p.AsValueOf(ft).Elem()) return sizeGroup(m, f.tagsize, opts) }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { m := asMessage(p.AsValueOf(ft).Elem()) return appendGroup(b, m, f.wiretag, opts) }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { mp := p.AsValueOf(ft).Elem() if mp.IsNil() { mp.Set(reflect.New(ft.Elem())) } return consumeGroup(b, asMessage(mp), num, wtyp, opts) }, isInit: func(p pointer, f *coderFieldInfo) error { m := asMessage(p.AsValueOf(ft).Elem()) return proto.CheckInitialized(m) }, merge: mergeMessage, } } } func sizeGroupType(p pointer, f *coderFieldInfo, opts marshalOptions) int { return 2*f.tagsize + f.mi.sizePointer(p.Elem(), opts) } func appendGroupType(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, f.wiretag) // start group b, err := f.mi.marshalAppendPointer(b, p.Elem(), opts) b = protowire.AppendVarint(b, f.wiretag+1) // end group return b, err } func consumeGroupType(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.StartGroupType { return out, errUnknown } if p.Elem().IsNil() { p.SetPointer(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } return f.mi.unmarshalPointer(b, p.Elem(), f.num, opts) } func sizeGroup(m proto.Message, tagsize int, opts marshalOptions) int { return 2*tagsize + opts.Options().Size(m) } func appendGroup(b []byte, m proto.Message, wiretag uint64, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, wiretag) // start group b, err := opts.Options().MarshalAppend(b, m) b = protowire.AppendVarint(b, wiretag+1) // end group return b, err } func consumeGroup(b []byte, m proto.Message, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.StartGroupType { return out, errUnknown } b, n := protowire.ConsumeGroup(num, b) if n < 0 { return out, errDecode } o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: b, Message: m.ProtoReflect(), }) if err != nil { return out, err } out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return out, nil } func makeMessageSliceFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { if mi := getMessageInfo(ft); mi != nil { funcs := pointerCoderFuncs{ size: sizeMessageSliceInfo, marshal: appendMessageSliceInfo, unmarshal: consumeMessageSliceInfo, merge: mergeMessageSlice, } if needsInitCheck(mi.Desc) { funcs.isInit = isInitMessageSliceInfo } return funcs } return pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { return sizeMessageSlice(p, ft, f.tagsize, opts) }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { return appendMessageSlice(b, p, f.wiretag, ft, opts) }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { return consumeMessageSlice(b, p, ft, wtyp, opts) }, isInit: func(p pointer, f *coderFieldInfo) error { return isInitMessageSlice(p, ft) }, merge: mergeMessageSlice, } } func sizeMessageSliceInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { s := p.PointerSlice() n := 0 for _, v := range s { n += protowire.SizeBytes(f.mi.sizePointer(v, opts)) + f.tagsize } return n } func appendMessageSliceInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := p.PointerSlice() var err error for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) siz := f.mi.sizePointer(v, opts) b = protowire.AppendVarint(b, uint64(siz)) before := len(b) b, err = f.mi.marshalAppendPointer(b, v, opts) if err != nil { return b, err } if measuredSize := len(b) - before; siz != measuredSize { return nil, errors.MismatchedSizeCalculation(siz, measuredSize) } } return b, nil } func consumeMessageSliceInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } m := reflect.New(f.mi.GoReflectType.Elem()).Interface() mp := pointerOfIface(m) o, err := f.mi.unmarshalPointer(v, mp, 0, opts) if err != nil { return out, err } p.AppendPointerSlice(mp) out.n = n out.initialized = o.initialized return out, nil } func isInitMessageSliceInfo(p pointer, f *coderFieldInfo) error { s := p.PointerSlice() for _, v := range s { if err := f.mi.checkInitializedPointer(v); err != nil { return err } } return nil } func sizeMessageSlice(p pointer, goType reflect.Type, tagsize int, opts marshalOptions) int { mopts := opts.Options() s := p.PointerSlice() n := 0 for _, v := range s { m := asMessage(v.AsValueOf(goType.Elem())) n += protowire.SizeBytes(mopts.Size(m)) + tagsize } return n } func appendMessageSlice(b []byte, p pointer, wiretag uint64, goType reflect.Type, opts marshalOptions) ([]byte, error) { mopts := opts.Options() s := p.PointerSlice() var err error for _, v := range s { m := asMessage(v.AsValueOf(goType.Elem())) b = protowire.AppendVarint(b, wiretag) siz := mopts.Size(m) b = protowire.AppendVarint(b, uint64(siz)) before := len(b) b, err = mopts.MarshalAppend(b, m) if err != nil { return b, err } if measuredSize := len(b) - before; siz != measuredSize { return nil, errors.MismatchedSizeCalculation(siz, measuredSize) } } return b, nil } func consumeMessageSlice(b []byte, p pointer, goType reflect.Type, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } mp := reflect.New(goType.Elem()) o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: v, Message: asMessage(mp).ProtoReflect(), }) if err != nil { return out, err } p.AppendPointerSlice(pointerOfValue(mp)) out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return out, nil } func isInitMessageSlice(p pointer, goType reflect.Type) error { s := p.PointerSlice() for _, v := range s { m := asMessage(v.AsValueOf(goType.Elem())) if err := proto.CheckInitialized(m); err != nil { return err } } return nil } // Slices of messages func sizeMessageSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) int { mopts := opts.Options() list := listv.List() n := 0 for i, llen := 0, list.Len(); i < llen; i++ { m := list.Get(i).Message().Interface() n += protowire.SizeBytes(mopts.Size(m)) + tagsize } return n } func appendMessageSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() mopts := opts.Options() for i, llen := 0, list.Len(); i < llen; i++ { m := list.Get(i).Message().Interface() b = protowire.AppendVarint(b, wiretag) siz := mopts.Size(m) b = protowire.AppendVarint(b, uint64(siz)) before := len(b) var err error b, err = mopts.MarshalAppend(b, m) if err != nil { return b, err } if measuredSize := len(b) - before; siz != measuredSize { return nil, errors.MismatchedSizeCalculation(siz, measuredSize) } } return b, nil } func consumeMessageSliceValue(b []byte, listv protoreflect.Value, _ protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp != protowire.BytesType { return protoreflect.Value{}, out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return protoreflect.Value{}, out, errDecode } m := list.NewElement() o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: v, Message: m.Message(), }) if err != nil { return protoreflect.Value{}, out, err } list.Append(m) out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return listv, out, nil } func isInitMessageSliceValue(listv protoreflect.Value) error { list := listv.List() for i, llen := 0, list.Len(); i < llen; i++ { m := list.Get(i).Message().Interface() if err := proto.CheckInitialized(m); err != nil { return err } } return nil } var coderMessageSliceValue = valueCoderFuncs{ size: sizeMessageSliceValue, marshal: appendMessageSliceValue, unmarshal: consumeMessageSliceValue, isInit: isInitMessageSliceValue, merge: mergeMessageListValue, } func sizeGroupSliceValue(listv protoreflect.Value, tagsize int, opts marshalOptions) int { mopts := opts.Options() list := listv.List() n := 0 for i, llen := 0, list.Len(); i < llen; i++ { m := list.Get(i).Message().Interface() n += 2*tagsize + mopts.Size(m) } return n } func appendGroupSliceValue(b []byte, listv protoreflect.Value, wiretag uint64, opts marshalOptions) ([]byte, error) { list := listv.List() mopts := opts.Options() for i, llen := 0, list.Len(); i < llen; i++ { m := list.Get(i).Message().Interface() b = protowire.AppendVarint(b, wiretag) // start group var err error b, err = mopts.MarshalAppend(b, m) if err != nil { return b, err } b = protowire.AppendVarint(b, wiretag+1) // end group } return b, nil } func consumeGroupSliceValue(b []byte, listv protoreflect.Value, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (_ protoreflect.Value, out unmarshalOutput, err error) { list := listv.List() if wtyp != protowire.StartGroupType { return protoreflect.Value{}, out, errUnknown } b, n := protowire.ConsumeGroup(num, b) if n < 0 { return protoreflect.Value{}, out, errDecode } m := list.NewElement() o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: b, Message: m.Message(), }) if err != nil { return protoreflect.Value{}, out, err } list.Append(m) out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return listv, out, nil } var coderGroupSliceValue = valueCoderFuncs{ size: sizeGroupSliceValue, marshal: appendGroupSliceValue, unmarshal: consumeGroupSliceValue, isInit: isInitMessageSliceValue, merge: mergeMessageListValue, } func makeGroupSliceFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) pointerCoderFuncs { num := fd.Number() if mi := getMessageInfo(ft); mi != nil { funcs := pointerCoderFuncs{ size: sizeGroupSliceInfo, marshal: appendGroupSliceInfo, unmarshal: consumeGroupSliceInfo, merge: mergeMessageSlice, } if needsInitCheck(mi.Desc) { funcs.isInit = isInitMessageSliceInfo } return funcs } return pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { return sizeGroupSlice(p, ft, f.tagsize, opts) }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { return appendGroupSlice(b, p, f.wiretag, ft, opts) }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { return consumeGroupSlice(b, p, num, wtyp, ft, opts) }, isInit: func(p pointer, f *coderFieldInfo) error { return isInitMessageSlice(p, ft) }, merge: mergeMessageSlice, } } func sizeGroupSlice(p pointer, messageType reflect.Type, tagsize int, opts marshalOptions) int { mopts := opts.Options() s := p.PointerSlice() n := 0 for _, v := range s { m := asMessage(v.AsValueOf(messageType.Elem())) n += 2*tagsize + mopts.Size(m) } return n } func appendGroupSlice(b []byte, p pointer, wiretag uint64, messageType reflect.Type, opts marshalOptions) ([]byte, error) { s := p.PointerSlice() var err error for _, v := range s { m := asMessage(v.AsValueOf(messageType.Elem())) b = protowire.AppendVarint(b, wiretag) // start group b, err = opts.Options().MarshalAppend(b, m) if err != nil { return b, err } b = protowire.AppendVarint(b, wiretag+1) // end group } return b, nil } func consumeGroupSlice(b []byte, p pointer, num protowire.Number, wtyp protowire.Type, goType reflect.Type, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.StartGroupType { return out, errUnknown } b, n := protowire.ConsumeGroup(num, b) if n < 0 { return out, errDecode } mp := reflect.New(goType.Elem()) o, err := opts.Options().UnmarshalState(protoiface.UnmarshalInput{ Buf: b, Message: asMessage(mp).ProtoReflect(), }) if err != nil { return out, err } p.AppendPointerSlice(pointerOfValue(mp)) out.n = n out.initialized = o.Flags&protoiface.UnmarshalInitialized != 0 return out, nil } func sizeGroupSliceInfo(p pointer, f *coderFieldInfo, opts marshalOptions) int { s := p.PointerSlice() n := 0 for _, v := range s { n += 2*f.tagsize + f.mi.sizePointer(v, opts) } return n } func appendGroupSliceInfo(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := p.PointerSlice() var err error for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) // start group b, err = f.mi.marshalAppendPointer(b, v, opts) if err != nil { return b, err } b = protowire.AppendVarint(b, f.wiretag+1) // end group } return b, nil } func consumeGroupSliceInfo(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { if wtyp != protowire.StartGroupType { return unmarshalOutput{}, errUnknown } m := reflect.New(f.mi.GoReflectType.Elem()).Interface() mp := pointerOfIface(m) out, err := f.mi.unmarshalPointer(b, mp, f.num, opts) if err != nil { return out, err } p.AppendPointerSlice(mp) return out, nil } func asMessage(v reflect.Value) protoreflect.ProtoMessage { if m, ok := v.Interface().(protoreflect.ProtoMessage); ok { return m } return legacyWrapMessage(v).Interface() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/encode.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "math" "sort" "sync/atomic" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/protolazy" "google.golang.org/protobuf/proto" piface "google.golang.org/protobuf/runtime/protoiface" ) type marshalOptions struct { flags piface.MarshalInputFlags } func (o marshalOptions) Options() proto.MarshalOptions { return proto.MarshalOptions{ AllowPartial: true, Deterministic: o.Deterministic(), UseCachedSize: o.UseCachedSize(), } } func (o marshalOptions) Deterministic() bool { return o.flags&piface.MarshalDeterministic != 0 } func (o marshalOptions) UseCachedSize() bool { return o.flags&piface.MarshalUseCachedSize != 0 } // size is protoreflect.Methods.Size. func (mi *MessageInfo) size(in piface.SizeInput) piface.SizeOutput { var p pointer if ms, ok := in.Message.(*messageState); ok { p = ms.pointer() } else { p = in.Message.(*messageReflectWrapper).pointer() } size := mi.sizePointer(p, marshalOptions{ flags: in.Flags, }) return piface.SizeOutput{Size: size} } func (mi *MessageInfo) sizePointer(p pointer, opts marshalOptions) (size int) { mi.init() if p.IsNil() { return 0 } if opts.UseCachedSize() && mi.sizecacheOffset.IsValid() { // The size cache contains the size + 1, to allow the // zero value to be invalid, while also allowing for a // 0 size to be cached. if size := atomic.LoadInt32(p.Apply(mi.sizecacheOffset).Int32()); size > 0 { return int(size - 1) } } return mi.sizePointerSlow(p, opts) } func (mi *MessageInfo) sizePointerSlow(p pointer, opts marshalOptions) (size int) { if flags.ProtoLegacy && mi.isMessageSet { size = sizeMessageSet(mi, p, opts) if mi.sizecacheOffset.IsValid() { atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), int32(size+1)) } return size } if mi.extensionOffset.IsValid() { e := p.Apply(mi.extensionOffset).Extensions() size += mi.sizeExtensions(e, opts) } var lazy **protolazy.XXX_lazyUnmarshalInfo var presence presence if mi.presenceOffset.IsValid() { presence = p.Apply(mi.presenceOffset).PresenceInfo() if mi.lazyOffset.IsValid() { lazy = p.Apply(mi.lazyOffset).LazyInfoPtr() } } for _, f := range mi.orderedCoderFields { if f.funcs.size == nil { continue } fptr := p.Apply(f.offset) if f.presenceIndex != noPresence { if !presence.Present(f.presenceIndex) { continue } if f.isLazy && fptr.AtomicGetPointer().IsNil() { if lazyFields(opts) { size += (*lazy).SizeField(uint32(f.num)) continue } else { mi.lazyUnmarshal(p, f.num) } } size += f.funcs.size(fptr, f, opts) continue } if f.isPointer && fptr.Elem().IsNil() { continue } size += f.funcs.size(fptr, f, opts) } if mi.unknownOffset.IsValid() { if u := mi.getUnknownBytes(p); u != nil { size += len(*u) } } if mi.sizecacheOffset.IsValid() { if size > (math.MaxInt32 - 1) { // The size is too large for the int32 sizecache field. // We will need to recompute the size when encoding; // unfortunately expensive, but better than invalid output. atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), 0) } else { // The size cache contains the size + 1, to allow the // zero value to be invalid, while also allowing for a // 0 size to be cached. atomic.StoreInt32(p.Apply(mi.sizecacheOffset).Int32(), int32(size+1)) } } return size } // marshal is protoreflect.Methods.Marshal. func (mi *MessageInfo) marshal(in piface.MarshalInput) (out piface.MarshalOutput, err error) { var p pointer if ms, ok := in.Message.(*messageState); ok { p = ms.pointer() } else { p = in.Message.(*messageReflectWrapper).pointer() } b, err := mi.marshalAppendPointer(in.Buf, p, marshalOptions{ flags: in.Flags, }) return piface.MarshalOutput{Buf: b}, err } func (mi *MessageInfo) marshalAppendPointer(b []byte, p pointer, opts marshalOptions) ([]byte, error) { mi.init() if p.IsNil() { return b, nil } if flags.ProtoLegacy && mi.isMessageSet { return marshalMessageSet(mi, b, p, opts) } var err error // The old marshaler encodes extensions at beginning. if mi.extensionOffset.IsValid() { e := p.Apply(mi.extensionOffset).Extensions() // TODO: Special handling for MessageSet? b, err = mi.appendExtensions(b, e, opts) if err != nil { return b, err } } var lazy **protolazy.XXX_lazyUnmarshalInfo var presence presence if mi.presenceOffset.IsValid() { presence = p.Apply(mi.presenceOffset).PresenceInfo() if mi.lazyOffset.IsValid() { lazy = p.Apply(mi.lazyOffset).LazyInfoPtr() } } for _, f := range mi.orderedCoderFields { if f.funcs.marshal == nil { continue } fptr := p.Apply(f.offset) if f.presenceIndex != noPresence { if !presence.Present(f.presenceIndex) { continue } if f.isLazy { // Be careful, this field needs to be read atomically, like for a get if f.isPointer && fptr.AtomicGetPointer().IsNil() { if lazyFields(opts) { b, _ = (*lazy).AppendField(b, uint32(f.num)) continue } else { mi.lazyUnmarshal(p, f.num) } } b, err = f.funcs.marshal(b, fptr, f, opts) if err != nil { return b, err } continue } else if f.isPointer && fptr.Elem().IsNil() { continue } b, err = f.funcs.marshal(b, fptr, f, opts) if err != nil { return b, err } continue } if f.isPointer && fptr.Elem().IsNil() { continue } b, err = f.funcs.marshal(b, fptr, f, opts) if err != nil { return b, err } } if mi.unknownOffset.IsValid() && !mi.isMessageSet { if u := mi.getUnknownBytes(p); u != nil { b = append(b, (*u)...) } } return b, nil } // fullyLazyExtensions returns true if we should attempt to keep extensions lazy over size and marshal. func fullyLazyExtensions(opts marshalOptions) bool { // When deterministic marshaling is requested, force an unmarshal for lazy // extensions to produce a deterministic result, instead of passing through // bytes lazily that may or may not match what Go Protobuf would produce. return opts.flags&piface.MarshalDeterministic == 0 } // lazyFields returns true if we should attempt to keep fields lazy over size and marshal. func lazyFields(opts marshalOptions) bool { // When deterministic marshaling is requested, force an unmarshal for lazy // fields to produce a deterministic result, instead of passing through // bytes lazily that may or may not match what Go Protobuf would produce. return opts.flags&piface.MarshalDeterministic == 0 } func (mi *MessageInfo) sizeExtensions(ext *map[int32]ExtensionField, opts marshalOptions) (n int) { if ext == nil { return 0 } for _, x := range *ext { xi := getExtensionFieldInfo(x.Type()) if xi.funcs.size == nil { continue } if fullyLazyExtensions(opts) { // Don't expand the extension, instead use the buffer to calculate size if lb := x.lazyBuffer(); lb != nil { // We got hold of the buffer, so it's still lazy. n += len(lb) continue } } n += xi.funcs.size(x.Value(), xi.tagsize, opts) } return n } func (mi *MessageInfo) appendExtensions(b []byte, ext *map[int32]ExtensionField, opts marshalOptions) ([]byte, error) { if ext == nil { return b, nil } switch len(*ext) { case 0: return b, nil case 1: // Fast-path for one extension: Don't bother sorting the keys. var err error for _, x := range *ext { xi := getExtensionFieldInfo(x.Type()) if fullyLazyExtensions(opts) { // Don't expand the extension if it's still in wire format, instead use the buffer content. if lb := x.lazyBuffer(); lb != nil { b = append(b, lb...) continue } } b, err = xi.funcs.marshal(b, x.Value(), xi.wiretag, opts) } return b, err default: // Sort the keys to provide a deterministic encoding. // Not sure this is required, but the old code does it. keys := make([]int, 0, len(*ext)) for k := range *ext { keys = append(keys, int(k)) } sort.Ints(keys) var err error for _, k := range keys { x := (*ext)[int32(k)] xi := getExtensionFieldInfo(x.Type()) if fullyLazyExtensions(opts) { // Don't expand the extension if it's still in wire format, instead use the buffer content. if lb := x.lazyBuffer(); lb != nil { b = append(b, lb...) continue } } b, err = xi.funcs.marshal(b, x.Value(), xi.wiretag, opts) if err != nil { return b, err } } return b, nil } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_messageset.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "sort" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" ) func sizeMessageSet(mi *MessageInfo, p pointer, opts marshalOptions) (size int) { if !flags.ProtoLegacy { return 0 } ext := *p.Apply(mi.extensionOffset).Extensions() for _, x := range ext { xi := getExtensionFieldInfo(x.Type()) if xi.funcs.size == nil { continue } num, _ := protowire.DecodeTag(xi.wiretag) size += messageset.SizeField(num) if fullyLazyExtensions(opts) { // Don't expand the extension, instead use the buffer to calculate size if lb := x.lazyBuffer(); lb != nil { // We got hold of the buffer, so it's still lazy. // Don't count the tag size in the extension buffer, it's already added. size += protowire.SizeTag(messageset.FieldMessage) + len(lb) - xi.tagsize continue } } size += xi.funcs.size(x.Value(), protowire.SizeTag(messageset.FieldMessage), opts) } if u := mi.getUnknownBytes(p); u != nil { size += messageset.SizeUnknown(*u) } return size } func marshalMessageSet(mi *MessageInfo, b []byte, p pointer, opts marshalOptions) ([]byte, error) { if !flags.ProtoLegacy { return b, errors.New("no support for message_set_wire_format") } ext := *p.Apply(mi.extensionOffset).Extensions() switch len(ext) { case 0: case 1: // Fast-path for one extension: Don't bother sorting the keys. for _, x := range ext { var err error b, err = marshalMessageSetField(mi, b, x, opts) if err != nil { return b, err } } default: // Sort the keys to provide a deterministic encoding. // Not sure this is required, but the old code does it. keys := make([]int, 0, len(ext)) for k := range ext { keys = append(keys, int(k)) } sort.Ints(keys) for _, k := range keys { var err error b, err = marshalMessageSetField(mi, b, ext[int32(k)], opts) if err != nil { return b, err } } } if u := mi.getUnknownBytes(p); u != nil { var err error b, err = messageset.AppendUnknown(b, *u) if err != nil { return b, err } } return b, nil } func marshalMessageSetField(mi *MessageInfo, b []byte, x ExtensionField, opts marshalOptions) ([]byte, error) { xi := getExtensionFieldInfo(x.Type()) num, _ := protowire.DecodeTag(xi.wiretag) b = messageset.AppendFieldStart(b, num) if fullyLazyExtensions(opts) { // Don't expand the extension if it's still in wire format, instead use the buffer content. if lb := x.lazyBuffer(); lb != nil { // The tag inside the lazy buffer is a different tag (the extension // number), but what we need here is the tag for FieldMessage: b = protowire.AppendVarint(b, protowire.EncodeTag(messageset.FieldMessage, protowire.BytesType)) b = append(b, lb[xi.tagsize:]...) b = messageset.AppendFieldEnd(b) return b, nil } } b, err := xi.funcs.marshal(b, x.Value(), protowire.EncodeTag(messageset.FieldMessage, protowire.BytesType), opts) if err != nil { return b, err } b = messageset.AppendFieldEnd(b) return b, nil } func unmarshalMessageSet(mi *MessageInfo, b []byte, p pointer, opts unmarshalOptions) (out unmarshalOutput, err error) { if !flags.ProtoLegacy { return out, errors.New("no support for message_set_wire_format") } ep := p.Apply(mi.extensionOffset).Extensions() if *ep == nil { *ep = make(map[int32]ExtensionField) } ext := *ep initialized := true err = messageset.Unmarshal(b, true, func(num protowire.Number, v []byte) error { o, err := mi.unmarshalExtension(v, num, protowire.BytesType, ext, opts) if err == errUnknown { u := mi.mutableUnknownBytes(p) *u = protowire.AppendTag(*u, num, protowire.BytesType) *u = append(*u, v...) return nil } if !o.initialized { initialized = false } return err }) out.n = len(b) out.initialized = initialized return out, err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/bitmap_race.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/bitmap_race.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build race package impl // When running under race detector, we add a presence map of bytes, that we can access // in the hook functions so that we trigger the race detection whenever we have concurrent // Read-Writes or Write-Writes. The race detector does not otherwise detect invalid concurrent // access to lazy fields as all updates of bitmaps and pointers are done using atomic operations. type RaceDetectHookData struct { shadowPresence *[]byte } // Hooks for presence bitmap operations that allocate, read and write the shadowPresence // using non-atomic operations. func (data *RaceDetectHookData) raceDetectHookAlloc(size presenceSize) { sp := make([]byte, size) atomicStoreShadowPresence(&data.shadowPresence, &sp) } func (p presence) raceDetectHookPresent(num uint32) { data := p.toRaceDetectData() if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp != nil { _ = (*sp)[num] } } func (p presence) raceDetectHookSetPresent(num uint32, size presenceSize) { data := p.toRaceDetectData() if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp == nil { data.raceDetectHookAlloc(size) sp = atomicLoadShadowPresence(&data.shadowPresence) } (*sp)[num] = 1 } func (p presence) raceDetectHookClearPresent(num uint32) { data := p.toRaceDetectData() if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp != nil { (*sp)[num] = 0 } } // raceDetectHookAllocAndCopy allocates a new shadowPresence slice at lazy and copies // shadowPresence bytes from src to lazy. func (p presence) raceDetectHookAllocAndCopy(q presence) { sData := q.toRaceDetectData() dData := p.toRaceDetectData() if sData == nil { return } srcSp := atomicLoadShadowPresence(&sData.shadowPresence) if srcSp == nil { atomicStoreShadowPresence(&dData.shadowPresence, nil) return } n := len(*srcSp) dSlice := make([]byte, n) atomicStoreShadowPresence(&dData.shadowPresence, &dSlice) for i := 0; i < n; i++ { dSlice[i] = (*srcSp)[i] } } // raceDetectHookPresent is called by the generated file interface // (*proto.internalFuncs) Present to optionally read an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookPresent(field *uint32, num uint32) { data := findPointerToRaceDetectData(field, num) if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp != nil { _ = (*sp)[num] } } // raceDetectHookSetPresent is called by the generated file interface // (*proto.internalFuncs) SetPresent to optionally write an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookSetPresent(field *uint32, num uint32, size presenceSize) { data := findPointerToRaceDetectData(field, num) if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp == nil { data.raceDetectHookAlloc(size) sp = atomicLoadShadowPresence(&data.shadowPresence) } (*sp)[num] = 1 } // raceDetectHookClearPresent is called by the generated file interface // (*proto.internalFuncs) ClearPresent to optionally write an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookClearPresent(field *uint32, num uint32) { data := findPointerToRaceDetectData(field, num) if data == nil { return } sp := atomicLoadShadowPresence(&data.shadowPresence) if sp != nil { (*sp)[num] = 0 } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/bitmap.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/bitmap.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. //go:build !race package impl // There is no additional data as we're not running under race detector. type RaceDetectHookData struct{} // Empty stubs for when not using the race detector. Calls to these from index.go should be optimized away. func (presence) raceDetectHookPresent(num uint32) {} func (presence) raceDetectHookSetPresent(num uint32, size presenceSize) {} func (presence) raceDetectHookClearPresent(num uint32) {} func (presence) raceDetectHookAllocAndCopy(src presence) {} // raceDetectHookPresent is called by the generated file interface // (*proto.internalFuncs) Present to optionally read an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookPresent(field *uint32, num uint32) {} // raceDetectHookSetPresent is called by the generated file interface // (*proto.internalFuncs) SetPresent to optionally write an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookSetPresent(field *uint32, num uint32, size presenceSize) {} // raceDetectHookClearPresent is called by the generated file interface // (*proto.internalFuncs) ClearPresent to optionally write an unprotected // shadow bitmap when race detection is enabled. In regular code it is // a noop. func raceDetectHookClearPresent(field *uint32, num uint32) {}
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_field_opaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_field_opaque.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) func makeOpaqueMessageFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) (*MessageInfo, pointerCoderFuncs) { mi := getMessageInfo(ft) if mi == nil { panic(fmt.Sprintf("invalid field: %v: unsupported message type %v", fd.FullName(), ft)) } switch fd.Kind() { case protoreflect.MessageKind: return mi, pointerCoderFuncs{ size: sizeOpaqueMessage, marshal: appendOpaqueMessage, unmarshal: consumeOpaqueMessage, isInit: isInitOpaqueMessage, merge: mergeOpaqueMessage, } case protoreflect.GroupKind: return mi, pointerCoderFuncs{ size: sizeOpaqueGroup, marshal: appendOpaqueGroup, unmarshal: consumeOpaqueGroup, isInit: isInitOpaqueMessage, merge: mergeOpaqueMessage, } } panic("unexpected field kind") } func sizeOpaqueMessage(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { return protowire.SizeBytes(f.mi.sizePointer(p.AtomicGetPointer(), opts)) + f.tagsize } func appendOpaqueMessage(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { mp := p.AtomicGetPointer() calculatedSize := f.mi.sizePointer(mp, opts) b = protowire.AppendVarint(b, f.wiretag) b = protowire.AppendVarint(b, uint64(calculatedSize)) before := len(b) b, err := f.mi.marshalAppendPointer(b, mp, opts) if measuredSize := len(b) - before; calculatedSize != measuredSize && err == nil { return nil, errors.MismatchedSizeCalculation(calculatedSize, measuredSize) } return b, err } func consumeOpaqueMessage(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } mp := p.AtomicGetPointer() if mp.IsNil() { mp = p.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } o, err := f.mi.unmarshalPointer(v, mp, 0, opts) if err != nil { return out, err } out.n = n out.initialized = o.initialized return out, nil } func isInitOpaqueMessage(p pointer, f *coderFieldInfo) error { mp := p.AtomicGetPointer() if mp.IsNil() { return nil } return f.mi.checkInitializedPointer(mp) } func mergeOpaqueMessage(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { dstmp := dst.AtomicGetPointer() if dstmp.IsNil() { dstmp = dst.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } f.mi.mergePointer(dstmp, src.AtomicGetPointer(), opts) } func sizeOpaqueGroup(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { return 2*f.tagsize + f.mi.sizePointer(p.AtomicGetPointer(), opts) } func appendOpaqueGroup(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { b = protowire.AppendVarint(b, f.wiretag) // start group b, err := f.mi.marshalAppendPointer(b, p.AtomicGetPointer(), opts) b = protowire.AppendVarint(b, f.wiretag+1) // end group return b, err } func consumeOpaqueGroup(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.StartGroupType { return out, errUnknown } mp := p.AtomicGetPointer() if mp.IsNil() { mp = p.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.mi.GoReflectType.Elem()))) } o, e := f.mi.unmarshalPointer(b, mp, f.num, opts) return o, e } func makeOpaqueRepeatedMessageFieldCoder(fd protoreflect.FieldDescriptor, ft reflect.Type) (*MessageInfo, pointerCoderFuncs) { if ft.Kind() != reflect.Ptr || ft.Elem().Kind() != reflect.Slice { panic(fmt.Sprintf("invalid field: %v: unsupported type for opaque repeated message: %v", fd.FullName(), ft)) } mt := ft.Elem().Elem() // *[]*T -> *T mi := getMessageInfo(mt) if mi == nil { panic(fmt.Sprintf("invalid field: %v: unsupported message type %v", fd.FullName(), mt)) } switch fd.Kind() { case protoreflect.MessageKind: return mi, pointerCoderFuncs{ size: sizeOpaqueMessageSlice, marshal: appendOpaqueMessageSlice, unmarshal: consumeOpaqueMessageSlice, isInit: isInitOpaqueMessageSlice, merge: mergeOpaqueMessageSlice, } case protoreflect.GroupKind: return mi, pointerCoderFuncs{ size: sizeOpaqueGroupSlice, marshal: appendOpaqueGroupSlice, unmarshal: consumeOpaqueGroupSlice, isInit: isInitOpaqueMessageSlice, merge: mergeOpaqueMessageSlice, } } panic("unexpected field kind") } func sizeOpaqueMessageSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := p.AtomicGetPointer().PointerSlice() n := 0 for _, v := range s { n += protowire.SizeBytes(f.mi.sizePointer(v, opts)) + f.tagsize } return n } func appendOpaqueMessageSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := p.AtomicGetPointer().PointerSlice() var err error for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) siz := f.mi.sizePointer(v, opts) b = protowire.AppendVarint(b, uint64(siz)) before := len(b) b, err = f.mi.marshalAppendPointer(b, v, opts) if err != nil { return b, err } if measuredSize := len(b) - before; siz != measuredSize { return nil, errors.MismatchedSizeCalculation(siz, measuredSize) } } return b, nil } func consumeOpaqueMessageSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } mp := pointerOfValue(reflect.New(f.mi.GoReflectType.Elem())) o, err := f.mi.unmarshalPointer(v, mp, 0, opts) if err != nil { return out, err } sp := p.AtomicGetPointer() if sp.IsNil() { sp = p.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.ft.Elem()))) } sp.AppendPointerSlice(mp) out.n = n out.initialized = o.initialized return out, nil } func isInitOpaqueMessageSlice(p pointer, f *coderFieldInfo) error { sp := p.AtomicGetPointer() if sp.IsNil() { return nil } s := sp.PointerSlice() for _, v := range s { if err := f.mi.checkInitializedPointer(v); err != nil { return err } } return nil } func mergeOpaqueMessageSlice(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { ds := dst.AtomicGetPointer() if ds.IsNil() { ds = dst.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.ft.Elem()))) } for _, sp := range src.AtomicGetPointer().PointerSlice() { dm := pointerOfValue(reflect.New(f.mi.GoReflectType.Elem())) f.mi.mergePointer(dm, sp, opts) ds.AppendPointerSlice(dm) } } func sizeOpaqueGroupSlice(p pointer, f *coderFieldInfo, opts marshalOptions) (size int) { s := p.AtomicGetPointer().PointerSlice() n := 0 for _, v := range s { n += 2*f.tagsize + f.mi.sizePointer(v, opts) } return n } func appendOpaqueGroupSlice(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { s := p.AtomicGetPointer().PointerSlice() var err error for _, v := range s { b = protowire.AppendVarint(b, f.wiretag) // start group b, err = f.mi.marshalAppendPointer(b, v, opts) if err != nil { return b, err } b = protowire.AppendVarint(b, f.wiretag+1) // end group } return b, nil } func consumeOpaqueGroupSlice(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.StartGroupType { return out, errUnknown } mp := pointerOfValue(reflect.New(f.mi.GoReflectType.Elem())) out, err = f.mi.unmarshalPointer(b, mp, f.num, opts) if err != nil { return out, err } sp := p.AtomicGetPointer() if sp.IsNil() { sp = p.AtomicSetPointerIfNil(pointerOfValue(reflect.New(f.ft.Elem()))) } sp.AppendPointerSlice(mp) return out, err }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_enum.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strings" "sync" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // legacyEnumName returns the name of enums used in legacy code. // It is neither the protobuf full name nor the qualified Go name, // but rather an odd hybrid of both. func legacyEnumName(ed protoreflect.EnumDescriptor) string { var protoPkg string enumName := string(ed.FullName()) if fd := ed.ParentFile(); fd != nil { protoPkg = string(fd.Package()) enumName = strings.TrimPrefix(enumName, protoPkg+".") } if protoPkg == "" { return strs.GoCamelCase(enumName) } return protoPkg + "." + strs.GoCamelCase(enumName) } // legacyWrapEnum wraps v as a protoreflect.Enum, // where v must be a int32 kind and not implement the v2 API already. func legacyWrapEnum(v reflect.Value) protoreflect.Enum { et := legacyLoadEnumType(v.Type()) return et.New(protoreflect.EnumNumber(v.Int())) } var legacyEnumTypeCache sync.Map // map[reflect.Type]protoreflect.EnumType // legacyLoadEnumType dynamically loads a protoreflect.EnumType for t, // where t must be an int32 kind and not implement the v2 API already. func legacyLoadEnumType(t reflect.Type) protoreflect.EnumType { // Fast-path: check if a EnumType is cached for this concrete type. if et, ok := legacyEnumTypeCache.Load(t); ok { return et.(protoreflect.EnumType) } // Slow-path: derive enum descriptor and initialize EnumType. var et protoreflect.EnumType ed := LegacyLoadEnumDesc(t) et = &legacyEnumType{ desc: ed, goType: t, } if et, ok := legacyEnumTypeCache.LoadOrStore(t, et); ok { return et.(protoreflect.EnumType) } return et } type legacyEnumType struct { desc protoreflect.EnumDescriptor goType reflect.Type m sync.Map // map[protoreflect.EnumNumber]proto.Enum } func (t *legacyEnumType) New(n protoreflect.EnumNumber) protoreflect.Enum { if e, ok := t.m.Load(n); ok { return e.(protoreflect.Enum) } e := &legacyEnumWrapper{num: n, pbTyp: t, goTyp: t.goType} t.m.Store(n, e) return e } func (t *legacyEnumType) Descriptor() protoreflect.EnumDescriptor { return t.desc } type legacyEnumWrapper struct { num protoreflect.EnumNumber pbTyp protoreflect.EnumType goTyp reflect.Type } func (e *legacyEnumWrapper) Descriptor() protoreflect.EnumDescriptor { return e.pbTyp.Descriptor() } func (e *legacyEnumWrapper) Type() protoreflect.EnumType { return e.pbTyp } func (e *legacyEnumWrapper) Number() protoreflect.EnumNumber { return e.num } func (e *legacyEnumWrapper) ProtoReflect() protoreflect.Enum { return e } func (e *legacyEnumWrapper) protoUnwrap() any { v := reflect.New(e.goTyp).Elem() v.SetInt(int64(e.num)) return v.Interface() } var ( _ protoreflect.Enum = (*legacyEnumWrapper)(nil) _ unwrapper = (*legacyEnumWrapper)(nil) ) var legacyEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor // LegacyLoadEnumDesc returns an EnumDescriptor derived from the Go type, // which must be an int32 kind and not implement the v2 API already. // // This is exported for testing purposes. func LegacyLoadEnumDesc(t reflect.Type) protoreflect.EnumDescriptor { // Fast-path: check if an EnumDescriptor is cached for this concrete type. if ed, ok := legacyEnumDescCache.Load(t); ok { return ed.(protoreflect.EnumDescriptor) } // Slow-path: initialize EnumDescriptor from the raw descriptor. ev := reflect.Zero(t).Interface() if _, ok := ev.(protoreflect.Enum); ok { panic(fmt.Sprintf("%v already implements proto.Enum", t)) } edV1, ok := ev.(enumV1) if !ok { return aberrantLoadEnumDesc(t) } b, idxs := edV1.EnumDescriptor() var ed protoreflect.EnumDescriptor if len(idxs) == 1 { ed = legacyLoadFileDesc(b).Enums().Get(idxs[0]) } else { md := legacyLoadFileDesc(b).Messages().Get(idxs[0]) for _, i := range idxs[1 : len(idxs)-1] { md = md.Messages().Get(i) } ed = md.Enums().Get(idxs[len(idxs)-1]) } if ed, ok := legacyEnumDescCache.LoadOrStore(t, ed); ok { return ed.(protoreflect.EnumDescriptor) } return ed } var aberrantEnumDescCache sync.Map // map[reflect.Type]protoreflect.EnumDescriptor // aberrantLoadEnumDesc returns an EnumDescriptor derived from the Go type, // which must not implement protoreflect.Enum or enumV1. // // If the type does not implement enumV1, then there is no reliable // way to derive the original protobuf type information. // We are unable to use the global enum registry since it is // unfortunately keyed by the protobuf full name, which we also do not know. // Thus, this produces some bogus enum descriptor based on the Go type name. func aberrantLoadEnumDesc(t reflect.Type) protoreflect.EnumDescriptor { // Fast-path: check if an EnumDescriptor is cached for this concrete type. if ed, ok := aberrantEnumDescCache.Load(t); ok { return ed.(protoreflect.EnumDescriptor) } // Slow-path: construct a bogus, but unique EnumDescriptor. ed := &filedesc.Enum{L2: new(filedesc.EnumL2)} ed.L0.FullName = AberrantDeriveFullName(t) // e.g., github_com.user.repo.MyEnum ed.L0.ParentFile = filedesc.SurrogateProto3 ed.L1.EditionFeatures = ed.L0.ParentFile.L1.EditionFeatures ed.L2.Values.List = append(ed.L2.Values.List, filedesc.EnumValue{}) // TODO: Use the presence of a UnmarshalJSON method to determine proto2? vd := &ed.L2.Values.List[0] vd.L0.FullName = ed.L0.FullName + "_UNKNOWN" // e.g., github_com.user.repo.MyEnum_UNKNOWN vd.L0.ParentFile = ed.L0.ParentFile vd.L0.Parent = ed // TODO: We could use the String method to obtain some enum value names by // starting at 0 and print the enum until it produces invalid identifiers. // An exhaustive query is clearly impractical, but can be best-effort. if ed, ok := aberrantEnumDescCache.LoadOrStore(t, ed); ok { return ed.(protoreflect.EnumDescriptor) } return ed } // AberrantDeriveFullName derives a fully qualified protobuf name for the given Go type // The provided name is not guaranteed to be stable nor universally unique. // It should be sufficiently unique within a program. // // This is exported for testing purposes. func AberrantDeriveFullName(t reflect.Type) protoreflect.FullName { sanitize := func(r rune) rune { switch { case r == '/': return '.' case 'a' <= r && r <= 'z', 'A' <= r && r <= 'Z', '0' <= r && r <= '9': return r default: return '_' } } prefix := strings.Map(sanitize, t.PkgPath()) suffix := strings.Map(sanitize, t.Name()) if suffix == "" { suffix = fmt.Sprintf("UnknownX%X", reflect.ValueOf(t).Pointer()) } ss := append(strings.Split(prefix, "."), suffix) for i, s := range ss { if s == "" || ('0' <= s[0] && s[0] <= '9') { ss[i] = "x" + s } } return protoreflect.FullName(strings.Join(ss, ".")) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/extension.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/extension.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "sync" "sync/atomic" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // ExtensionInfo implements ExtensionType. // // This type contains a number of exported fields for legacy compatibility. // The only non-deprecated use of this type is through the methods of the // ExtensionType interface. type ExtensionInfo struct { // An ExtensionInfo may exist in several stages of initialization. // // extensionInfoUninitialized: Some or all of the legacy exported // fields may be set, but none of the unexported fields have been // initialized. This is the starting state for an ExtensionInfo // in legacy generated code. // // extensionInfoDescInit: The desc field is set, but other unexported fields // may not be initialized. Legacy exported fields may or may not be set. // This is the starting state for an ExtensionInfo in newly generated code. // // extensionInfoFullInit: The ExtensionInfo is fully initialized. // This state is only entered after lazy initialization is complete. init uint32 mu sync.Mutex goType reflect.Type desc extensionTypeDescriptor conv Converter info *extensionFieldInfo // for fast-path method implementations // ExtendedType is a typed nil-pointer to the parent message type that // is being extended. It is possible for this to be unpopulated in v2 // since the message may no longer implement the MessageV1 interface. // // Deprecated: Use the ExtendedType method instead. ExtendedType protoiface.MessageV1 // ExtensionType is the zero value of the extension type. // // For historical reasons, reflect.TypeOf(ExtensionType) and the // type returned by InterfaceOf may not be identical. // // Deprecated: Use InterfaceOf(xt.Zero()) instead. ExtensionType any // Field is the field number of the extension. // // Deprecated: Use the Descriptor().Number method instead. Field int32 // Name is the fully qualified name of extension. // // Deprecated: Use the Descriptor().FullName method instead. Name string // Tag is the protobuf struct tag used in the v1 API. // // Deprecated: Do not use. Tag string // Filename is the proto filename in which the extension is defined. // // Deprecated: Use Descriptor().ParentFile().Path() instead. Filename string } // Stages of initialization: See the ExtensionInfo.init field. const ( extensionInfoUninitialized = 0 extensionInfoDescInit = 1 extensionInfoFullInit = 2 ) func InitExtensionInfo(xi *ExtensionInfo, xd protoreflect.ExtensionDescriptor, goType reflect.Type) { xi.goType = goType xi.desc = extensionTypeDescriptor{xd, xi} xi.init = extensionInfoDescInit } func (xi *ExtensionInfo) New() protoreflect.Value { return xi.lazyInit().New() } func (xi *ExtensionInfo) Zero() protoreflect.Value { return xi.lazyInit().Zero() } func (xi *ExtensionInfo) ValueOf(v any) protoreflect.Value { return xi.lazyInit().PBValueOf(reflect.ValueOf(v)) } func (xi *ExtensionInfo) InterfaceOf(v protoreflect.Value) any { return xi.lazyInit().GoValueOf(v).Interface() } func (xi *ExtensionInfo) IsValidValue(v protoreflect.Value) bool { return xi.lazyInit().IsValidPB(v) } func (xi *ExtensionInfo) IsValidInterface(v any) bool { return xi.lazyInit().IsValidGo(reflect.ValueOf(v)) } func (xi *ExtensionInfo) TypeDescriptor() protoreflect.ExtensionTypeDescriptor { if atomic.LoadUint32(&xi.init) < extensionInfoDescInit { xi.lazyInitSlow() } return &xi.desc } func (xi *ExtensionInfo) lazyInit() Converter { if atomic.LoadUint32(&xi.init) < extensionInfoFullInit { xi.lazyInitSlow() } return xi.conv } func (xi *ExtensionInfo) lazyInitSlow() { xi.mu.Lock() defer xi.mu.Unlock() if xi.init == extensionInfoFullInit { return } defer atomic.StoreUint32(&xi.init, extensionInfoFullInit) if xi.desc.ExtensionDescriptor == nil { xi.initFromLegacy() } if !xi.desc.ExtensionDescriptor.IsPlaceholder() { if xi.ExtensionType == nil { xi.initToLegacy() } xi.conv = NewConverter(xi.goType, xi.desc.ExtensionDescriptor) xi.info = makeExtensionFieldInfo(xi.desc.ExtensionDescriptor) xi.info.validation = newValidationInfo(xi.desc.ExtensionDescriptor, xi.goType) } } type extensionTypeDescriptor struct { protoreflect.ExtensionDescriptor xi *ExtensionInfo } func (xtd *extensionTypeDescriptor) Type() protoreflect.ExtensionType { return xtd.xi } func (xtd *extensionTypeDescriptor) Descriptor() protoreflect.ExtensionDescriptor { return xtd.ExtensionDescriptor }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/api_export.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/api_export.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strconv" "google.golang.org/protobuf/encoding/prototext" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Export is a zero-length named type that exists only to export a set of // functions that we do not want to appear in godoc. type Export struct{} // NewError formats a string according to the format specifier and arguments and // returns an error that has a "proto" prefix. func (Export) NewError(f string, x ...any) error { return errors.New(f, x...) } // enum is any enum type generated by protoc-gen-go // and must be a named int32 type. type enum = any // EnumOf returns the protoreflect.Enum interface over e. // It returns nil if e is nil. func (Export) EnumOf(e enum) protoreflect.Enum { switch e := e.(type) { case nil: return nil case protoreflect.Enum: return e default: return legacyWrapEnum(reflect.ValueOf(e)) } } // EnumDescriptorOf returns the protoreflect.EnumDescriptor for e. // It returns nil if e is nil. func (Export) EnumDescriptorOf(e enum) protoreflect.EnumDescriptor { switch e := e.(type) { case nil: return nil case protoreflect.Enum: return e.Descriptor() default: return LegacyLoadEnumDesc(reflect.TypeOf(e)) } } // EnumTypeOf returns the protoreflect.EnumType for e. // It returns nil if e is nil. func (Export) EnumTypeOf(e enum) protoreflect.EnumType { switch e := e.(type) { case nil: return nil case protoreflect.Enum: return e.Type() default: return legacyLoadEnumType(reflect.TypeOf(e)) } } // EnumStringOf returns the enum value as a string, either as the name if // the number is resolvable, or the number formatted as a string. func (Export) EnumStringOf(ed protoreflect.EnumDescriptor, n protoreflect.EnumNumber) string { ev := ed.Values().ByNumber(n) if ev != nil { return string(ev.Name()) } return strconv.Itoa(int(n)) } // message is any message type generated by protoc-gen-go // and must be a pointer to a named struct type. type message = any // legacyMessageWrapper wraps a v2 message as a v1 message. type legacyMessageWrapper struct{ m protoreflect.ProtoMessage } func (m legacyMessageWrapper) Reset() { proto.Reset(m.m) } func (m legacyMessageWrapper) String() string { return Export{}.MessageStringOf(m.m) } func (m legacyMessageWrapper) ProtoMessage() {} // ProtoMessageV1Of converts either a v1 or v2 message to a v1 message. // It returns nil if m is nil. func (Export) ProtoMessageV1Of(m message) protoiface.MessageV1 { switch mv := m.(type) { case nil: return nil case protoiface.MessageV1: return mv case unwrapper: return Export{}.ProtoMessageV1Of(mv.protoUnwrap()) case protoreflect.ProtoMessage: return legacyMessageWrapper{mv} default: panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m)) } } func (Export) protoMessageV2Of(m message) protoreflect.ProtoMessage { switch mv := m.(type) { case nil: return nil case protoreflect.ProtoMessage: return mv case legacyMessageWrapper: return mv.m case protoiface.MessageV1: return nil default: panic(fmt.Sprintf("message %T is neither a v1 or v2 Message", m)) } } // ProtoMessageV2Of converts either a v1 or v2 message to a v2 message. // It returns nil if m is nil. func (Export) ProtoMessageV2Of(m message) protoreflect.ProtoMessage { if m == nil { return nil } if mv := (Export{}).protoMessageV2Of(m); mv != nil { return mv } return legacyWrapMessage(reflect.ValueOf(m)).Interface() } // MessageOf returns the protoreflect.Message interface over m. // It returns nil if m is nil. func (Export) MessageOf(m message) protoreflect.Message { if m == nil { return nil } if mv := (Export{}).protoMessageV2Of(m); mv != nil { return mv.ProtoReflect() } return legacyWrapMessage(reflect.ValueOf(m)) } // MessageDescriptorOf returns the protoreflect.MessageDescriptor for m. // It returns nil if m is nil. func (Export) MessageDescriptorOf(m message) protoreflect.MessageDescriptor { if m == nil { return nil } if mv := (Export{}).protoMessageV2Of(m); mv != nil { return mv.ProtoReflect().Descriptor() } return LegacyLoadMessageDesc(reflect.TypeOf(m)) } // MessageTypeOf returns the protoreflect.MessageType for m. // It returns nil if m is nil. func (Export) MessageTypeOf(m message) protoreflect.MessageType { if m == nil { return nil } if mv := (Export{}).protoMessageV2Of(m); mv != nil { return mv.ProtoReflect().Type() } return legacyLoadMessageType(reflect.TypeOf(m), "") } // MessageStringOf returns the message value as a string, // which is the message serialized in the protobuf text format. func (Export) MessageStringOf(m protoreflect.ProtoMessage) string { return prototext.MarshalOptions{Multiline: false}.Format(m) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_map.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_map.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "sort" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/reflect/protoreflect" ) type mapInfo struct { goType reflect.Type keyWiretag uint64 valWiretag uint64 keyFuncs valueCoderFuncs valFuncs valueCoderFuncs keyZero protoreflect.Value keyKind protoreflect.Kind conv *mapConverter } func encoderFuncsForMap(fd protoreflect.FieldDescriptor, ft reflect.Type) (valueMessage *MessageInfo, funcs pointerCoderFuncs) { // TODO: Consider generating specialized map coders. keyField := fd.MapKey() valField := fd.MapValue() keyWiretag := protowire.EncodeTag(1, wireTypes[keyField.Kind()]) valWiretag := protowire.EncodeTag(2, wireTypes[valField.Kind()]) keyFuncs := encoderFuncsForValue(keyField) valFuncs := encoderFuncsForValue(valField) conv := newMapConverter(ft, fd) mapi := &mapInfo{ goType: ft, keyWiretag: keyWiretag, valWiretag: valWiretag, keyFuncs: keyFuncs, valFuncs: valFuncs, keyZero: keyField.Default(), keyKind: keyField.Kind(), conv: conv, } if valField.Kind() == protoreflect.MessageKind { valueMessage = getMessageInfo(ft.Elem()) } funcs = pointerCoderFuncs{ size: func(p pointer, f *coderFieldInfo, opts marshalOptions) int { return sizeMap(p.AsValueOf(ft).Elem(), mapi, f, opts) }, marshal: func(b []byte, p pointer, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { return appendMap(b, p.AsValueOf(ft).Elem(), mapi, f, opts) }, unmarshal: func(b []byte, p pointer, wtyp protowire.Type, f *coderFieldInfo, opts unmarshalOptions) (unmarshalOutput, error) { mp := p.AsValueOf(ft) if mp.Elem().IsNil() { mp.Elem().Set(reflect.MakeMap(mapi.goType)) } if f.mi == nil { return consumeMap(b, mp.Elem(), wtyp, mapi, f, opts) } else { return consumeMapOfMessage(b, mp.Elem(), wtyp, mapi, f, opts) } }, } switch valField.Kind() { case protoreflect.MessageKind: funcs.merge = mergeMapOfMessage case protoreflect.BytesKind: funcs.merge = mergeMapOfBytes default: funcs.merge = mergeMap } if valFuncs.isInit != nil { funcs.isInit = func(p pointer, f *coderFieldInfo) error { return isInitMap(p.AsValueOf(ft).Elem(), mapi, f) } } return valueMessage, funcs } const ( mapKeyTagSize = 1 // field 1, tag size 1. mapValTagSize = 1 // field 2, tag size 2. ) func sizeMap(mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) int { if mapv.Len() == 0 { return 0 } n := 0 iter := mapv.MapRange() for iter.Next() { key := mapi.conv.keyConv.PBValueOf(iter.Key()).MapKey() keySize := mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) var valSize int value := mapi.conv.valConv.PBValueOf(iter.Value()) if f.mi == nil { valSize = mapi.valFuncs.size(value, mapValTagSize, opts) } else { p := pointerOfValue(iter.Value()) valSize += mapValTagSize valSize += protowire.SizeBytes(f.mi.sizePointer(p, opts)) } n += f.tagsize + protowire.SizeBytes(keySize+valSize) } return n } func consumeMap(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } b, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } var ( key = mapi.keyZero val = mapi.conv.valConv.New() ) for len(b) > 0 { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return out, errDecode } if num > protowire.MaxValidNumber { return out, errDecode } b = b[n:] err := errUnknown switch num { case genid.MapEntry_Key_field_number: var v protoreflect.Value var o unmarshalOutput v, o, err = mapi.keyFuncs.unmarshal(b, key, num, wtyp, opts) if err != nil { break } key = v n = o.n case genid.MapEntry_Value_field_number: var v protoreflect.Value var o unmarshalOutput v, o, err = mapi.valFuncs.unmarshal(b, val, num, wtyp, opts) if err != nil { break } val = v n = o.n } if err == errUnknown { n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return out, errDecode } } else if err != nil { return out, err } b = b[n:] } mapv.SetMapIndex(mapi.conv.keyConv.GoValueOf(key), mapi.conv.valConv.GoValueOf(val)) out.n = n return out, nil } func consumeMapOfMessage(b []byte, mapv reflect.Value, wtyp protowire.Type, mapi *mapInfo, f *coderFieldInfo, opts unmarshalOptions) (out unmarshalOutput, err error) { if wtyp != protowire.BytesType { return out, errUnknown } b, n := protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } var ( key = mapi.keyZero val = reflect.New(f.mi.GoReflectType.Elem()) ) for len(b) > 0 { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return out, errDecode } if num > protowire.MaxValidNumber { return out, errDecode } b = b[n:] err := errUnknown switch num { case 1: var v protoreflect.Value var o unmarshalOutput v, o, err = mapi.keyFuncs.unmarshal(b, key, num, wtyp, opts) if err != nil { break } key = v n = o.n case 2: if wtyp != protowire.BytesType { break } var v []byte v, n = protowire.ConsumeBytes(b) if n < 0 { return out, errDecode } var o unmarshalOutput o, err = f.mi.unmarshalPointer(v, pointerOfValue(val), 0, opts) if o.initialized { // Consider this map item initialized so long as we see // an initialized value. out.initialized = true } } if err == errUnknown { n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return out, errDecode } } else if err != nil { return out, err } b = b[n:] } mapv.SetMapIndex(mapi.conv.keyConv.GoValueOf(key), val) out.n = n return out, nil } func appendMapItem(b []byte, keyrv, valrv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { if f.mi == nil { key := mapi.conv.keyConv.PBValueOf(keyrv).MapKey() val := mapi.conv.valConv.PBValueOf(valrv) size := 0 size += mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) size += mapi.valFuncs.size(val, mapValTagSize, opts) b = protowire.AppendVarint(b, uint64(size)) before := len(b) b, err := mapi.keyFuncs.marshal(b, key.Value(), mapi.keyWiretag, opts) if err != nil { return nil, err } b, err = mapi.valFuncs.marshal(b, val, mapi.valWiretag, opts) if measuredSize := len(b) - before; size != measuredSize && err == nil { return nil, errors.MismatchedSizeCalculation(size, measuredSize) } return b, err } else { key := mapi.conv.keyConv.PBValueOf(keyrv).MapKey() val := pointerOfValue(valrv) valSize := f.mi.sizePointer(val, opts) size := 0 size += mapi.keyFuncs.size(key.Value(), mapKeyTagSize, opts) size += mapValTagSize + protowire.SizeBytes(valSize) b = protowire.AppendVarint(b, uint64(size)) b, err := mapi.keyFuncs.marshal(b, key.Value(), mapi.keyWiretag, opts) if err != nil { return nil, err } b = protowire.AppendVarint(b, mapi.valWiretag) b = protowire.AppendVarint(b, uint64(valSize)) before := len(b) b, err = f.mi.marshalAppendPointer(b, val, opts) if measuredSize := len(b) - before; valSize != measuredSize && err == nil { return nil, errors.MismatchedSizeCalculation(valSize, measuredSize) } return b, err } } func appendMap(b []byte, mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { if mapv.Len() == 0 { return b, nil } if opts.Deterministic() { return appendMapDeterministic(b, mapv, mapi, f, opts) } iter := mapv.MapRange() for iter.Next() { var err error b = protowire.AppendVarint(b, f.wiretag) b, err = appendMapItem(b, iter.Key(), iter.Value(), mapi, f, opts) if err != nil { return b, err } } return b, nil } func appendMapDeterministic(b []byte, mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo, opts marshalOptions) ([]byte, error) { keys := mapv.MapKeys() sort.Slice(keys, func(i, j int) bool { switch keys[i].Kind() { case reflect.Bool: return !keys[i].Bool() && keys[j].Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return keys[i].Int() < keys[j].Int() case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return keys[i].Uint() < keys[j].Uint() case reflect.Float32, reflect.Float64: return keys[i].Float() < keys[j].Float() case reflect.String: return keys[i].String() < keys[j].String() default: panic("invalid kind: " + keys[i].Kind().String()) } }) for _, key := range keys { var err error b = protowire.AppendVarint(b, f.wiretag) b, err = appendMapItem(b, key, mapv.MapIndex(key), mapi, f, opts) if err != nil { return b, err } } return b, nil } func isInitMap(mapv reflect.Value, mapi *mapInfo, f *coderFieldInfo) error { if mi := f.mi; mi != nil { mi.init() if !mi.needsInitCheck { return nil } iter := mapv.MapRange() for iter.Next() { val := pointerOfValue(iter.Value()) if err := mi.checkInitializedPointer(val); err != nil { return err } } } else { iter := mapv.MapRange() for iter.Next() { val := mapi.conv.valConv.PBValueOf(iter.Value()) if err := mapi.valFuncs.isInit(val); err != nil { return err } } } return nil } func mergeMap(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { dstm := dst.AsValueOf(f.ft).Elem() srcm := src.AsValueOf(f.ft).Elem() if srcm.Len() == 0 { return } if dstm.IsNil() { dstm.Set(reflect.MakeMap(f.ft)) } iter := srcm.MapRange() for iter.Next() { dstm.SetMapIndex(iter.Key(), iter.Value()) } } func mergeMapOfBytes(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { dstm := dst.AsValueOf(f.ft).Elem() srcm := src.AsValueOf(f.ft).Elem() if srcm.Len() == 0 { return } if dstm.IsNil() { dstm.Set(reflect.MakeMap(f.ft)) } iter := srcm.MapRange() for iter.Next() { dstm.SetMapIndex(iter.Key(), reflect.ValueOf(append(emptyBuf[:], iter.Value().Bytes()...))) } } func mergeMapOfMessage(dst, src pointer, f *coderFieldInfo, opts mergeOptions) { dstm := dst.AsValueOf(f.ft).Elem() srcm := src.AsValueOf(f.ft).Elem() if srcm.Len() == 0 { return } if dstm.IsNil() { dstm.Set(reflect.MakeMap(f.ft)) } iter := srcm.MapRange() for iter.Next() { val := reflect.New(f.ft.Elem().Elem()) if f.mi != nil { f.mi.mergePointer(pointerOfValue(val), pointerOfValue(iter.Value()), opts) } else { opts.Merge(asMessage(val), asMessage(iter.Value())) } dstm.SetMapIndex(iter.Key(), val) } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/api_export_opaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/api_export_opaque.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "strconv" "sync/atomic" "unsafe" "google.golang.org/protobuf/reflect/protoreflect" ) func (Export) UnmarshalField(msg any, fieldNum int32) { UnmarshalField(msg.(protoreflect.ProtoMessage).ProtoReflect(), protoreflect.FieldNumber(fieldNum)) } // Present checks the presence set for a certain field number (zero // based, ordered by appearance in original proto file). part is // a pointer to the correct element in the bitmask array, num is the // field number unaltered. Example (field number 70 -> part = // &m.XXX_presence[1], num = 70) func (Export) Present(part *uint32, num uint32) bool { // This hook will read an unprotected shadow presence set if // we're unning under the race detector raceDetectHookPresent(part, num) return atomic.LoadUint32(part)&(1<<(num%32)) > 0 } // SetPresent adds a field to the presence set. part is a pointer to // the relevant element in the array and num is the field number // unaltered. size is the number of fields in the protocol // buffer. func (Export) SetPresent(part *uint32, num uint32, size uint32) { // This hook will mutate an unprotected shadow presence set if // we're running under the race detector raceDetectHookSetPresent(part, num, presenceSize(size)) for { old := atomic.LoadUint32(part) if atomic.CompareAndSwapUint32(part, old, old|(1<<(num%32))) { return } } } // SetPresentNonAtomic is like SetPresent, but operates non-atomically. // It is meant for use by builder methods, where the message is known not // to be accessible yet by other goroutines. func (Export) SetPresentNonAtomic(part *uint32, num uint32, size uint32) { // This hook will mutate an unprotected shadow presence set if // we're running under the race detector raceDetectHookSetPresent(part, num, presenceSize(size)) *part |= 1 << (num % 32) } // ClearPresence removes a field from the presence set. part is a // pointer to the relevant element in the presence array and num is // the field number unaltered. func (Export) ClearPresent(part *uint32, num uint32) { // This hook will mutate an unprotected shadow presence set if // we're running under the race detector raceDetectHookClearPresent(part, num) for { old := atomic.LoadUint32(part) if atomic.CompareAndSwapUint32(part, old, old&^(1<<(num%32))) { return } } } // interfaceToPointer takes a pointer to an empty interface whose value is a // pointer type, and converts it into a "pointer" that points to the same // target func interfaceToPointer(i *any) pointer { return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]} } func (p pointer) atomicGetPointer() pointer { return pointer{p: atomic.LoadPointer((*unsafe.Pointer)(p.p))} } func (p pointer) atomicSetPointer(q pointer) { atomic.StorePointer((*unsafe.Pointer)(p.p), q.p) } // AtomicCheckPointerIsNil takes an interface (which is a pointer to a // pointer) and returns true if the pointed-to pointer is nil (using an // atomic load). This function is inlineable and, on x86, just becomes a // simple load and compare. func (Export) AtomicCheckPointerIsNil(ptr any) bool { return interfaceToPointer(&ptr).atomicGetPointer().IsNil() } // AtomicSetPointer takes two interfaces (first is a pointer to a pointer, // second is a pointer) and atomically sets the second pointer into location // referenced by first pointer. Unfortunately, atomicSetPointer() does not inline // (even on x86), so this does not become a simple store on x86. func (Export) AtomicSetPointer(dstPtr, valPtr any) { interfaceToPointer(&dstPtr).atomicSetPointer(interfaceToPointer(&valPtr)) } // AtomicLoadPointer loads the pointer at the location pointed at by src, // and stores that pointer value into the location pointed at by dst. func (Export) AtomicLoadPointer(ptr Pointer, dst Pointer) { *(*unsafe.Pointer)(unsafe.Pointer(dst)) = atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(ptr))) } // AtomicInitializePointer makes ptr and dst point to the same value. // // If *ptr is a nil pointer, it sets *ptr = *dst. // // If *ptr is a non-nil pointer, it sets *dst = *ptr. func (Export) AtomicInitializePointer(ptr Pointer, dst Pointer) { if !atomic.CompareAndSwapPointer((*unsafe.Pointer)(ptr), unsafe.Pointer(nil), *(*unsafe.Pointer)(dst)) { *(*unsafe.Pointer)(unsafe.Pointer(dst)) = atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(ptr))) } } // MessageFieldStringOf returns the field formatted as a string, // either as the field name if resolvable otherwise as a decimal string. func (Export) MessageFieldStringOf(md protoreflect.MessageDescriptor, n protoreflect.FieldNumber) string { fd := md.Fields().ByNumber(n) if fd != nil { return string(fd.Name()) } return strconv.Itoa(int(n)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert_map.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/convert_map.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) type mapConverter struct { goType reflect.Type // map[K]V keyConv, valConv Converter } func newMapConverter(t reflect.Type, fd protoreflect.FieldDescriptor) *mapConverter { if t.Kind() != reflect.Map { panic(fmt.Sprintf("invalid Go type %v for field %v", t, fd.FullName())) } return &mapConverter{ goType: t, keyConv: newSingularConverter(t.Key(), fd.MapKey()), valConv: newSingularConverter(t.Elem(), fd.MapValue()), } } func (c *mapConverter) PBValueOf(v reflect.Value) protoreflect.Value { if v.Type() != c.goType { panic(fmt.Sprintf("invalid type: got %v, want %v", v.Type(), c.goType)) } return protoreflect.ValueOfMap(&mapReflect{v, c.keyConv, c.valConv}) } func (c *mapConverter) GoValueOf(v protoreflect.Value) reflect.Value { return v.Map().(*mapReflect).v } func (c *mapConverter) IsValidPB(v protoreflect.Value) bool { mapv, ok := v.Interface().(*mapReflect) if !ok { return false } return mapv.v.Type() == c.goType } func (c *mapConverter) IsValidGo(v reflect.Value) bool { return v.IsValid() && v.Type() == c.goType } func (c *mapConverter) New() protoreflect.Value { return c.PBValueOf(reflect.MakeMap(c.goType)) } func (c *mapConverter) Zero() protoreflect.Value { return c.PBValueOf(reflect.Zero(c.goType)) } type mapReflect struct { v reflect.Value // map[K]V keyConv Converter valConv Converter } func (ms *mapReflect) Len() int { return ms.v.Len() } func (ms *mapReflect) Has(k protoreflect.MapKey) bool { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.v.MapIndex(rk) return rv.IsValid() } func (ms *mapReflect) Get(k protoreflect.MapKey) protoreflect.Value { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.v.MapIndex(rk) if !rv.IsValid() { return protoreflect.Value{} } return ms.valConv.PBValueOf(rv) } func (ms *mapReflect) Set(k protoreflect.MapKey, v protoreflect.Value) { rk := ms.keyConv.GoValueOf(k.Value()) rv := ms.valConv.GoValueOf(v) ms.v.SetMapIndex(rk, rv) } func (ms *mapReflect) Clear(k protoreflect.MapKey) { rk := ms.keyConv.GoValueOf(k.Value()) ms.v.SetMapIndex(rk, reflect.Value{}) } func (ms *mapReflect) Mutable(k protoreflect.MapKey) protoreflect.Value { if _, ok := ms.valConv.(*messageConverter); !ok { panic("invalid Mutable on map with non-message value type") } v := ms.Get(k) if !v.IsValid() { v = ms.NewValue() ms.Set(k, v) } return v } func (ms *mapReflect) Range(f func(protoreflect.MapKey, protoreflect.Value) bool) { iter := ms.v.MapRange() for iter.Next() { k := ms.keyConv.PBValueOf(iter.Key()).MapKey() v := ms.valConv.PBValueOf(iter.Value()) if !f(k, v) { return } } } func (ms *mapReflect) NewValue() protoreflect.Value { return ms.valConv.New() } func (ms *mapReflect) IsValid() bool { return !ms.v.IsNil() } func (ms *mapReflect) protoUnwrap() any { return ms.v.Interface() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_opaque_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_opaque_gen.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package impl import ( "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) func getterForOpaqueNullableScalar(mi *MessageInfo, index uint32, fd protoreflect.FieldDescriptor, fs reflect.StructField, conv Converter, fieldOffset offset) func(p pointer) protoreflect.Value { ft := fs.Type if ft.Kind() == reflect.Ptr { ft = ft.Elem() } if fd.Kind() == protoreflect.EnumKind { // Enums for nullable opaque types. return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } rv := p.Apply(fieldOffset).AsValueOf(fs.Type).Elem() return conv.PBValueOf(rv) } } switch ft.Kind() { case reflect.Bool: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Bool() return protoreflect.ValueOfBool(*x) } case reflect.Int32: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Int32() return protoreflect.ValueOfInt32(*x) } case reflect.Uint32: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Uint32() return protoreflect.ValueOfUint32(*x) } case reflect.Int64: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Int64() return protoreflect.ValueOfInt64(*x) } case reflect.Uint64: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Uint64() return protoreflect.ValueOfUint64(*x) } case reflect.Float32: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Float32() return protoreflect.ValueOfFloat32(*x) } case reflect.Float64: return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Float64() return protoreflect.ValueOfFloat64(*x) } case reflect.String: if fd.Kind() == protoreflect.BytesKind { return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).StringPtr() if *x == nil { return conv.Zero() } if len(**x) == 0 { return protoreflect.ValueOfBytes(nil) } return protoreflect.ValueOfBytes([]byte(**x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).StringPtr() if *x == nil { return conv.Zero() } return protoreflect.ValueOfString(**x) } case reflect.Slice: if fd.Kind() == protoreflect.StringKind { return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() return protoreflect.ValueOfString(string(*x)) } } return func(p pointer) protoreflect.Value { if p.IsNil() || !mi.present(p, index) { return conv.Zero() } x := p.Apply(fieldOffset).Bytes() return protoreflect.ValueOfBytes(*x) } } panic("unexpected protobuf kind: " + ft.Kind().String()) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/enum.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/enum.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "google.golang.org/protobuf/reflect/protoreflect" ) type EnumInfo struct { GoReflectType reflect.Type // int32 kind Desc protoreflect.EnumDescriptor } func (t *EnumInfo) New(n protoreflect.EnumNumber) protoreflect.Enum { return reflect.ValueOf(n).Convert(t.GoReflectType).Interface().(protoreflect.Enum) } func (t *EnumInfo) Descriptor() protoreflect.EnumDescriptor { return t.Desc }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/presence.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/presence.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "sync/atomic" "unsafe" ) // presenceSize represents the size of a presence set, which should be the largest index of the set+1 type presenceSize uint32 // presence is the internal representation of the bitmap array in a generated protobuf type presence struct { // This is a pointer to the beginning of an array of uint32 P unsafe.Pointer } func (p presence) toElem(num uint32) (ret *uint32) { const ( bitsPerByte = 8 siz = unsafe.Sizeof(*ret) ) // p.P points to an array of uint32, num is the bit in this array that the // caller wants to check/manipulate. Calculate the index in the array that // contains this specific bit. E.g.: 76 / 32 = 2 (integer division). offset := uintptr(num) / (siz * bitsPerByte) * siz return (*uint32)(unsafe.Pointer(uintptr(p.P) + offset)) } // Present checks for the presence of a specific field number in a presence set. func (p presence) Present(num uint32) bool { return Export{}.Present(p.toElem(num), num) } // SetPresent adds presence for a specific field number in a presence set. func (p presence) SetPresent(num uint32, size presenceSize) { Export{}.SetPresent(p.toElem(num), num, uint32(size)) } // SetPresentUnatomic adds presence for a specific field number in a presence set without using // atomic operations. Only to be called during unmarshaling. func (p presence) SetPresentUnatomic(num uint32, size presenceSize) { Export{}.SetPresentNonAtomic(p.toElem(num), num, uint32(size)) } // ClearPresent removes presence for a specific field number in a presence set. func (p presence) ClearPresent(num uint32) { Export{}.ClearPresent(p.toElem(num), num) } // LoadPresenceCache (together with PresentInCache) allows for a // cached version of checking for presence without re-reading the word // for every field. It is optimized for efficiency and assumes no // simltaneous mutation of the presence set (or at least does not have // a problem with simultaneous mutation giving inconsistent results). func (p presence) LoadPresenceCache() (current uint32) { if p.P == nil { return 0 } return atomic.LoadUint32((*uint32)(p.P)) } // PresentInCache reads presence from a cached word in the presence // bitmap. It caches up a new word if the bit is outside the // word. This is for really fast iteration through bitmaps in cases // where we either know that the bitmap will not be altered, or we // don't care about inconsistencies caused by simultaneous writes. func (p presence) PresentInCache(num uint32, cachedElement *uint32, current *uint32) bool { if num/32 != *cachedElement { o := uintptr(num/32) * unsafe.Sizeof(uint32(0)) q := (*uint32)(unsafe.Pointer(uintptr(p.P) + o)) *current = atomic.LoadUint32(q) *cachedElement = num / 32 } return (*current & (1 << (num % 32))) > 0 } // AnyPresent checks if any field is marked as present in the bitmap. func (p presence) AnyPresent(size presenceSize) bool { n := uintptr((size + 31) / 32) for j := uintptr(0); j < n; j++ { o := j * unsafe.Sizeof(uint32(0)) q := (*uint32)(unsafe.Pointer(uintptr(p.P) + o)) b := atomic.LoadUint32(q) if b > 0 { return true } } return false } // toRaceDetectData finds the preceding RaceDetectHookData in a // message by using pointer arithmetic. As the type of the presence // set (bitmap) varies with the number of fields in the protobuf, we // can not have a struct type containing the array and the // RaceDetectHookData. instead the RaceDetectHookData is placed // immediately before the bitmap array, and we find it by walking // backwards in the struct. // // This method is only called from the race-detect version of the code, // so RaceDetectHookData is never an empty struct. func (p presence) toRaceDetectData() *RaceDetectHookData { var template struct { d RaceDetectHookData a [1]uint32 } o := (uintptr(unsafe.Pointer(&template.a)) - uintptr(unsafe.Pointer(&template.d))) return (*RaceDetectHookData)(unsafe.Pointer(uintptr(p.P) - o)) } func atomicLoadShadowPresence(p **[]byte) *[]byte { return (*[]byte)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreShadowPresence(p **[]byte, v *[]byte) { atomic.CompareAndSwapPointer((*unsafe.Pointer)(unsafe.Pointer(p)), nil, unsafe.Pointer(v)) } // findPointerToRaceDetectData finds the preceding RaceDetectHookData // in a message by using pointer arithmetic. For the methods called // directy from generated code, we don't have a pointer to the // beginning of the presence set, but a pointer inside the array. As // we know the index of the bit we're manipulating (num), we can // calculate which element of the array ptr is pointing to. With that // information we find the preceding RaceDetectHookData and can // manipulate the shadow bitmap. // // This method is only called from the race-detect version of the // code, so RaceDetectHookData is never an empty struct. func findPointerToRaceDetectData(ptr *uint32, num uint32) *RaceDetectHookData { var template struct { d RaceDetectHookData a [1]uint32 } o := (uintptr(unsafe.Pointer(&template.a)) - uintptr(unsafe.Pointer(&template.d))) + uintptr(num/32)*unsafe.Sizeof(uint32(0)) return (*RaceDetectHookData)(unsafe.Pointer(uintptr(unsafe.Pointer(ptr)) - o)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "strconv" "strings" "sync" "sync/atomic" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/reflect/protoreflect" ) // MessageInfo provides protobuf related functionality for a given Go type // that represents a message. A given instance of MessageInfo is tied to // exactly one Go type, which must be a pointer to a struct type. // // The exported fields must be populated before any methods are called // and cannot be mutated after set. type MessageInfo struct { // GoReflectType is the underlying message Go type and must be populated. GoReflectType reflect.Type // pointer to struct // Desc is the underlying message descriptor type and must be populated. Desc protoreflect.MessageDescriptor // Deprecated: Exporter will be removed the next time we bump // protoimpl.GenVersion. See https://github.com/golang/protobuf/issues/1640 Exporter exporter // OneofWrappers is list of pointers to oneof wrapper struct types. OneofWrappers []any initMu sync.Mutex // protects all unexported fields initDone uint32 reflectMessageInfo // for reflection implementation coderMessageInfo // for fast-path method implementations } // exporter is a function that returns a reference to the ith field of v, // where v is a pointer to a struct. It returns nil if it does not support // exporting the requested field (e.g., already exported). type exporter func(v any, i int) any // getMessageInfo returns the MessageInfo for any message type that // is generated by our implementation of protoc-gen-go (for v2 and on). // If it is unable to obtain a MessageInfo, it returns nil. func getMessageInfo(mt reflect.Type) *MessageInfo { m, ok := reflect.Zero(mt).Interface().(protoreflect.ProtoMessage) if !ok { return nil } mr, ok := m.ProtoReflect().(interface{ ProtoMessageInfo() *MessageInfo }) if !ok { return nil } return mr.ProtoMessageInfo() } func (mi *MessageInfo) init() { // This function is called in the hot path. Inline the sync.Once logic, // since allocating a closure for Once.Do is expensive. // Keep init small to ensure that it can be inlined. if atomic.LoadUint32(&mi.initDone) == 0 { mi.initOnce() } } func (mi *MessageInfo) initOnce() { mi.initMu.Lock() defer mi.initMu.Unlock() if mi.initDone == 1 { return } if opaqueInitHook(mi) { return } t := mi.GoReflectType if t.Kind() != reflect.Ptr && t.Elem().Kind() != reflect.Struct { panic(fmt.Sprintf("got %v, want *struct kind", t)) } t = t.Elem() si := mi.makeStructInfo(t) mi.makeReflectFuncs(t, si) mi.makeCoderMethods(t, si) atomic.StoreUint32(&mi.initDone, 1) } // getPointer returns the pointer for a message, which should be of // the type of the MessageInfo. If the message is of a different type, // it returns ok==false. func (mi *MessageInfo) getPointer(m protoreflect.Message) (p pointer, ok bool) { switch m := m.(type) { case *messageState: return m.pointer(), m.messageInfo() == mi case *messageReflectWrapper: return m.pointer(), m.messageInfo() == mi } return pointer{}, false } type ( SizeCache = int32 WeakFields = map[int32]protoreflect.ProtoMessage UnknownFields = unknownFieldsA // TODO: switch to unknownFieldsB unknownFieldsA = []byte unknownFieldsB = *[]byte ExtensionFields = map[int32]ExtensionField ) var ( sizecacheType = reflect.TypeOf(SizeCache(0)) unknownFieldsAType = reflect.TypeOf(unknownFieldsA(nil)) unknownFieldsBType = reflect.TypeOf(unknownFieldsB(nil)) extensionFieldsType = reflect.TypeOf(ExtensionFields(nil)) ) type structInfo struct { sizecacheOffset offset sizecacheType reflect.Type unknownOffset offset unknownType reflect.Type extensionOffset offset extensionType reflect.Type lazyOffset offset presenceOffset offset fieldsByNumber map[protoreflect.FieldNumber]reflect.StructField oneofsByName map[protoreflect.Name]reflect.StructField oneofWrappersByType map[reflect.Type]protoreflect.FieldNumber oneofWrappersByNumber map[protoreflect.FieldNumber]reflect.Type } func (mi *MessageInfo) makeStructInfo(t reflect.Type) structInfo { si := structInfo{ sizecacheOffset: invalidOffset, unknownOffset: invalidOffset, extensionOffset: invalidOffset, lazyOffset: invalidOffset, presenceOffset: invalidOffset, fieldsByNumber: map[protoreflect.FieldNumber]reflect.StructField{}, oneofsByName: map[protoreflect.Name]reflect.StructField{}, oneofWrappersByType: map[reflect.Type]protoreflect.FieldNumber{}, oneofWrappersByNumber: map[protoreflect.FieldNumber]reflect.Type{}, } fieldLoop: for i := 0; i < t.NumField(); i++ { switch f := t.Field(i); f.Name { case genid.SizeCache_goname, genid.SizeCacheA_goname: if f.Type == sizecacheType { si.sizecacheOffset = offsetOf(f) si.sizecacheType = f.Type } case genid.UnknownFields_goname, genid.UnknownFieldsA_goname: if f.Type == unknownFieldsAType || f.Type == unknownFieldsBType { si.unknownOffset = offsetOf(f) si.unknownType = f.Type } case genid.ExtensionFields_goname, genid.ExtensionFieldsA_goname, genid.ExtensionFieldsB_goname: if f.Type == extensionFieldsType { si.extensionOffset = offsetOf(f) si.extensionType = f.Type } case "lazyFields", "XXX_lazyUnmarshalInfo": si.lazyOffset = offsetOf(f) case "XXX_presence": si.presenceOffset = offsetOf(f) default: for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { if len(s) > 0 && strings.Trim(s, "0123456789") == "" { n, _ := strconv.ParseUint(s, 10, 64) si.fieldsByNumber[protoreflect.FieldNumber(n)] = f continue fieldLoop } } if s := f.Tag.Get("protobuf_oneof"); len(s) > 0 { si.oneofsByName[protoreflect.Name(s)] = f continue fieldLoop } } } // Derive a mapping of oneof wrappers to fields. oneofWrappers := mi.OneofWrappers methods := make([]reflect.Method, 0, 2) if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofFuncs"); ok { methods = append(methods, m) } if m, ok := reflect.PtrTo(t).MethodByName("XXX_OneofWrappers"); ok { methods = append(methods, m) } for _, fn := range methods { for _, v := range fn.Func.Call([]reflect.Value{reflect.Zero(fn.Type.In(0))}) { if vs, ok := v.Interface().([]any); ok { oneofWrappers = vs } } } for _, v := range oneofWrappers { tf := reflect.TypeOf(v).Elem() f := tf.Field(0) for _, s := range strings.Split(f.Tag.Get("protobuf"), ",") { if len(s) > 0 && strings.Trim(s, "0123456789") == "" { n, _ := strconv.ParseUint(s, 10, 64) si.oneofWrappersByType[tf] = protoreflect.FieldNumber(n) si.oneofWrappersByNumber[protoreflect.FieldNumber(n)] = tf break } } } return si } func (mi *MessageInfo) New() protoreflect.Message { m := reflect.New(mi.GoReflectType.Elem()).Interface() if r, ok := m.(protoreflect.ProtoMessage); ok { return r.ProtoReflect() } return mi.MessageOf(m) } func (mi *MessageInfo) Zero() protoreflect.Message { return mi.MessageOf(reflect.Zero(mi.GoReflectType).Interface()) } func (mi *MessageInfo) Descriptor() protoreflect.MessageDescriptor { return mi.Desc } func (mi *MessageInfo) Enum(i int) protoreflect.EnumType { mi.init() fd := mi.Desc.Fields().Get(i) return Export{}.EnumTypeOf(mi.fieldTypes[fd.Number()]) } func (mi *MessageInfo) Message(i int) protoreflect.MessageType { mi.init() fd := mi.Desc.Fields().Get(i) switch { case fd.IsMap(): return mapEntryType{fd.Message(), mi.fieldTypes[fd.Number()]} default: return Export{}.MessageTypeOf(mi.fieldTypes[fd.Number()]) } } type mapEntryType struct { desc protoreflect.MessageDescriptor valType any // zero value of enum or message type } func (mt mapEntryType) New() protoreflect.Message { return nil } func (mt mapEntryType) Zero() protoreflect.Message { return nil } func (mt mapEntryType) Descriptor() protoreflect.MessageDescriptor { return mt.desc } func (mt mapEntryType) Enum(i int) protoreflect.EnumType { fd := mt.desc.Fields().Get(i) if fd.Enum() == nil { return nil } return Export{}.EnumTypeOf(mt.valType) } func (mt mapEntryType) Message(i int) protoreflect.MessageType { fd := mt.desc.Fields().Get(i) if fd.Message() == nil { return nil } return Export{}.MessageTypeOf(mt.valType) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/decode.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "math/bits" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/runtime/protoiface" ) var errDecode = errors.New("cannot parse invalid wire-format data") var errRecursionDepth = errors.New("exceeded maximum recursion depth") type unmarshalOptions struct { flags protoiface.UnmarshalInputFlags resolver interface { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } depth int } func (o unmarshalOptions) Options() proto.UnmarshalOptions { return proto.UnmarshalOptions{ Merge: true, AllowPartial: true, DiscardUnknown: o.DiscardUnknown(), Resolver: o.resolver, NoLazyDecoding: o.NoLazyDecoding(), } } func (o unmarshalOptions) DiscardUnknown() bool { return o.flags&protoiface.UnmarshalDiscardUnknown != 0 } func (o unmarshalOptions) AliasBuffer() bool { return o.flags&protoiface.UnmarshalAliasBuffer != 0 } func (o unmarshalOptions) Validated() bool { return o.flags&protoiface.UnmarshalValidated != 0 } func (o unmarshalOptions) NoLazyDecoding() bool { return o.flags&protoiface.UnmarshalNoLazyDecoding != 0 } func (o unmarshalOptions) CanBeLazy() bool { if o.resolver != protoregistry.GlobalTypes { return false } // We ignore the UnmarshalInvalidateSizeCache even though it's not in the default set return (o.flags & ^(protoiface.UnmarshalAliasBuffer | protoiface.UnmarshalValidated | protoiface.UnmarshalCheckRequired)) == 0 } var lazyUnmarshalOptions = unmarshalOptions{ resolver: protoregistry.GlobalTypes, flags: protoiface.UnmarshalAliasBuffer | protoiface.UnmarshalValidated, depth: protowire.DefaultRecursionLimit, } type unmarshalOutput struct { n int // number of bytes consumed initialized bool } // unmarshal is protoreflect.Methods.Unmarshal. func (mi *MessageInfo) unmarshal(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { var p pointer if ms, ok := in.Message.(*messageState); ok { p = ms.pointer() } else { p = in.Message.(*messageReflectWrapper).pointer() } out, err := mi.unmarshalPointer(in.Buf, p, 0, unmarshalOptions{ flags: in.Flags, resolver: in.Resolver, depth: in.Depth, }) var flags protoiface.UnmarshalOutputFlags if out.initialized { flags |= protoiface.UnmarshalInitialized } return protoiface.UnmarshalOutput{ Flags: flags, }, err } // errUnknown is returned during unmarshaling to indicate a parse error that // should result in a field being placed in the unknown fields section (for example, // when the wire type doesn't match) as opposed to the entire unmarshal operation // failing (for example, when a field extends past the available input). // // This is a sentinel error which should never be visible to the user. var errUnknown = errors.New("unknown") func (mi *MessageInfo) unmarshalPointer(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { mi.init() opts.depth-- if opts.depth < 0 { return out, errRecursionDepth } if flags.ProtoLegacy && mi.isMessageSet { return unmarshalMessageSet(mi, b, p, opts) } lazyDecoding := LazyEnabled() // default if opts.NoLazyDecoding() { lazyDecoding = false // explicitly disabled } if mi.lazyOffset.IsValid() && lazyDecoding { return mi.unmarshalPointerLazy(b, p, groupTag, opts) } return mi.unmarshalPointerEager(b, p, groupTag, opts) } // unmarshalPointerEager is the message unmarshalling function for all messages that are not lazy. // The corresponding function for Lazy is in google_lazy.go. func (mi *MessageInfo) unmarshalPointerEager(b []byte, p pointer, groupTag protowire.Number, opts unmarshalOptions) (out unmarshalOutput, err error) { initialized := true var requiredMask uint64 var exts *map[int32]ExtensionField var presence presence if mi.presenceOffset.IsValid() { presence = p.Apply(mi.presenceOffset).PresenceInfo() } start := len(b) for len(b) > 0 { // Parse the tag (field number and wire type). var tag uint64 if b[0] < 0x80 { tag = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int tag, n = protowire.ConsumeVarint(b) if n < 0 { return out, errDecode } b = b[n:] } var num protowire.Number if n := tag >> 3; n < uint64(protowire.MinValidNumber) || n > uint64(protowire.MaxValidNumber) { return out, errDecode } else { num = protowire.Number(n) } wtyp := protowire.Type(tag & 7) if wtyp == protowire.EndGroupType { if num != groupTag { return out, errDecode } groupTag = 0 break } var f *coderFieldInfo if int(num) < len(mi.denseCoderFields) { f = mi.denseCoderFields[num] } else { f = mi.coderFields[num] } var n int err := errUnknown switch { case f != nil: if f.funcs.unmarshal == nil { break } var o unmarshalOutput o, err = f.funcs.unmarshal(b, p.Apply(f.offset), wtyp, f, opts) n = o.n if err != nil { break } requiredMask |= f.validation.requiredBit if f.funcs.isInit != nil && !o.initialized { initialized = false } if f.presenceIndex != noPresence { presence.SetPresentUnatomic(f.presenceIndex, mi.presenceSize) } default: // Possible extension. if exts == nil && mi.extensionOffset.IsValid() { exts = p.Apply(mi.extensionOffset).Extensions() if *exts == nil { *exts = make(map[int32]ExtensionField) } } if exts == nil { break } var o unmarshalOutput o, err = mi.unmarshalExtension(b, num, wtyp, *exts, opts) if err != nil { break } n = o.n if !o.initialized { initialized = false } } if err != nil { if err != errUnknown { return out, err } n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return out, errDecode } if !opts.DiscardUnknown() && mi.unknownOffset.IsValid() { u := mi.mutableUnknownBytes(p) *u = protowire.AppendTag(*u, num, wtyp) *u = append(*u, b[:n]...) } } b = b[n:] } if groupTag != 0 { return out, errDecode } if mi.numRequiredFields > 0 && bits.OnesCount64(requiredMask) != int(mi.numRequiredFields) { initialized = false } if initialized { out.initialized = true } out.n = start - len(b) return out, nil } func (mi *MessageInfo) unmarshalExtension(b []byte, num protowire.Number, wtyp protowire.Type, exts map[int32]ExtensionField, opts unmarshalOptions) (out unmarshalOutput, err error) { x := exts[int32(num)] xt := x.Type() if xt == nil { var err error xt, err = opts.resolver.FindExtensionByNumber(mi.Desc.FullName(), num) if err != nil { if err == protoregistry.NotFound { return out, errUnknown } return out, errors.New("%v: unable to resolve extension %v: %v", mi.Desc.FullName(), num, err) } } xi := getExtensionFieldInfo(xt) if xi.funcs.unmarshal == nil { return out, errUnknown } if flags.LazyUnmarshalExtensions { if opts.CanBeLazy() && x.canLazy(xt) { out, valid := skipExtension(b, xi, num, wtyp, opts) switch valid { case ValidationValid: if out.initialized { x.appendLazyBytes(xt, xi, num, wtyp, b[:out.n]) exts[int32(num)] = x return out, nil } case ValidationInvalid: return out, errDecode case ValidationUnknown: } } } ival := x.Value() if !ival.IsValid() && xi.unmarshalNeedsValue { // Create a new message, list, or map value to fill in. // For enums, create a prototype value to let the unmarshal func know the // concrete type. ival = xt.New() } v, out, err := xi.funcs.unmarshal(b, ival, num, wtyp, opts) if err != nil { return out, err } if xi.funcs.isInit == nil { out.initialized = true } x.Set(xt, v) exts[int32(num)] = x return out, nil } func skipExtension(b []byte, xi *extensionFieldInfo, num protowire.Number, wtyp protowire.Type, opts unmarshalOptions) (out unmarshalOutput, _ ValidationStatus) { if xi.validation.mi == nil { return out, ValidationUnknown } xi.validation.mi.init() switch xi.validation.typ { case validationTypeMessage: if wtyp != protowire.BytesType { return out, ValidationUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return out, ValidationUnknown } if opts.Validated() { out.initialized = true out.n = n return out, ValidationValid } out, st := xi.validation.mi.validate(v, 0, opts) out.n = n return out, st case validationTypeGroup: if wtyp != protowire.StartGroupType { return out, ValidationUnknown } out, st := xi.validation.mi.validate(b, num, opts) return out, st default: return out, ValidationUnknown } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_extension.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/codec_extension.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "sync" "sync/atomic" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) type extensionFieldInfo struct { wiretag uint64 tagsize int unmarshalNeedsValue bool funcs valueCoderFuncs validation validationInfo } func getExtensionFieldInfo(xt protoreflect.ExtensionType) *extensionFieldInfo { if xi, ok := xt.(*ExtensionInfo); ok { xi.lazyInit() return xi.info } // Ideally we'd cache the resulting *extensionFieldInfo so we don't have to // recompute this metadata repeatedly. But without support for something like // weak references, such a cache would pin temporary values (like dynamic // extension types, constructed for the duration of a user request) to the // heap forever, causing memory usage of the cache to grow unbounded. // See discussion in https://github.com/golang/protobuf/issues/1521. return makeExtensionFieldInfo(xt.TypeDescriptor()) } func makeExtensionFieldInfo(xd protoreflect.ExtensionDescriptor) *extensionFieldInfo { var wiretag uint64 if !xd.IsPacked() { wiretag = protowire.EncodeTag(xd.Number(), wireTypes[xd.Kind()]) } else { wiretag = protowire.EncodeTag(xd.Number(), protowire.BytesType) } e := &extensionFieldInfo{ wiretag: wiretag, tagsize: protowire.SizeVarint(wiretag), funcs: encoderFuncsForValue(xd), } // Does the unmarshal function need a value passed to it? // This is true for composite types, where we pass in a message, list, or map to fill in, // and for enums, where we pass in a prototype value to specify the concrete enum type. switch xd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind, protoreflect.EnumKind: e.unmarshalNeedsValue = true default: if xd.Cardinality() == protoreflect.Repeated { e.unmarshalNeedsValue = true } } return e } type lazyExtensionValue struct { atomicOnce uint32 // atomically set if value is valid mu sync.Mutex xi *extensionFieldInfo value protoreflect.Value b []byte } type ExtensionField struct { typ protoreflect.ExtensionType // value is either the value of GetValue, // or a *lazyExtensionValue that then returns the value of GetValue. value protoreflect.Value lazy *lazyExtensionValue } func (f *ExtensionField) appendLazyBytes(xt protoreflect.ExtensionType, xi *extensionFieldInfo, num protowire.Number, wtyp protowire.Type, b []byte) { if f.lazy == nil { f.lazy = &lazyExtensionValue{xi: xi} } f.typ = xt f.lazy.xi = xi f.lazy.b = protowire.AppendTag(f.lazy.b, num, wtyp) f.lazy.b = append(f.lazy.b, b...) } func (f *ExtensionField) canLazy(xt protoreflect.ExtensionType) bool { if f.typ == nil { return true } if f.typ == xt && f.lazy != nil && atomic.LoadUint32(&f.lazy.atomicOnce) == 0 { return true } return false } // isUnexpandedLazy returns true if the ExensionField is lazy and not // yet expanded, which means it's present and already checked for // initialized required fields. func (f *ExtensionField) isUnexpandedLazy() bool { return f.lazy != nil && atomic.LoadUint32(&f.lazy.atomicOnce) == 0 } // lazyBuffer retrieves the buffer for a lazy extension if it's not yet expanded. // // The returned buffer has to be kept over whatever operation we're planning, // as re-retrieving it will fail after the message is lazily decoded. func (f *ExtensionField) lazyBuffer() []byte { // This function might be in the critical path, so check the atomic without // taking a look first, then only take the lock if needed. if !f.isUnexpandedLazy() { return nil } f.lazy.mu.Lock() defer f.lazy.mu.Unlock() return f.lazy.b } func (f *ExtensionField) lazyInit() { f.lazy.mu.Lock() defer f.lazy.mu.Unlock() if atomic.LoadUint32(&f.lazy.atomicOnce) == 1 { return } if f.lazy.xi != nil { b := f.lazy.b val := f.typ.New() for len(b) > 0 { var tag uint64 if b[0] < 0x80 { tag = uint64(b[0]) b = b[1:] } else if len(b) >= 2 && b[1] < 128 { tag = uint64(b[0]&0x7f) + uint64(b[1])<<7 b = b[2:] } else { var n int tag, n = protowire.ConsumeVarint(b) if n < 0 { panic(errors.New("bad tag in lazy extension decoding")) } b = b[n:] } num := protowire.Number(tag >> 3) wtyp := protowire.Type(tag & 7) var out unmarshalOutput var err error val, out, err = f.lazy.xi.funcs.unmarshal(b, val, num, wtyp, lazyUnmarshalOptions) if err != nil { panic(errors.New("decode failure in lazy extension decoding: %v", err)) } b = b[out.n:] } f.lazy.value = val } else { panic("No support for lazy fns for ExtensionField") } f.lazy.xi = nil f.lazy.b = nil atomic.StoreUint32(&f.lazy.atomicOnce, 1) } // Set sets the type and value of the extension field. // This must not be called concurrently. func (f *ExtensionField) Set(t protoreflect.ExtensionType, v protoreflect.Value) { f.typ = t f.value = v f.lazy = nil } // Value returns the value of the extension field. // This may be called concurrently. func (f *ExtensionField) Value() protoreflect.Value { if f.lazy != nil { if atomic.LoadUint32(&f.lazy.atomicOnce) == 0 { f.lazyInit() } return f.lazy.value } return f.value } // Type returns the type of the extension field. // This may be called concurrently. func (f ExtensionField) Type() protoreflect.ExtensionType { return f.typ } // IsSet returns whether the extension field is set. // This may be called concurrently. func (f ExtensionField) IsSet() bool { return f.typ != nil } // IsLazy reports whether a field is lazily encoded. // It is exported for testing. func IsLazy(m protoreflect.Message, fd protoreflect.FieldDescriptor) bool { var mi *MessageInfo var p pointer switch m := m.(type) { case *messageState: mi = m.messageInfo() p = m.pointer() case *messageReflectWrapper: mi = m.messageInfo() p = m.pointer() default: return false } xd, ok := fd.(protoreflect.ExtensionTypeDescriptor) if !ok { return false } xt := xd.Type() ext := mi.extensionMap(p) if ext == nil { return false } f, ok := (*ext)[int32(fd.Number())] if !ok { return false } return f.typ == xt && f.lazy != nil && atomic.LoadUint32(&f.lazy.atomicOnce) == 0 }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "fmt" "reflect" "google.golang.org/protobuf/internal/detrand" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) type reflectMessageInfo struct { fields map[protoreflect.FieldNumber]*fieldInfo oneofs map[protoreflect.Name]*oneofInfo // fieldTypes contains the zero value of an enum or message field. // For lists, it contains the element type. // For maps, it contains the entry value type. fieldTypes map[protoreflect.FieldNumber]any // denseFields is a subset of fields where: // 0 < fieldDesc.Number() < len(denseFields) // It provides faster access to the fieldInfo, but may be incomplete. denseFields []*fieldInfo // rangeInfos is a list of all fields (not belonging to a oneof) and oneofs. rangeInfos []any // either *fieldInfo or *oneofInfo getUnknown func(pointer) protoreflect.RawFields setUnknown func(pointer, protoreflect.RawFields) extensionMap func(pointer) *extensionMap nilMessage atomicNilMessage } // makeReflectFuncs generates the set of functions to support reflection. func (mi *MessageInfo) makeReflectFuncs(t reflect.Type, si structInfo) { mi.makeKnownFieldsFunc(si) mi.makeUnknownFieldsFunc(t, si) mi.makeExtensionFieldsFunc(t, si) mi.makeFieldTypes(si) } // makeKnownFieldsFunc generates functions for operations that can be performed // on each protobuf message field. It takes in a reflect.Type representing the // Go struct and matches message fields with struct fields. // // This code assumes that the struct is well-formed and panics if there are // any discrepancies. func (mi *MessageInfo) makeKnownFieldsFunc(si structInfo) { mi.fields = map[protoreflect.FieldNumber]*fieldInfo{} md := mi.Desc fds := md.Fields() for i := 0; i < fds.Len(); i++ { fd := fds.Get(i) fs := si.fieldsByNumber[fd.Number()] isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic() if isOneof { fs = si.oneofsByName[fd.ContainingOneof().Name()] } var fi fieldInfo switch { case fs.Type == nil: fi = fieldInfoForMissing(fd) // never occurs for officially generated message types case isOneof: fi = fieldInfoForOneof(fd, fs, mi.Exporter, si.oneofWrappersByNumber[fd.Number()]) case fd.IsMap(): fi = fieldInfoForMap(fd, fs, mi.Exporter) case fd.IsList(): fi = fieldInfoForList(fd, fs, mi.Exporter) case fd.Message() != nil: fi = fieldInfoForMessage(fd, fs, mi.Exporter) default: fi = fieldInfoForScalar(fd, fs, mi.Exporter) } mi.fields[fd.Number()] = &fi } mi.oneofs = map[protoreflect.Name]*oneofInfo{} for i := 0; i < md.Oneofs().Len(); i++ { od := md.Oneofs().Get(i) mi.oneofs[od.Name()] = makeOneofInfo(od, si, mi.Exporter) } mi.denseFields = make([]*fieldInfo, fds.Len()*2) for i := 0; i < fds.Len(); i++ { if fd := fds.Get(i); int(fd.Number()) < len(mi.denseFields) { mi.denseFields[fd.Number()] = mi.fields[fd.Number()] } } for i := 0; i < fds.Len(); { fd := fds.Get(i) if od := fd.ContainingOneof(); od != nil && !od.IsSynthetic() { mi.rangeInfos = append(mi.rangeInfos, mi.oneofs[od.Name()]) i += od.Fields().Len() } else { mi.rangeInfos = append(mi.rangeInfos, mi.fields[fd.Number()]) i++ } } // Introduce instability to iteration order, but keep it deterministic. if len(mi.rangeInfos) > 1 && detrand.Bool() { i := detrand.Intn(len(mi.rangeInfos) - 1) mi.rangeInfos[i], mi.rangeInfos[i+1] = mi.rangeInfos[i+1], mi.rangeInfos[i] } } func (mi *MessageInfo) makeUnknownFieldsFunc(t reflect.Type, si structInfo) { switch { case si.unknownOffset.IsValid() && si.unknownType == unknownFieldsAType: // Handle as []byte. mi.getUnknown = func(p pointer) protoreflect.RawFields { if p.IsNil() { return nil } return *p.Apply(mi.unknownOffset).Bytes() } mi.setUnknown = func(p pointer, b protoreflect.RawFields) { if p.IsNil() { panic("invalid SetUnknown on nil Message") } *p.Apply(mi.unknownOffset).Bytes() = b } case si.unknownOffset.IsValid() && si.unknownType == unknownFieldsBType: // Handle as *[]byte. mi.getUnknown = func(p pointer) protoreflect.RawFields { if p.IsNil() { return nil } bp := p.Apply(mi.unknownOffset).BytesPtr() if *bp == nil { return nil } return **bp } mi.setUnknown = func(p pointer, b protoreflect.RawFields) { if p.IsNil() { panic("invalid SetUnknown on nil Message") } bp := p.Apply(mi.unknownOffset).BytesPtr() if *bp == nil { *bp = new([]byte) } **bp = b } default: mi.getUnknown = func(pointer) protoreflect.RawFields { return nil } mi.setUnknown = func(p pointer, _ protoreflect.RawFields) { if p.IsNil() { panic("invalid SetUnknown on nil Message") } } } } func (mi *MessageInfo) makeExtensionFieldsFunc(t reflect.Type, si structInfo) { if si.extensionOffset.IsValid() { mi.extensionMap = func(p pointer) *extensionMap { if p.IsNil() { return (*extensionMap)(nil) } v := p.Apply(si.extensionOffset).AsValueOf(extensionFieldsType) return (*extensionMap)(v.Interface().(*map[int32]ExtensionField)) } } else { mi.extensionMap = func(pointer) *extensionMap { return (*extensionMap)(nil) } } } func (mi *MessageInfo) makeFieldTypes(si structInfo) { md := mi.Desc fds := md.Fields() for i := 0; i < fds.Len(); i++ { var ft reflect.Type fd := fds.Get(i) fs := si.fieldsByNumber[fd.Number()] isOneof := fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic() if isOneof { fs = si.oneofsByName[fd.ContainingOneof().Name()] } var isMessage bool switch { case fs.Type == nil: continue // never occurs for officially generated message types case isOneof: if fd.Enum() != nil || fd.Message() != nil { ft = si.oneofWrappersByNumber[fd.Number()].Field(0).Type } case fd.IsMap(): if fd.MapValue().Enum() != nil || fd.MapValue().Message() != nil { ft = fs.Type.Elem() } isMessage = fd.MapValue().Message() != nil case fd.IsList(): if fd.Enum() != nil || fd.Message() != nil { ft = fs.Type.Elem() if ft.Kind() == reflect.Slice { ft = ft.Elem() } } isMessage = fd.Message() != nil case fd.Enum() != nil: ft = fs.Type if fd.HasPresence() && ft.Kind() == reflect.Ptr { ft = ft.Elem() } case fd.Message() != nil: ft = fs.Type isMessage = true } if isMessage && ft != nil && ft.Kind() != reflect.Ptr { ft = reflect.PtrTo(ft) // never occurs for officially generated message types } if ft != nil { if mi.fieldTypes == nil { mi.fieldTypes = make(map[protoreflect.FieldNumber]any) } mi.fieldTypes[fd.Number()] = reflect.Zero(ft).Interface() } } } type extensionMap map[int32]ExtensionField func (m *extensionMap) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { if m != nil { for _, x := range *m { xd := x.Type().TypeDescriptor() v := x.Value() if xd.IsList() && v.List().Len() == 0 { continue } if !f(xd, v) { return } } } } func (m *extensionMap) Has(xd protoreflect.ExtensionTypeDescriptor) (ok bool) { if m == nil { return false } x, ok := (*m)[int32(xd.Number())] if !ok { return false } if x.isUnexpandedLazy() { // Avoid calling x.Value(), which triggers a lazy unmarshal. return true } switch { case xd.IsList(): return x.Value().List().Len() > 0 case xd.IsMap(): return x.Value().Map().Len() > 0 } return true } func (m *extensionMap) Clear(xd protoreflect.ExtensionTypeDescriptor) { delete(*m, int32(xd.Number())) } func (m *extensionMap) Get(xd protoreflect.ExtensionTypeDescriptor) protoreflect.Value { if m != nil { if x, ok := (*m)[int32(xd.Number())]; ok { return x.Value() } } return xd.Type().Zero() } func (m *extensionMap) Set(xd protoreflect.ExtensionTypeDescriptor, v protoreflect.Value) { xt := xd.Type() isValid := true switch { case !xt.IsValidValue(v): isValid = false case xd.IsList(): isValid = v.List().IsValid() case xd.IsMap(): isValid = v.Map().IsValid() case xd.Message() != nil: isValid = v.Message().IsValid() } if !isValid { panic(fmt.Sprintf("%v: assigning invalid value", xd.FullName())) } if *m == nil { *m = make(map[int32]ExtensionField) } var x ExtensionField x.Set(xt, v) (*m)[int32(xd.Number())] = x } func (m *extensionMap) Mutable(xd protoreflect.ExtensionTypeDescriptor) protoreflect.Value { if xd.Kind() != protoreflect.MessageKind && xd.Kind() != protoreflect.GroupKind && !xd.IsList() && !xd.IsMap() { panic("invalid Mutable on field with non-composite type") } if x, ok := (*m)[int32(xd.Number())]; ok { return x.Value() } v := xd.Type().New() m.Set(xd, v) return v } // MessageState is a data structure that is nested as the first field in a // concrete message. It provides a way to implement the ProtoReflect method // in an allocation-free way without needing to have a shadow Go type generated // for every message type. This technique only works using unsafe. // // Example generated code: // // type M struct { // state protoimpl.MessageState // // Field1 int32 // Field2 string // Field3 *BarMessage // ... // } // // func (m *M) ProtoReflect() protoreflect.Message { // mi := &file_fizz_buzz_proto_msgInfos[5] // if protoimpl.UnsafeEnabled && m != nil { // ms := protoimpl.X.MessageStateOf(Pointer(m)) // if ms.LoadMessageInfo() == nil { // ms.StoreMessageInfo(mi) // } // return ms // } // return mi.MessageOf(m) // } // // The MessageState type holds a *MessageInfo, which must be atomically set to // the message info associated with a given message instance. // By unsafely converting a *M into a *MessageState, the MessageState object // has access to all the information needed to implement protobuf reflection. // It has access to the message info as its first field, and a pointer to the // MessageState is identical to a pointer to the concrete message value. // // Requirements: // - The type M must implement protoreflect.ProtoMessage. // - The address of m must not be nil. // - The address of m and the address of m.state must be equal, // even though they are different Go types. type MessageState struct { pragma.NoUnkeyedLiterals pragma.DoNotCompare pragma.DoNotCopy atomicMessageInfo *MessageInfo } type messageState MessageState var ( _ protoreflect.Message = (*messageState)(nil) _ unwrapper = (*messageState)(nil) ) // messageDataType is a tuple of a pointer to the message data and // a pointer to the message type. It is a generalized way of providing a // reflective view over a message instance. The disadvantage of this approach // is the need to allocate this tuple of 16B. type messageDataType struct { p pointer mi *MessageInfo } type ( messageReflectWrapper messageDataType messageIfaceWrapper messageDataType ) var ( _ protoreflect.Message = (*messageReflectWrapper)(nil) _ unwrapper = (*messageReflectWrapper)(nil) _ protoreflect.ProtoMessage = (*messageIfaceWrapper)(nil) _ unwrapper = (*messageIfaceWrapper)(nil) ) // MessageOf returns a reflective view over a message. The input must be a // pointer to a named Go struct. If the provided type has a ProtoReflect method, // it must be implemented by calling this method. func (mi *MessageInfo) MessageOf(m any) protoreflect.Message { if reflect.TypeOf(m) != mi.GoReflectType { panic(fmt.Sprintf("type mismatch: got %T, want %v", m, mi.GoReflectType)) } p := pointerOfIface(m) if p.IsNil() { return mi.nilMessage.Init(mi) } return &messageReflectWrapper{p, mi} } func (m *messageReflectWrapper) pointer() pointer { return m.p } func (m *messageReflectWrapper) messageInfo() *MessageInfo { return m.mi } // Reset implements the v1 proto.Message.Reset method. func (m *messageIfaceWrapper) Reset() { if mr, ok := m.protoUnwrap().(interface{ Reset() }); ok { mr.Reset() return } rv := reflect.ValueOf(m.protoUnwrap()) if rv.Kind() == reflect.Ptr && !rv.IsNil() { rv.Elem().Set(reflect.Zero(rv.Type().Elem())) } } func (m *messageIfaceWrapper) ProtoReflect() protoreflect.Message { return (*messageReflectWrapper)(m) } func (m *messageIfaceWrapper) protoUnwrap() any { return m.p.AsIfaceOf(m.mi.GoReflectType.Elem()) } // checkField verifies that the provided field descriptor is valid. // Exactly one of the returned values is populated. func (mi *MessageInfo) checkField(fd protoreflect.FieldDescriptor) (*fieldInfo, protoreflect.ExtensionTypeDescriptor) { var fi *fieldInfo if n := fd.Number(); 0 < n && int(n) < len(mi.denseFields) { fi = mi.denseFields[n] } else { fi = mi.fields[n] } if fi != nil { if fi.fieldDesc != fd { if got, want := fd.FullName(), fi.fieldDesc.FullName(); got != want { panic(fmt.Sprintf("mismatching field: got %v, want %v", got, want)) } panic(fmt.Sprintf("mismatching field: %v", fd.FullName())) } return fi, nil } if fd.IsExtension() { if got, want := fd.ContainingMessage().FullName(), mi.Desc.FullName(); got != want { // TODO: Should this be exact containing message descriptor match? panic(fmt.Sprintf("extension %v has mismatching containing message: got %v, want %v", fd.FullName(), got, want)) } if !mi.Desc.ExtensionRanges().Has(fd.Number()) { panic(fmt.Sprintf("extension %v extends %v outside the extension range", fd.FullName(), mi.Desc.FullName())) } xtd, ok := fd.(protoreflect.ExtensionTypeDescriptor) if !ok { panic(fmt.Sprintf("extension %v does not implement protoreflect.ExtensionTypeDescriptor", fd.FullName())) } return nil, xtd } panic(fmt.Sprintf("field %v is invalid", fd.FullName())) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/legacy_extension.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package impl import ( "reflect" "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/encoding/messageset" ptag "google.golang.org/protobuf/internal/encoding/tag" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/runtime/protoiface" ) func (xi *ExtensionInfo) initToLegacy() { xd := xi.desc var parent protoiface.MessageV1 messageName := xd.ContainingMessage().FullName() if mt, _ := protoregistry.GlobalTypes.FindMessageByName(messageName); mt != nil { // Create a new parent message and unwrap it if possible. mv := mt.New().Interface() t := reflect.TypeOf(mv) if mv, ok := mv.(unwrapper); ok { t = reflect.TypeOf(mv.protoUnwrap()) } // Check whether the message implements the legacy v1 Message interface. mz := reflect.Zero(t).Interface() if mz, ok := mz.(protoiface.MessageV1); ok { parent = mz } } // Determine the v1 extension type, which is unfortunately not the same as // the v2 ExtensionType.GoType. extType := xi.goType switch extType.Kind() { case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String: extType = reflect.PtrTo(extType) // T -> *T for singular scalar fields } // Reconstruct the legacy enum full name. var enumName string if xd.Kind() == protoreflect.EnumKind { enumName = legacyEnumName(xd.Enum()) } // Derive the proto file that the extension was declared within. var filename string if fd := xd.ParentFile(); fd != nil { filename = fd.Path() } // For MessageSet extensions, the name used is the parent message. name := xd.FullName() if messageset.IsMessageSetExtension(xd) { name = name.Parent() } xi.ExtendedType = parent xi.ExtensionType = reflect.Zero(extType).Interface() xi.Field = int32(xd.Number()) xi.Name = string(name) xi.Tag = ptag.Marshal(xd, enumName) xi.Filename = filename } // initFromLegacy initializes an ExtensionInfo from // the contents of the deprecated exported fields of the type. func (xi *ExtensionInfo) initFromLegacy() { // The v1 API returns "type incomplete" descriptors where only the // field number is specified. In such a case, use a placeholder. if xi.ExtendedType == nil || xi.ExtensionType == nil { xd := placeholderExtension{ name: protoreflect.FullName(xi.Name), number: protoreflect.FieldNumber(xi.Field), } xi.desc = extensionTypeDescriptor{xd, xi} return } // Resolve enum or message dependencies. var ed protoreflect.EnumDescriptor var md protoreflect.MessageDescriptor t := reflect.TypeOf(xi.ExtensionType) isOptional := t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct isRepeated := t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 if isOptional || isRepeated { t = t.Elem() } switch v := reflect.Zero(t).Interface().(type) { case protoreflect.Enum: ed = v.Descriptor() case enumV1: ed = LegacyLoadEnumDesc(t) case protoreflect.ProtoMessage: md = v.ProtoReflect().Descriptor() case messageV1: md = LegacyLoadMessageDesc(t) } // Derive basic field information from the struct tag. var evs protoreflect.EnumValueDescriptors if ed != nil { evs = ed.Values() } fd := ptag.Unmarshal(xi.Tag, t, evs).(*filedesc.Field) // Construct a v2 ExtensionType. xd := &filedesc.Extension{L2: new(filedesc.ExtensionL2)} xd.L0.ParentFile = filedesc.SurrogateProto2 xd.L0.FullName = protoreflect.FullName(xi.Name) xd.L1.Number = protoreflect.FieldNumber(xi.Field) xd.L1.Cardinality = fd.L1.Cardinality xd.L1.Kind = fd.L1.Kind xd.L1.EditionFeatures = fd.L1.EditionFeatures xd.L2.Default = fd.L1.Default xd.L1.Extendee = Export{}.MessageDescriptorOf(xi.ExtendedType) xd.L2.Enum = ed xd.L2.Message = md // Derive real extension field name for MessageSets. if messageset.IsMessageSet(xd.L1.Extendee) && md.FullName() == xd.L0.FullName { xd.L0.FullName = xd.L0.FullName.Append(messageset.ExtensionName) } tt := reflect.TypeOf(xi.ExtensionType) if isOptional { tt = tt.Elem() } xi.goType = tt xi.desc = extensionTypeDescriptor{xd, xi} } type placeholderExtension struct { name protoreflect.FullName number protoreflect.FieldNumber } func (x placeholderExtension) ParentFile() protoreflect.FileDescriptor { return nil } func (x placeholderExtension) Parent() protoreflect.Descriptor { return nil } func (x placeholderExtension) Index() int { return 0 } func (x placeholderExtension) Syntax() protoreflect.Syntax { return 0 } func (x placeholderExtension) Name() protoreflect.Name { return x.name.Name() } func (x placeholderExtension) FullName() protoreflect.FullName { return x.name } func (x placeholderExtension) IsPlaceholder() bool { return true } func (x placeholderExtension) Options() protoreflect.ProtoMessage { return descopts.Field } func (x placeholderExtension) Number() protoreflect.FieldNumber { return x.number } func (x placeholderExtension) Cardinality() protoreflect.Cardinality { return 0 } func (x placeholderExtension) Kind() protoreflect.Kind { return 0 } func (x placeholderExtension) HasJSONName() bool { return false } func (x placeholderExtension) JSONName() string { return "[" + string(x.name) + "]" } func (x placeholderExtension) TextName() string { return "[" + string(x.name) + "]" } func (x placeholderExtension) HasPresence() bool { return false } func (x placeholderExtension) HasOptionalKeyword() bool { return false } func (x placeholderExtension) IsExtension() bool { return true } func (x placeholderExtension) IsWeak() bool { return false } func (x placeholderExtension) IsLazy() bool { return false } func (x placeholderExtension) IsPacked() bool { return false } func (x placeholderExtension) IsList() bool { return false } func (x placeholderExtension) IsMap() bool { return false } func (x placeholderExtension) MapKey() protoreflect.FieldDescriptor { return nil } func (x placeholderExtension) MapValue() protoreflect.FieldDescriptor { return nil } func (x placeholderExtension) HasDefault() bool { return false } func (x placeholderExtension) Default() protoreflect.Value { return protoreflect.Value{} } func (x placeholderExtension) DefaultEnumValue() protoreflect.EnumValueDescriptor { return nil } func (x placeholderExtension) ContainingOneof() protoreflect.OneofDescriptor { return nil } func (x placeholderExtension) ContainingMessage() protoreflect.MessageDescriptor { return nil } func (x placeholderExtension) Enum() protoreflect.EnumDescriptor { return nil } func (x placeholderExtension) Message() protoreflect.MessageDescriptor { return nil } func (x placeholderExtension) ProtoType(protoreflect.FieldDescriptor) { return } func (x placeholderExtension) ProtoInternal(pragma.DoNotImplement) { return }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/impl/message_reflect_gen.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package impl import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) func (m *messageState) Descriptor() protoreflect.MessageDescriptor { return m.messageInfo().Desc } func (m *messageState) Type() protoreflect.MessageType { return m.messageInfo() } func (m *messageState) New() protoreflect.Message { return m.messageInfo().New() } func (m *messageState) Interface() protoreflect.ProtoMessage { return m.protoUnwrap().(protoreflect.ProtoMessage) } func (m *messageState) protoUnwrap() any { return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) } func (m *messageState) ProtoMethods() *protoiface.Methods { mi := m.messageInfo() mi.init() return &mi.methods } // ProtoMessageInfo is a pseudo-internal API for allowing the v1 code // to be able to retrieve a v2 MessageInfo struct. // // WARNING: This method is exempt from the compatibility promise and // may be removed in the future without warning. func (m *messageState) ProtoMessageInfo() *MessageInfo { return m.messageInfo() } func (m *messageState) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { mi := m.messageInfo() mi.init() for _, ri := range mi.rangeInfos { switch ri := ri.(type) { case *fieldInfo: if ri.has(m.pointer()) { if !f(ri.fieldDesc, ri.get(m.pointer())) { return } } case *oneofInfo: if n := ri.which(m.pointer()); n > 0 { fi := mi.fields[n] if !f(fi.fieldDesc, fi.get(m.pointer())) { return } } } } mi.extensionMap(m.pointer()).Range(f) } func (m *messageState) Has(fd protoreflect.FieldDescriptor) bool { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.has(m.pointer()) } else { return mi.extensionMap(m.pointer()).Has(xd) } } func (m *messageState) Clear(fd protoreflect.FieldDescriptor) { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { fi.clear(m.pointer()) } else { mi.extensionMap(m.pointer()).Clear(xd) } } func (m *messageState) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.get(m.pointer()) } else { return mi.extensionMap(m.pointer()).Get(xd) } } func (m *messageState) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { fi.set(m.pointer(), v) } else { mi.extensionMap(m.pointer()).Set(xd, v) } } func (m *messageState) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.mutable(m.pointer()) } else { return mi.extensionMap(m.pointer()).Mutable(xd) } } func (m *messageState) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.newField() } else { return xd.Type().New() } } func (m *messageState) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { mi := m.messageInfo() mi.init() if oi := mi.oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { return od.Fields().ByNumber(oi.which(m.pointer())) } panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) } func (m *messageState) GetUnknown() protoreflect.RawFields { mi := m.messageInfo() mi.init() return mi.getUnknown(m.pointer()) } func (m *messageState) SetUnknown(b protoreflect.RawFields) { mi := m.messageInfo() mi.init() mi.setUnknown(m.pointer(), b) } func (m *messageState) IsValid() bool { return !m.pointer().IsNil() } func (m *messageReflectWrapper) Descriptor() protoreflect.MessageDescriptor { return m.messageInfo().Desc } func (m *messageReflectWrapper) Type() protoreflect.MessageType { return m.messageInfo() } func (m *messageReflectWrapper) New() protoreflect.Message { return m.messageInfo().New() } func (m *messageReflectWrapper) Interface() protoreflect.ProtoMessage { if m, ok := m.protoUnwrap().(protoreflect.ProtoMessage); ok { return m } return (*messageIfaceWrapper)(m) } func (m *messageReflectWrapper) protoUnwrap() any { return m.pointer().AsIfaceOf(m.messageInfo().GoReflectType.Elem()) } func (m *messageReflectWrapper) ProtoMethods() *protoiface.Methods { mi := m.messageInfo() mi.init() return &mi.methods } // ProtoMessageInfo is a pseudo-internal API for allowing the v1 code // to be able to retrieve a v2 MessageInfo struct. // // WARNING: This method is exempt from the compatibility promise and // may be removed in the future without warning. func (m *messageReflectWrapper) ProtoMessageInfo() *MessageInfo { return m.messageInfo() } func (m *messageReflectWrapper) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { mi := m.messageInfo() mi.init() for _, ri := range mi.rangeInfos { switch ri := ri.(type) { case *fieldInfo: if ri.has(m.pointer()) { if !f(ri.fieldDesc, ri.get(m.pointer())) { return } } case *oneofInfo: if n := ri.which(m.pointer()); n > 0 { fi := mi.fields[n] if !f(fi.fieldDesc, fi.get(m.pointer())) { return } } } } mi.extensionMap(m.pointer()).Range(f) } func (m *messageReflectWrapper) Has(fd protoreflect.FieldDescriptor) bool { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.has(m.pointer()) } else { return mi.extensionMap(m.pointer()).Has(xd) } } func (m *messageReflectWrapper) Clear(fd protoreflect.FieldDescriptor) { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { fi.clear(m.pointer()) } else { mi.extensionMap(m.pointer()).Clear(xd) } } func (m *messageReflectWrapper) Get(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.get(m.pointer()) } else { return mi.extensionMap(m.pointer()).Get(xd) } } func (m *messageReflectWrapper) Set(fd protoreflect.FieldDescriptor, v protoreflect.Value) { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { fi.set(m.pointer(), v) } else { mi.extensionMap(m.pointer()).Set(xd, v) } } func (m *messageReflectWrapper) Mutable(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.mutable(m.pointer()) } else { return mi.extensionMap(m.pointer()).Mutable(xd) } } func (m *messageReflectWrapper) NewField(fd protoreflect.FieldDescriptor) protoreflect.Value { mi := m.messageInfo() mi.init() if fi, xd := mi.checkField(fd); fi != nil { return fi.newField() } else { return xd.Type().New() } } func (m *messageReflectWrapper) WhichOneof(od protoreflect.OneofDescriptor) protoreflect.FieldDescriptor { mi := m.messageInfo() mi.init() if oi := mi.oneofs[od.Name()]; oi != nil && oi.oneofDesc == od { return od.Fields().ByNumber(oi.which(m.pointer())) } panic("invalid oneof descriptor " + string(od.FullName()) + " for message " + string(m.Descriptor().FullName())) } func (m *messageReflectWrapper) GetUnknown() protoreflect.RawFields { mi := m.messageInfo() mi.init() return mi.getUnknown(m.pointer()) } func (m *messageReflectWrapper) SetUnknown(b protoreflect.RawFields) { mi := m.messageInfo() mi.init() mi.setUnknown(m.pointer(), b) } func (m *messageReflectWrapper) IsValid() bool { return !m.pointer().IsNil() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/descfmt/stringer.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package descfmt provides functionality to format descriptors. package descfmt import ( "fmt" "io" "reflect" "strconv" "strings" "google.golang.org/protobuf/internal/detrand" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) type list interface { Len() int pragma.DoNotImplement } func FormatList(s fmt.State, r rune, vs list) { io.WriteString(s, formatListOpt(vs, true, r == 'v' && (s.Flag('+') || s.Flag('#')))) } func formatListOpt(vs list, isRoot, allowMulti bool) string { start, end := "[", "]" if isRoot { var name string switch vs.(type) { case protoreflect.Names: name = "Names" case protoreflect.FieldNumbers: name = "FieldNumbers" case protoreflect.FieldRanges: name = "FieldRanges" case protoreflect.EnumRanges: name = "EnumRanges" case protoreflect.FileImports: name = "FileImports" case protoreflect.Descriptor: name = reflect.ValueOf(vs).MethodByName("Get").Type().Out(0).Name() + "s" default: name = reflect.ValueOf(vs).Elem().Type().Name() } start, end = name+"{", "}" } var ss []string switch vs := vs.(type) { case protoreflect.Names: for i := 0; i < vs.Len(); i++ { ss = append(ss, fmt.Sprint(vs.Get(i))) } return start + joinStrings(ss, false) + end case protoreflect.FieldNumbers: for i := 0; i < vs.Len(); i++ { ss = append(ss, fmt.Sprint(vs.Get(i))) } return start + joinStrings(ss, false) + end case protoreflect.FieldRanges: for i := 0; i < vs.Len(); i++ { r := vs.Get(i) if r[0]+1 == r[1] { ss = append(ss, fmt.Sprintf("%d", r[0])) } else { ss = append(ss, fmt.Sprintf("%d:%d", r[0], r[1])) // enum ranges are end exclusive } } return start + joinStrings(ss, false) + end case protoreflect.EnumRanges: for i := 0; i < vs.Len(); i++ { r := vs.Get(i) if r[0] == r[1] { ss = append(ss, fmt.Sprintf("%d", r[0])) } else { ss = append(ss, fmt.Sprintf("%d:%d", r[0], int64(r[1])+1)) // enum ranges are end inclusive } } return start + joinStrings(ss, false) + end case protoreflect.FileImports: for i := 0; i < vs.Len(); i++ { var rs records rv := reflect.ValueOf(vs.Get(i)) rs.Append(rv, []methodAndName{ {rv.MethodByName("Path"), "Path"}, {rv.MethodByName("Package"), "Package"}, {rv.MethodByName("IsPublic"), "IsPublic"}, {rv.MethodByName("IsWeak"), "IsWeak"}, }...) ss = append(ss, "{"+rs.Join()+"}") } return start + joinStrings(ss, allowMulti) + end default: _, isEnumValue := vs.(protoreflect.EnumValueDescriptors) for i := 0; i < vs.Len(); i++ { m := reflect.ValueOf(vs).MethodByName("Get") v := m.Call([]reflect.Value{reflect.ValueOf(i)})[0].Interface() ss = append(ss, formatDescOpt(v.(protoreflect.Descriptor), false, allowMulti && !isEnumValue, nil)) } return start + joinStrings(ss, allowMulti && isEnumValue) + end } } type methodAndName struct { method reflect.Value name string } func FormatDesc(s fmt.State, r rune, t protoreflect.Descriptor) { io.WriteString(s, formatDescOpt(t, true, r == 'v' && (s.Flag('+') || s.Flag('#')), nil)) } func InternalFormatDescOptForTesting(t protoreflect.Descriptor, isRoot, allowMulti bool, record func(string)) string { return formatDescOpt(t, isRoot, allowMulti, record) } func formatDescOpt(t protoreflect.Descriptor, isRoot, allowMulti bool, record func(string)) string { rv := reflect.ValueOf(t) rt := rv.MethodByName("ProtoType").Type().In(0) start, end := "{", "}" if isRoot { start = rt.Name() + "{" } _, isFile := t.(protoreflect.FileDescriptor) rs := records{ allowMulti: allowMulti, record: record, } if t.IsPlaceholder() { if isFile { rs.Append(rv, []methodAndName{ {rv.MethodByName("Path"), "Path"}, {rv.MethodByName("Package"), "Package"}, {rv.MethodByName("IsPlaceholder"), "IsPlaceholder"}, }...) } else { rs.Append(rv, []methodAndName{ {rv.MethodByName("FullName"), "FullName"}, {rv.MethodByName("IsPlaceholder"), "IsPlaceholder"}, }...) } } else { switch { case isFile: rs.Append(rv, methodAndName{rv.MethodByName("Syntax"), "Syntax"}) case isRoot: rs.Append(rv, []methodAndName{ {rv.MethodByName("Syntax"), "Syntax"}, {rv.MethodByName("FullName"), "FullName"}, }...) default: rs.Append(rv, methodAndName{rv.MethodByName("Name"), "Name"}) } switch t := t.(type) { case protoreflect.FieldDescriptor: accessors := []methodAndName{ {rv.MethodByName("Number"), "Number"}, {rv.MethodByName("Cardinality"), "Cardinality"}, {rv.MethodByName("Kind"), "Kind"}, {rv.MethodByName("HasJSONName"), "HasJSONName"}, {rv.MethodByName("JSONName"), "JSONName"}, {rv.MethodByName("HasPresence"), "HasPresence"}, {rv.MethodByName("IsExtension"), "IsExtension"}, {rv.MethodByName("IsPacked"), "IsPacked"}, {rv.MethodByName("IsWeak"), "IsWeak"}, {rv.MethodByName("IsList"), "IsList"}, {rv.MethodByName("IsMap"), "IsMap"}, {rv.MethodByName("MapKey"), "MapKey"}, {rv.MethodByName("MapValue"), "MapValue"}, {rv.MethodByName("HasDefault"), "HasDefault"}, {rv.MethodByName("Default"), "Default"}, {rv.MethodByName("ContainingOneof"), "ContainingOneof"}, {rv.MethodByName("ContainingMessage"), "ContainingMessage"}, {rv.MethodByName("Message"), "Message"}, {rv.MethodByName("Enum"), "Enum"}, } for _, s := range accessors { switch s.name { case "MapKey": if k := t.MapKey(); k != nil { rs.recs = append(rs.recs, [2]string{"MapKey", k.Kind().String()}) } case "MapValue": if v := t.MapValue(); v != nil { switch v.Kind() { case protoreflect.EnumKind: rs.AppendRecs("MapValue", [2]string{"MapValue", string(v.Enum().FullName())}) case protoreflect.MessageKind, protoreflect.GroupKind: rs.AppendRecs("MapValue", [2]string{"MapValue", string(v.Message().FullName())}) default: rs.AppendRecs("MapValue", [2]string{"MapValue", v.Kind().String()}) } } case "ContainingOneof": if od := t.ContainingOneof(); od != nil { rs.AppendRecs("ContainingOneof", [2]string{"Oneof", string(od.Name())}) } case "ContainingMessage": if t.IsExtension() { rs.AppendRecs("ContainingMessage", [2]string{"Extendee", string(t.ContainingMessage().FullName())}) } case "Message": if !t.IsMap() { rs.Append(rv, s) } default: rs.Append(rv, s) } } case protoreflect.OneofDescriptor: var ss []string fs := t.Fields() for i := 0; i < fs.Len(); i++ { ss = append(ss, string(fs.Get(i).Name())) } if len(ss) > 0 { rs.AppendRecs("Fields", [2]string{"Fields", "[" + joinStrings(ss, false) + "]"}) } case protoreflect.FileDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("Path"), "Path"}, {rv.MethodByName("Package"), "Package"}, {rv.MethodByName("Imports"), "Imports"}, {rv.MethodByName("Messages"), "Messages"}, {rv.MethodByName("Enums"), "Enums"}, {rv.MethodByName("Extensions"), "Extensions"}, {rv.MethodByName("Services"), "Services"}, }...) case protoreflect.MessageDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("IsMapEntry"), "IsMapEntry"}, {rv.MethodByName("Fields"), "Fields"}, {rv.MethodByName("Oneofs"), "Oneofs"}, {rv.MethodByName("ReservedNames"), "ReservedNames"}, {rv.MethodByName("ReservedRanges"), "ReservedRanges"}, {rv.MethodByName("RequiredNumbers"), "RequiredNumbers"}, {rv.MethodByName("ExtensionRanges"), "ExtensionRanges"}, {rv.MethodByName("Messages"), "Messages"}, {rv.MethodByName("Enums"), "Enums"}, {rv.MethodByName("Extensions"), "Extensions"}, }...) case protoreflect.EnumDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("Values"), "Values"}, {rv.MethodByName("ReservedNames"), "ReservedNames"}, {rv.MethodByName("ReservedRanges"), "ReservedRanges"}, {rv.MethodByName("IsClosed"), "IsClosed"}, }...) case protoreflect.EnumValueDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("Number"), "Number"}, }...) case protoreflect.ServiceDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("Methods"), "Methods"}, }...) case protoreflect.MethodDescriptor: rs.Append(rv, []methodAndName{ {rv.MethodByName("Input"), "Input"}, {rv.MethodByName("Output"), "Output"}, {rv.MethodByName("IsStreamingClient"), "IsStreamingClient"}, {rv.MethodByName("IsStreamingServer"), "IsStreamingServer"}, }...) } if m := rv.MethodByName("GoType"); m.IsValid() { rs.Append(rv, methodAndName{m, "GoType"}) } } return start + rs.Join() + end } type records struct { recs [][2]string allowMulti bool // record is a function that will be called for every Append() or // AppendRecs() call, to be used for testing with the // InternalFormatDescOptForTesting function. record func(string) } func (rs *records) AppendRecs(fieldName string, newRecs [2]string) { if rs.record != nil { rs.record(fieldName) } rs.recs = append(rs.recs, newRecs) } func (rs *records) Append(v reflect.Value, accessors ...methodAndName) { for _, a := range accessors { if rs.record != nil { rs.record(a.name) } var rv reflect.Value if a.method.IsValid() { rv = a.method.Call(nil)[0] } if v.Kind() == reflect.Struct && !rv.IsValid() { rv = v.FieldByName(a.name) } if !rv.IsValid() { panic(fmt.Sprintf("unknown accessor: %v.%s", v.Type(), a.name)) } if _, ok := rv.Interface().(protoreflect.Value); ok { rv = rv.MethodByName("Interface").Call(nil)[0] if !rv.IsNil() { rv = rv.Elem() } } // Ignore zero values. var isZero bool switch rv.Kind() { case reflect.Interface, reflect.Slice: isZero = rv.IsNil() case reflect.Bool: isZero = rv.Bool() == false case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: isZero = rv.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: isZero = rv.Uint() == 0 case reflect.String: isZero = rv.String() == "" } if n, ok := rv.Interface().(list); ok { isZero = n.Len() == 0 } if isZero { continue } // Format the value. var s string v := rv.Interface() switch v := v.(type) { case list: s = formatListOpt(v, false, rs.allowMulti) case protoreflect.FieldDescriptor, protoreflect.OneofDescriptor, protoreflect.EnumValueDescriptor, protoreflect.MethodDescriptor: s = string(v.(protoreflect.Descriptor).Name()) case protoreflect.Descriptor: s = string(v.FullName()) case string: s = strconv.Quote(v) case []byte: s = fmt.Sprintf("%q", v) default: s = fmt.Sprint(v) } rs.recs = append(rs.recs, [2]string{a.name, s}) } } func (rs *records) Join() string { var ss []string // In single line mode, simply join all records with commas. if !rs.allowMulti { for _, r := range rs.recs { ss = append(ss, r[0]+formatColon(0)+r[1]) } return joinStrings(ss, false) } // In allowMulti line mode, align single line records for more readable output. var maxLen int flush := func(i int) { for _, r := range rs.recs[len(ss):i] { ss = append(ss, r[0]+formatColon(maxLen-len(r[0]))+r[1]) } maxLen = 0 } for i, r := range rs.recs { if isMulti := strings.Contains(r[1], "\n"); isMulti { flush(i) ss = append(ss, r[0]+formatColon(0)+strings.Join(strings.Split(r[1], "\n"), "\n\t")) } else if maxLen < len(r[0]) { maxLen = len(r[0]) } } flush(len(rs.recs)) return joinStrings(ss, true) } func formatColon(padding int) string { // Deliberately introduce instability into the debug output to // discourage users from performing string comparisons. // This provides us flexibility to change the output in the future. if detrand.Bool() { return ":" + strings.Repeat(" ", 1+padding) // use non-breaking spaces (U+00a0) } else { return ":" + strings.Repeat(" ", 1+padding) // use regular spaces (U+0020) } } func joinStrings(ss []string, isMulti bool) string { if len(ss) == 0 { return "" } if isMulti { return "\n\t" + strings.Join(ss, "\n\t") + "\n" } return strings.Join(ss, ", ") }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/detrand/rand.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/detrand/rand.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package detrand provides deterministically random functionality. // // The pseudo-randomness of these functions is seeded by the program binary // itself and guarantees that the output does not change within a program, // while ensuring that the output is unstable across different builds. package detrand import ( "encoding/binary" "hash/fnv" "os" ) // Disable disables detrand such that all functions returns the zero value. // This function is not concurrent-safe and must be called during program init. func Disable() { randSeed = 0 } // Bool returns a deterministically random boolean. func Bool() bool { return randSeed%2 == 1 } // Intn returns a deterministically random integer between 0 and n-1, inclusive. func Intn(n int) int { if n <= 0 { panic("must be positive") } return int(randSeed % uint64(n)) } // randSeed is a best-effort at an approximate hash of the Go binary. var randSeed = binaryHash() func binaryHash() uint64 { // Open the Go binary. s, err := os.Executable() if err != nil { return 0 } f, err := os.Open(s) if err != nil { return 0 } defer f.Close() // Hash the size and several samples of the Go binary. const numSamples = 8 var buf [64]byte h := fnv.New64() fi, err := f.Stat() if err != nil { return 0 } binary.LittleEndian.PutUint64(buf[:8], uint64(fi.Size())) h.Write(buf[:8]) for i := int64(0); i < numSamples; i++ { if _, err := f.ReadAt(buf[:], i*fi.Size()/numSamples); err != nil { return 0 } h.Write(buf[:]) } return h.Sum64() }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/strs/strings_unsafe.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package strs import ( "unsafe" "google.golang.org/protobuf/reflect/protoreflect" ) // UnsafeString returns an unsafe string reference of b. // The caller must treat the input slice as immutable. // // WARNING: Use carefully. The returned result must not leak to the end user // unless the input slice is provably immutable. func UnsafeString(b []byte) string { return unsafe.String(unsafe.SliceData(b), len(b)) } // UnsafeBytes returns an unsafe bytes slice reference of s. // The caller must treat returned slice as immutable. // // WARNING: Use carefully. The returned result must not leak to the end user. func UnsafeBytes(s string) []byte { return unsafe.Slice(unsafe.StringData(s), len(s)) } // Builder builds a set of strings with shared lifetime. // This differs from strings.Builder, which is for building a single string. type Builder struct { buf []byte } // AppendFullName is equivalent to protoreflect.FullName.Append, // but optimized for large batches where each name has a shared lifetime. func (sb *Builder) AppendFullName(prefix protoreflect.FullName, name protoreflect.Name) protoreflect.FullName { n := len(prefix) + len(".") + len(name) if len(prefix) == 0 { n -= len(".") } sb.grow(n) sb.buf = append(sb.buf, prefix...) sb.buf = append(sb.buf, '.') sb.buf = append(sb.buf, name...) return protoreflect.FullName(sb.last(n)) } // MakeString is equivalent to string(b), but optimized for large batches // with a shared lifetime. func (sb *Builder) MakeString(b []byte) string { sb.grow(len(b)) sb.buf = append(sb.buf, b...) return sb.last(len(b)) } func (sb *Builder) grow(n int) { if cap(sb.buf)-len(sb.buf) >= n { return } // Unlike strings.Builder, we do not need to copy over the contents // of the old buffer since our builder provides no API for // retrieving previously created strings. sb.buf = make([]byte, 0, 2*(cap(sb.buf)+n)) } func (sb *Builder) last(n int) string { return UnsafeString(sb.buf[len(sb.buf)-n:]) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/strs/strings.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/strs/strings.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package strs provides string manipulation functionality specific to protobuf. package strs import ( "go/token" "strings" "unicode" "unicode/utf8" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/reflect/protoreflect" ) // EnforceUTF8 reports whether to enforce strict UTF-8 validation. func EnforceUTF8(fd protoreflect.FieldDescriptor) bool { if flags.ProtoLegacy || fd.Syntax() == protoreflect.Editions { if fd, ok := fd.(interface{ EnforceUTF8() bool }); ok { return fd.EnforceUTF8() } } return fd.Syntax() == protoreflect.Proto3 } // GoCamelCase camel-cases a protobuf name for use as a Go identifier. // // If there is an interior underscore followed by a lower case letter, // drop the underscore and convert the letter to upper case. func GoCamelCase(s string) string { // Invariant: if the next letter is lower case, it must be converted // to upper case. // That is, we process a word at a time, where words are marked by _ or // upper case letter. Digits are treated as words. var b []byte for i := 0; i < len(s); i++ { c := s[i] switch { case c == '.' && i+1 < len(s) && isASCIILower(s[i+1]): // Skip over '.' in ".{{lowercase}}". case c == '.': b = append(b, '_') // convert '.' to '_' case c == '_' && (i == 0 || s[i-1] == '.'): // Convert initial '_' to ensure we start with a capital letter. // Do the same for '_' after '.' to match historic behavior. b = append(b, 'X') // convert '_' to 'X' case c == '_' && i+1 < len(s) && isASCIILower(s[i+1]): // Skip over '_' in "_{{lowercase}}". case isASCIIDigit(c): b = append(b, c) default: // Assume we have a letter now - if not, it's a bogus identifier. // The next word is a sequence of characters that must start upper case. if isASCIILower(c) { c -= 'a' - 'A' // convert lowercase to uppercase } b = append(b, c) // Accept lower case sequence that follows. for ; i+1 < len(s) && isASCIILower(s[i+1]); i++ { b = append(b, s[i+1]) } } } return string(b) } // GoSanitized converts a string to a valid Go identifier. func GoSanitized(s string) string { // Sanitize the input to the set of valid characters, // which must be '_' or be in the Unicode L or N categories. s = strings.Map(func(r rune) rune { if unicode.IsLetter(r) || unicode.IsDigit(r) { return r } return '_' }, s) // Prepend '_' in the event of a Go keyword conflict or if // the identifier is invalid (does not start in the Unicode L category). r, _ := utf8.DecodeRuneInString(s) if token.Lookup(s).IsKeyword() || !unicode.IsLetter(r) { return "_" + s } return s } // JSONCamelCase converts a snake_case identifier to a camelCase identifier, // according to the protobuf JSON specification. func JSONCamelCase(s string) string { var b []byte var wasUnderscore bool for i := 0; i < len(s); i++ { // proto identifiers are always ASCII c := s[i] if c != '_' { if wasUnderscore && isASCIILower(c) { c -= 'a' - 'A' // convert to uppercase } b = append(b, c) } wasUnderscore = c == '_' } return string(b) } // JSONSnakeCase converts a camelCase identifier to a snake_case identifier, // according to the protobuf JSON specification. func JSONSnakeCase(s string) string { var b []byte for i := 0; i < len(s); i++ { // proto identifiers are always ASCII c := s[i] if isASCIIUpper(c) { b = append(b, '_') c += 'a' - 'A' // convert to lowercase } b = append(b, c) } return string(b) } // MapEntryName derives the name of the map entry message given the field name. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:254-276,6057 func MapEntryName(s string) string { var b []byte upperNext := true for _, c := range s { switch { case c == '_': upperNext = true case upperNext: b = append(b, byte(unicode.ToUpper(c))) upperNext = false default: b = append(b, byte(c)) } } b = append(b, "Entry"...) return string(b) } // EnumValueName derives the camel-cased enum value name. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:297-313 func EnumValueName(s string) string { var b []byte upperNext := true for _, c := range s { switch { case c == '_': upperNext = true case upperNext: b = append(b, byte(unicode.ToUpper(c))) upperNext = false default: b = append(b, byte(unicode.ToLower(c))) upperNext = false } } return string(b) } // TrimEnumPrefix trims the enum name prefix from an enum value name, // where the prefix is all lowercase without underscores. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:330-375 func TrimEnumPrefix(s, prefix string) string { s0 := s // original input for len(s) > 0 && len(prefix) > 0 { if s[0] == '_' { s = s[1:] continue } if unicode.ToLower(rune(s[0])) != rune(prefix[0]) { return s0 // no prefix match } s, prefix = s[1:], prefix[1:] } if len(prefix) > 0 { return s0 // no prefix match } s = strings.TrimLeft(s, "_") if len(s) == 0 { return s0 // avoid returning empty string } return s } func isASCIILower(c byte) bool { return 'a' <= c && c <= 'z' } func isASCIIUpper(c byte) bool { return 'A' <= c && c <= 'Z' } func isASCIIDigit(c byte) bool { return '0' <= c && c <= '9' }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/order/order.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/order/order.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package order import ( "google.golang.org/protobuf/reflect/protoreflect" ) // FieldOrder specifies the ordering to visit message fields. // It is a function that reports whether x is ordered before y. type FieldOrder func(x, y protoreflect.FieldDescriptor) bool var ( // AnyFieldOrder specifies no specific field ordering. AnyFieldOrder FieldOrder = nil // LegacyFieldOrder sorts fields in the same ordering as emitted by // wire serialization in the github.com/golang/protobuf implementation. LegacyFieldOrder FieldOrder = func(x, y protoreflect.FieldDescriptor) bool { ox, oy := x.ContainingOneof(), y.ContainingOneof() inOneof := func(od protoreflect.OneofDescriptor) bool { return od != nil && !od.IsSynthetic() } // Extension fields sort before non-extension fields. if x.IsExtension() != y.IsExtension() { return x.IsExtension() && !y.IsExtension() } // Fields not within a oneof sort before those within a oneof. if inOneof(ox) != inOneof(oy) { return !inOneof(ox) && inOneof(oy) } // Fields in disjoint oneof sets are sorted by declaration index. if inOneof(ox) && inOneof(oy) && ox != oy { return ox.Index() < oy.Index() } // Fields sorted by field number. return x.Number() < y.Number() } // NumberFieldOrder sorts fields by their field number. NumberFieldOrder FieldOrder = func(x, y protoreflect.FieldDescriptor) bool { return x.Number() < y.Number() } // IndexNameFieldOrder sorts non-extension fields before extension fields. // Non-extensions are sorted according to their declaration index. // Extensions are sorted according to their full name. IndexNameFieldOrder FieldOrder = func(x, y protoreflect.FieldDescriptor) bool { // Non-extension fields sort before extension fields. if x.IsExtension() != y.IsExtension() { return !x.IsExtension() && y.IsExtension() } // Extensions sorted by fullname. if x.IsExtension() && y.IsExtension() { return x.FullName() < y.FullName() } // Non-extensions sorted by declaration index. return x.Index() < y.Index() } ) // KeyOrder specifies the ordering to visit map entries. // It is a function that reports whether x is ordered before y. type KeyOrder func(x, y protoreflect.MapKey) bool var ( // AnyKeyOrder specifies no specific key ordering. AnyKeyOrder KeyOrder = nil // GenericKeyOrder sorts false before true, numeric keys in ascending order, // and strings in lexicographical ordering according to UTF-8 codepoints. GenericKeyOrder KeyOrder = func(x, y protoreflect.MapKey) bool { switch x.Interface().(type) { case bool: return !x.Bool() && y.Bool() case int32, int64: return x.Int() < y.Int() case uint32, uint64: return x.Uint() < y.Uint() case string: return x.String() < y.String() default: panic("invalid map key type") } } )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/order/range.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/order/range.go
// Copyright 2020 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package order provides ordered access to messages and maps. package order import ( "sort" "sync" "google.golang.org/protobuf/reflect/protoreflect" ) type messageField struct { fd protoreflect.FieldDescriptor v protoreflect.Value } var messageFieldPool = sync.Pool{ New: func() any { return new([]messageField) }, } type ( // FieldRnger is an interface for visiting all fields in a message. // The protoreflect.Message type implements this interface. FieldRanger interface{ Range(VisitField) } // VisitField is called every time a message field is visited. VisitField = func(protoreflect.FieldDescriptor, protoreflect.Value) bool ) // RangeFields iterates over the fields of fs according to the specified order. func RangeFields(fs FieldRanger, less FieldOrder, fn VisitField) { if less == nil { fs.Range(fn) return } // Obtain a pre-allocated scratch buffer. p := messageFieldPool.Get().(*[]messageField) fields := (*p)[:0] defer func() { if cap(fields) < 1024 { *p = fields messageFieldPool.Put(p) } }() // Collect all fields in the message and sort them. fs.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { fields = append(fields, messageField{fd, v}) return true }) sort.Slice(fields, func(i, j int) bool { return less(fields[i].fd, fields[j].fd) }) // Visit the fields in the specified ordering. for _, f := range fields { if !fn(f.fd, f.v) { return } } } type mapEntry struct { k protoreflect.MapKey v protoreflect.Value } var mapEntryPool = sync.Pool{ New: func() any { return new([]mapEntry) }, } type ( // EntryRanger is an interface for visiting all fields in a message. // The protoreflect.Map type implements this interface. EntryRanger interface{ Range(VisitEntry) } // VisitEntry is called every time a map entry is visited. VisitEntry = func(protoreflect.MapKey, protoreflect.Value) bool ) // RangeEntries iterates over the entries of es according to the specified order. func RangeEntries(es EntryRanger, less KeyOrder, fn VisitEntry) { if less == nil { es.Range(fn) return } // Obtain a pre-allocated scratch buffer. p := mapEntryPool.Get().(*[]mapEntry) entries := (*p)[:0] defer func() { if cap(entries) < 1024 { *p = entries mapEntryPool.Put(p) } }() // Collect all entries in the map and sort them. es.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { entries = append(entries, mapEntry{k, v}) return true }) sort.Slice(entries, func(i, j int) bool { return less(entries[i].k, entries[j].k) }) // Visit the entries in the specified ordering. for _, e := range entries { if !fn(e.k, e.v) { return } } }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/field_mask_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_field_mask_proto = "google/protobuf/field_mask.proto" // Names for google.protobuf.FieldMask. const ( FieldMask_message_name protoreflect.Name = "FieldMask" FieldMask_message_fullname protoreflect.FullName = "google.protobuf.FieldMask" ) // Field names for google.protobuf.FieldMask. const ( FieldMask_Paths_field_name protoreflect.Name = "paths" FieldMask_Paths_field_fullname protoreflect.FullName = "google.protobuf.FieldMask.paths" ) // Field numbers for google.protobuf.FieldMask. const ( FieldMask_Paths_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/goname.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/goname.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid // Go names of implementation-specific struct fields in generated messages. const ( State_goname = "state" SizeCache_goname = "sizeCache" SizeCacheA_goname = "XXX_sizecache" UnknownFields_goname = "unknownFields" UnknownFieldsA_goname = "XXX_unrecognized" ExtensionFields_goname = "extensionFields" ExtensionFieldsA_goname = "XXX_InternalExtensions" ExtensionFieldsB_goname = "XXX_extensions" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/any_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/any_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_any_proto = "google/protobuf/any.proto" // Names for google.protobuf.Any. const ( Any_message_name protoreflect.Name = "Any" Any_message_fullname protoreflect.FullName = "google.protobuf.Any" ) // Field names for google.protobuf.Any. const ( Any_TypeUrl_field_name protoreflect.Name = "type_url" Any_Value_field_name protoreflect.Name = "value" Any_TypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Any.type_url" Any_Value_field_fullname protoreflect.FullName = "google.protobuf.Any.value" ) // Field numbers for google.protobuf.Any. const ( Any_TypeUrl_field_number protoreflect.FieldNumber = 1 Any_Value_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/duration_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/duration_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_duration_proto = "google/protobuf/duration.proto" // Names for google.protobuf.Duration. const ( Duration_message_name protoreflect.Name = "Duration" Duration_message_fullname protoreflect.FullName = "google.protobuf.Duration" ) // Field names for google.protobuf.Duration. const ( Duration_Seconds_field_name protoreflect.Name = "seconds" Duration_Nanos_field_name protoreflect.Name = "nanos" Duration_Seconds_field_fullname protoreflect.FullName = "google.protobuf.Duration.seconds" Duration_Nanos_field_fullname protoreflect.FullName = "google.protobuf.Duration.nanos" ) // Field numbers for google.protobuf.Duration. const ( Duration_Seconds_field_number protoreflect.FieldNumber = 1 Duration_Nanos_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/descriptor_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_descriptor_proto = "google/protobuf/descriptor.proto" // Full and short names for google.protobuf.Edition. const ( Edition_enum_fullname = "google.protobuf.Edition" Edition_enum_name = "Edition" ) // Enum values for google.protobuf.Edition. const ( Edition_EDITION_UNKNOWN_enum_value = 0 Edition_EDITION_LEGACY_enum_value = 900 Edition_EDITION_PROTO2_enum_value = 998 Edition_EDITION_PROTO3_enum_value = 999 Edition_EDITION_2023_enum_value = 1000 Edition_EDITION_2024_enum_value = 1001 Edition_EDITION_1_TEST_ONLY_enum_value = 1 Edition_EDITION_2_TEST_ONLY_enum_value = 2 Edition_EDITION_99997_TEST_ONLY_enum_value = 99997 Edition_EDITION_99998_TEST_ONLY_enum_value = 99998 Edition_EDITION_99999_TEST_ONLY_enum_value = 99999 Edition_EDITION_MAX_enum_value = 2147483647 ) // Full and short names for google.protobuf.SymbolVisibility. const ( SymbolVisibility_enum_fullname = "google.protobuf.SymbolVisibility" SymbolVisibility_enum_name = "SymbolVisibility" ) // Enum values for google.protobuf.SymbolVisibility. const ( SymbolVisibility_VISIBILITY_UNSET_enum_value = 0 SymbolVisibility_VISIBILITY_LOCAL_enum_value = 1 SymbolVisibility_VISIBILITY_EXPORT_enum_value = 2 ) // Names for google.protobuf.FileDescriptorSet. const ( FileDescriptorSet_message_name protoreflect.Name = "FileDescriptorSet" FileDescriptorSet_message_fullname protoreflect.FullName = "google.protobuf.FileDescriptorSet" ) // Field names for google.protobuf.FileDescriptorSet. const ( FileDescriptorSet_File_field_name protoreflect.Name = "file" FileDescriptorSet_File_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorSet.file" ) // Field numbers for google.protobuf.FileDescriptorSet. const ( FileDescriptorSet_File_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.FileDescriptorProto. const ( FileDescriptorProto_message_name protoreflect.Name = "FileDescriptorProto" FileDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto" ) // Field names for google.protobuf.FileDescriptorProto. const ( FileDescriptorProto_Name_field_name protoreflect.Name = "name" FileDescriptorProto_Package_field_name protoreflect.Name = "package" FileDescriptorProto_Dependency_field_name protoreflect.Name = "dependency" FileDescriptorProto_PublicDependency_field_name protoreflect.Name = "public_dependency" FileDescriptorProto_WeakDependency_field_name protoreflect.Name = "weak_dependency" FileDescriptorProto_OptionDependency_field_name protoreflect.Name = "option_dependency" FileDescriptorProto_MessageType_field_name protoreflect.Name = "message_type" FileDescriptorProto_EnumType_field_name protoreflect.Name = "enum_type" FileDescriptorProto_Service_field_name protoreflect.Name = "service" FileDescriptorProto_Extension_field_name protoreflect.Name = "extension" FileDescriptorProto_Options_field_name protoreflect.Name = "options" FileDescriptorProto_SourceCodeInfo_field_name protoreflect.Name = "source_code_info" FileDescriptorProto_Syntax_field_name protoreflect.Name = "syntax" FileDescriptorProto_Edition_field_name protoreflect.Name = "edition" FileDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.name" FileDescriptorProto_Package_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.package" FileDescriptorProto_Dependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.dependency" FileDescriptorProto_PublicDependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.public_dependency" FileDescriptorProto_WeakDependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.weak_dependency" FileDescriptorProto_OptionDependency_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.option_dependency" FileDescriptorProto_MessageType_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.message_type" FileDescriptorProto_EnumType_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.enum_type" FileDescriptorProto_Service_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.service" FileDescriptorProto_Extension_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.extension" FileDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.options" FileDescriptorProto_SourceCodeInfo_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.source_code_info" FileDescriptorProto_Syntax_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.syntax" FileDescriptorProto_Edition_field_fullname protoreflect.FullName = "google.protobuf.FileDescriptorProto.edition" ) // Field numbers for google.protobuf.FileDescriptorProto. const ( FileDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 FileDescriptorProto_Package_field_number protoreflect.FieldNumber = 2 FileDescriptorProto_Dependency_field_number protoreflect.FieldNumber = 3 FileDescriptorProto_PublicDependency_field_number protoreflect.FieldNumber = 10 FileDescriptorProto_WeakDependency_field_number protoreflect.FieldNumber = 11 FileDescriptorProto_OptionDependency_field_number protoreflect.FieldNumber = 15 FileDescriptorProto_MessageType_field_number protoreflect.FieldNumber = 4 FileDescriptorProto_EnumType_field_number protoreflect.FieldNumber = 5 FileDescriptorProto_Service_field_number protoreflect.FieldNumber = 6 FileDescriptorProto_Extension_field_number protoreflect.FieldNumber = 7 FileDescriptorProto_Options_field_number protoreflect.FieldNumber = 8 FileDescriptorProto_SourceCodeInfo_field_number protoreflect.FieldNumber = 9 FileDescriptorProto_Syntax_field_number protoreflect.FieldNumber = 12 FileDescriptorProto_Edition_field_number protoreflect.FieldNumber = 14 ) // Names for google.protobuf.DescriptorProto. const ( DescriptorProto_message_name protoreflect.Name = "DescriptorProto" DescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto" ) // Field names for google.protobuf.DescriptorProto. const ( DescriptorProto_Name_field_name protoreflect.Name = "name" DescriptorProto_Field_field_name protoreflect.Name = "field" DescriptorProto_Extension_field_name protoreflect.Name = "extension" DescriptorProto_NestedType_field_name protoreflect.Name = "nested_type" DescriptorProto_EnumType_field_name protoreflect.Name = "enum_type" DescriptorProto_ExtensionRange_field_name protoreflect.Name = "extension_range" DescriptorProto_OneofDecl_field_name protoreflect.Name = "oneof_decl" DescriptorProto_Options_field_name protoreflect.Name = "options" DescriptorProto_ReservedRange_field_name protoreflect.Name = "reserved_range" DescriptorProto_ReservedName_field_name protoreflect.Name = "reserved_name" DescriptorProto_Visibility_field_name protoreflect.Name = "visibility" DescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.name" DescriptorProto_Field_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.field" DescriptorProto_Extension_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.extension" DescriptorProto_NestedType_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.nested_type" DescriptorProto_EnumType_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.enum_type" DescriptorProto_ExtensionRange_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.extension_range" DescriptorProto_OneofDecl_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.oneof_decl" DescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.options" DescriptorProto_ReservedRange_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.reserved_range" DescriptorProto_ReservedName_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.reserved_name" DescriptorProto_Visibility_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.visibility" ) // Field numbers for google.protobuf.DescriptorProto. const ( DescriptorProto_Name_field_number protoreflect.FieldNumber = 1 DescriptorProto_Field_field_number protoreflect.FieldNumber = 2 DescriptorProto_Extension_field_number protoreflect.FieldNumber = 6 DescriptorProto_NestedType_field_number protoreflect.FieldNumber = 3 DescriptorProto_EnumType_field_number protoreflect.FieldNumber = 4 DescriptorProto_ExtensionRange_field_number protoreflect.FieldNumber = 5 DescriptorProto_OneofDecl_field_number protoreflect.FieldNumber = 8 DescriptorProto_Options_field_number protoreflect.FieldNumber = 7 DescriptorProto_ReservedRange_field_number protoreflect.FieldNumber = 9 DescriptorProto_ReservedName_field_number protoreflect.FieldNumber = 10 DescriptorProto_Visibility_field_number protoreflect.FieldNumber = 11 ) // Names for google.protobuf.DescriptorProto.ExtensionRange. const ( DescriptorProto_ExtensionRange_message_name protoreflect.Name = "ExtensionRange" DescriptorProto_ExtensionRange_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange" ) // Field names for google.protobuf.DescriptorProto.ExtensionRange. const ( DescriptorProto_ExtensionRange_Start_field_name protoreflect.Name = "start" DescriptorProto_ExtensionRange_End_field_name protoreflect.Name = "end" DescriptorProto_ExtensionRange_Options_field_name protoreflect.Name = "options" DescriptorProto_ExtensionRange_Start_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.start" DescriptorProto_ExtensionRange_End_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.end" DescriptorProto_ExtensionRange_Options_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ExtensionRange.options" ) // Field numbers for google.protobuf.DescriptorProto.ExtensionRange. const ( DescriptorProto_ExtensionRange_Start_field_number protoreflect.FieldNumber = 1 DescriptorProto_ExtensionRange_End_field_number protoreflect.FieldNumber = 2 DescriptorProto_ExtensionRange_Options_field_number protoreflect.FieldNumber = 3 ) // Names for google.protobuf.DescriptorProto.ReservedRange. const ( DescriptorProto_ReservedRange_message_name protoreflect.Name = "ReservedRange" DescriptorProto_ReservedRange_message_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange" ) // Field names for google.protobuf.DescriptorProto.ReservedRange. const ( DescriptorProto_ReservedRange_Start_field_name protoreflect.Name = "start" DescriptorProto_ReservedRange_End_field_name protoreflect.Name = "end" DescriptorProto_ReservedRange_Start_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange.start" DescriptorProto_ReservedRange_End_field_fullname protoreflect.FullName = "google.protobuf.DescriptorProto.ReservedRange.end" ) // Field numbers for google.protobuf.DescriptorProto.ReservedRange. const ( DescriptorProto_ReservedRange_Start_field_number protoreflect.FieldNumber = 1 DescriptorProto_ReservedRange_End_field_number protoreflect.FieldNumber = 2 ) // Names for google.protobuf.ExtensionRangeOptions. const ( ExtensionRangeOptions_message_name protoreflect.Name = "ExtensionRangeOptions" ExtensionRangeOptions_message_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions" ) // Field names for google.protobuf.ExtensionRangeOptions. const ( ExtensionRangeOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" ExtensionRangeOptions_Declaration_field_name protoreflect.Name = "declaration" ExtensionRangeOptions_Features_field_name protoreflect.Name = "features" ExtensionRangeOptions_Verification_field_name protoreflect.Name = "verification" ExtensionRangeOptions_UninterpretedOption_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.uninterpreted_option" ExtensionRangeOptions_Declaration_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.declaration" ExtensionRangeOptions_Features_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.features" ExtensionRangeOptions_Verification_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.verification" ) // Field numbers for google.protobuf.ExtensionRangeOptions. const ( ExtensionRangeOptions_UninterpretedOption_field_number protoreflect.FieldNumber = 999 ExtensionRangeOptions_Declaration_field_number protoreflect.FieldNumber = 2 ExtensionRangeOptions_Features_field_number protoreflect.FieldNumber = 50 ExtensionRangeOptions_Verification_field_number protoreflect.FieldNumber = 3 ) // Full and short names for google.protobuf.ExtensionRangeOptions.VerificationState. const ( ExtensionRangeOptions_VerificationState_enum_fullname = "google.protobuf.ExtensionRangeOptions.VerificationState" ExtensionRangeOptions_VerificationState_enum_name = "VerificationState" ) // Enum values for google.protobuf.ExtensionRangeOptions.VerificationState. const ( ExtensionRangeOptions_DECLARATION_enum_value = 0 ExtensionRangeOptions_UNVERIFIED_enum_value = 1 ) // Names for google.protobuf.ExtensionRangeOptions.Declaration. const ( ExtensionRangeOptions_Declaration_message_name protoreflect.Name = "Declaration" ExtensionRangeOptions_Declaration_message_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration" ) // Field names for google.protobuf.ExtensionRangeOptions.Declaration. const ( ExtensionRangeOptions_Declaration_Number_field_name protoreflect.Name = "number" ExtensionRangeOptions_Declaration_FullName_field_name protoreflect.Name = "full_name" ExtensionRangeOptions_Declaration_Type_field_name protoreflect.Name = "type" ExtensionRangeOptions_Declaration_Reserved_field_name protoreflect.Name = "reserved" ExtensionRangeOptions_Declaration_Repeated_field_name protoreflect.Name = "repeated" ExtensionRangeOptions_Declaration_Number_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration.number" ExtensionRangeOptions_Declaration_FullName_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration.full_name" ExtensionRangeOptions_Declaration_Type_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration.type" ExtensionRangeOptions_Declaration_Reserved_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration.reserved" ExtensionRangeOptions_Declaration_Repeated_field_fullname protoreflect.FullName = "google.protobuf.ExtensionRangeOptions.Declaration.repeated" ) // Field numbers for google.protobuf.ExtensionRangeOptions.Declaration. const ( ExtensionRangeOptions_Declaration_Number_field_number protoreflect.FieldNumber = 1 ExtensionRangeOptions_Declaration_FullName_field_number protoreflect.FieldNumber = 2 ExtensionRangeOptions_Declaration_Type_field_number protoreflect.FieldNumber = 3 ExtensionRangeOptions_Declaration_Reserved_field_number protoreflect.FieldNumber = 5 ExtensionRangeOptions_Declaration_Repeated_field_number protoreflect.FieldNumber = 6 ) // Names for google.protobuf.FieldDescriptorProto. const ( FieldDescriptorProto_message_name protoreflect.Name = "FieldDescriptorProto" FieldDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto" ) // Field names for google.protobuf.FieldDescriptorProto. const ( FieldDescriptorProto_Name_field_name protoreflect.Name = "name" FieldDescriptorProto_Number_field_name protoreflect.Name = "number" FieldDescriptorProto_Label_field_name protoreflect.Name = "label" FieldDescriptorProto_Type_field_name protoreflect.Name = "type" FieldDescriptorProto_TypeName_field_name protoreflect.Name = "type_name" FieldDescriptorProto_Extendee_field_name protoreflect.Name = "extendee" FieldDescriptorProto_DefaultValue_field_name protoreflect.Name = "default_value" FieldDescriptorProto_OneofIndex_field_name protoreflect.Name = "oneof_index" FieldDescriptorProto_JsonName_field_name protoreflect.Name = "json_name" FieldDescriptorProto_Options_field_name protoreflect.Name = "options" FieldDescriptorProto_Proto3Optional_field_name protoreflect.Name = "proto3_optional" FieldDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.name" FieldDescriptorProto_Number_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.number" FieldDescriptorProto_Label_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.label" FieldDescriptorProto_Type_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.type" FieldDescriptorProto_TypeName_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.type_name" FieldDescriptorProto_Extendee_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.extendee" FieldDescriptorProto_DefaultValue_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.default_value" FieldDescriptorProto_OneofIndex_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.oneof_index" FieldDescriptorProto_JsonName_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.json_name" FieldDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.options" FieldDescriptorProto_Proto3Optional_field_fullname protoreflect.FullName = "google.protobuf.FieldDescriptorProto.proto3_optional" ) // Field numbers for google.protobuf.FieldDescriptorProto. const ( FieldDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 FieldDescriptorProto_Number_field_number protoreflect.FieldNumber = 3 FieldDescriptorProto_Label_field_number protoreflect.FieldNumber = 4 FieldDescriptorProto_Type_field_number protoreflect.FieldNumber = 5 FieldDescriptorProto_TypeName_field_number protoreflect.FieldNumber = 6 FieldDescriptorProto_Extendee_field_number protoreflect.FieldNumber = 2 FieldDescriptorProto_DefaultValue_field_number protoreflect.FieldNumber = 7 FieldDescriptorProto_OneofIndex_field_number protoreflect.FieldNumber = 9 FieldDescriptorProto_JsonName_field_number protoreflect.FieldNumber = 10 FieldDescriptorProto_Options_field_number protoreflect.FieldNumber = 8 FieldDescriptorProto_Proto3Optional_field_number protoreflect.FieldNumber = 17 ) // Full and short names for google.protobuf.FieldDescriptorProto.Type. const ( FieldDescriptorProto_Type_enum_fullname = "google.protobuf.FieldDescriptorProto.Type" FieldDescriptorProto_Type_enum_name = "Type" ) // Enum values for google.protobuf.FieldDescriptorProto.Type. const ( FieldDescriptorProto_TYPE_DOUBLE_enum_value = 1 FieldDescriptorProto_TYPE_FLOAT_enum_value = 2 FieldDescriptorProto_TYPE_INT64_enum_value = 3 FieldDescriptorProto_TYPE_UINT64_enum_value = 4 FieldDescriptorProto_TYPE_INT32_enum_value = 5 FieldDescriptorProto_TYPE_FIXED64_enum_value = 6 FieldDescriptorProto_TYPE_FIXED32_enum_value = 7 FieldDescriptorProto_TYPE_BOOL_enum_value = 8 FieldDescriptorProto_TYPE_STRING_enum_value = 9 FieldDescriptorProto_TYPE_GROUP_enum_value = 10 FieldDescriptorProto_TYPE_MESSAGE_enum_value = 11 FieldDescriptorProto_TYPE_BYTES_enum_value = 12 FieldDescriptorProto_TYPE_UINT32_enum_value = 13 FieldDescriptorProto_TYPE_ENUM_enum_value = 14 FieldDescriptorProto_TYPE_SFIXED32_enum_value = 15 FieldDescriptorProto_TYPE_SFIXED64_enum_value = 16 FieldDescriptorProto_TYPE_SINT32_enum_value = 17 FieldDescriptorProto_TYPE_SINT64_enum_value = 18 ) // Full and short names for google.protobuf.FieldDescriptorProto.Label. const ( FieldDescriptorProto_Label_enum_fullname = "google.protobuf.FieldDescriptorProto.Label" FieldDescriptorProto_Label_enum_name = "Label" ) // Enum values for google.protobuf.FieldDescriptorProto.Label. const ( FieldDescriptorProto_LABEL_OPTIONAL_enum_value = 1 FieldDescriptorProto_LABEL_REPEATED_enum_value = 3 FieldDescriptorProto_LABEL_REQUIRED_enum_value = 2 ) // Names for google.protobuf.OneofDescriptorProto. const ( OneofDescriptorProto_message_name protoreflect.Name = "OneofDescriptorProto" OneofDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto" ) // Field names for google.protobuf.OneofDescriptorProto. const ( OneofDescriptorProto_Name_field_name protoreflect.Name = "name" OneofDescriptorProto_Options_field_name protoreflect.Name = "options" OneofDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto.name" OneofDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.OneofDescriptorProto.options" ) // Field numbers for google.protobuf.OneofDescriptorProto. const ( OneofDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 OneofDescriptorProto_Options_field_number protoreflect.FieldNumber = 2 ) // Names for google.protobuf.EnumDescriptorProto. const ( EnumDescriptorProto_message_name protoreflect.Name = "EnumDescriptorProto" EnumDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto" ) // Field names for google.protobuf.EnumDescriptorProto. const ( EnumDescriptorProto_Name_field_name protoreflect.Name = "name" EnumDescriptorProto_Value_field_name protoreflect.Name = "value" EnumDescriptorProto_Options_field_name protoreflect.Name = "options" EnumDescriptorProto_ReservedRange_field_name protoreflect.Name = "reserved_range" EnumDescriptorProto_ReservedName_field_name protoreflect.Name = "reserved_name" EnumDescriptorProto_Visibility_field_name protoreflect.Name = "visibility" EnumDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.name" EnumDescriptorProto_Value_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.value" EnumDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.options" EnumDescriptorProto_ReservedRange_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.reserved_range" EnumDescriptorProto_ReservedName_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.reserved_name" EnumDescriptorProto_Visibility_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.visibility" ) // Field numbers for google.protobuf.EnumDescriptorProto. const ( EnumDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 EnumDescriptorProto_Value_field_number protoreflect.FieldNumber = 2 EnumDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 EnumDescriptorProto_ReservedRange_field_number protoreflect.FieldNumber = 4 EnumDescriptorProto_ReservedName_field_number protoreflect.FieldNumber = 5 EnumDescriptorProto_Visibility_field_number protoreflect.FieldNumber = 6 ) // Names for google.protobuf.EnumDescriptorProto.EnumReservedRange. const ( EnumDescriptorProto_EnumReservedRange_message_name protoreflect.Name = "EnumReservedRange" EnumDescriptorProto_EnumReservedRange_message_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange" ) // Field names for google.protobuf.EnumDescriptorProto.EnumReservedRange. const ( EnumDescriptorProto_EnumReservedRange_Start_field_name protoreflect.Name = "start" EnumDescriptorProto_EnumReservedRange_End_field_name protoreflect.Name = "end" EnumDescriptorProto_EnumReservedRange_Start_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange.start" EnumDescriptorProto_EnumReservedRange_End_field_fullname protoreflect.FullName = "google.protobuf.EnumDescriptorProto.EnumReservedRange.end" ) // Field numbers for google.protobuf.EnumDescriptorProto.EnumReservedRange. const ( EnumDescriptorProto_EnumReservedRange_Start_field_number protoreflect.FieldNumber = 1 EnumDescriptorProto_EnumReservedRange_End_field_number protoreflect.FieldNumber = 2 ) // Names for google.protobuf.EnumValueDescriptorProto. const ( EnumValueDescriptorProto_message_name protoreflect.Name = "EnumValueDescriptorProto" EnumValueDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto" ) // Field names for google.protobuf.EnumValueDescriptorProto. const ( EnumValueDescriptorProto_Name_field_name protoreflect.Name = "name" EnumValueDescriptorProto_Number_field_name protoreflect.Name = "number" EnumValueDescriptorProto_Options_field_name protoreflect.Name = "options" EnumValueDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.name" EnumValueDescriptorProto_Number_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.number" EnumValueDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumValueDescriptorProto.options" ) // Field numbers for google.protobuf.EnumValueDescriptorProto. const ( EnumValueDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 EnumValueDescriptorProto_Number_field_number protoreflect.FieldNumber = 2 EnumValueDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 ) // Names for google.protobuf.ServiceDescriptorProto. const ( ServiceDescriptorProto_message_name protoreflect.Name = "ServiceDescriptorProto" ServiceDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto" ) // Field names for google.protobuf.ServiceDescriptorProto. const ( ServiceDescriptorProto_Name_field_name protoreflect.Name = "name" ServiceDescriptorProto_Method_field_name protoreflect.Name = "method" ServiceDescriptorProto_Options_field_name protoreflect.Name = "options" ServiceDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.name" ServiceDescriptorProto_Method_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.method" ServiceDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.ServiceDescriptorProto.options" ) // Field numbers for google.protobuf.ServiceDescriptorProto. const ( ServiceDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 ServiceDescriptorProto_Method_field_number protoreflect.FieldNumber = 2 ServiceDescriptorProto_Options_field_number protoreflect.FieldNumber = 3 ) // Names for google.protobuf.MethodDescriptorProto. const ( MethodDescriptorProto_message_name protoreflect.Name = "MethodDescriptorProto" MethodDescriptorProto_message_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto" ) // Field names for google.protobuf.MethodDescriptorProto. const ( MethodDescriptorProto_Name_field_name protoreflect.Name = "name" MethodDescriptorProto_InputType_field_name protoreflect.Name = "input_type" MethodDescriptorProto_OutputType_field_name protoreflect.Name = "output_type" MethodDescriptorProto_Options_field_name protoreflect.Name = "options" MethodDescriptorProto_ClientStreaming_field_name protoreflect.Name = "client_streaming" MethodDescriptorProto_ServerStreaming_field_name protoreflect.Name = "server_streaming" MethodDescriptorProto_Name_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.name" MethodDescriptorProto_InputType_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.input_type" MethodDescriptorProto_OutputType_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.output_type" MethodDescriptorProto_Options_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.options" MethodDescriptorProto_ClientStreaming_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.client_streaming" MethodDescriptorProto_ServerStreaming_field_fullname protoreflect.FullName = "google.protobuf.MethodDescriptorProto.server_streaming" ) // Field numbers for google.protobuf.MethodDescriptorProto. const ( MethodDescriptorProto_Name_field_number protoreflect.FieldNumber = 1 MethodDescriptorProto_InputType_field_number protoreflect.FieldNumber = 2 MethodDescriptorProto_OutputType_field_number protoreflect.FieldNumber = 3 MethodDescriptorProto_Options_field_number protoreflect.FieldNumber = 4 MethodDescriptorProto_ClientStreaming_field_number protoreflect.FieldNumber = 5 MethodDescriptorProto_ServerStreaming_field_number protoreflect.FieldNumber = 6 ) // Names for google.protobuf.FileOptions. const ( FileOptions_message_name protoreflect.Name = "FileOptions" FileOptions_message_fullname protoreflect.FullName = "google.protobuf.FileOptions" ) // Field names for google.protobuf.FileOptions. const ( FileOptions_JavaPackage_field_name protoreflect.Name = "java_package" FileOptions_JavaOuterClassname_field_name protoreflect.Name = "java_outer_classname" FileOptions_JavaMultipleFiles_field_name protoreflect.Name = "java_multiple_files" FileOptions_JavaGenerateEqualsAndHash_field_name protoreflect.Name = "java_generate_equals_and_hash" FileOptions_JavaStringCheckUtf8_field_name protoreflect.Name = "java_string_check_utf8" FileOptions_OptimizeFor_field_name protoreflect.Name = "optimize_for" FileOptions_GoPackage_field_name protoreflect.Name = "go_package" FileOptions_CcGenericServices_field_name protoreflect.Name = "cc_generic_services" FileOptions_JavaGenericServices_field_name protoreflect.Name = "java_generic_services" FileOptions_PyGenericServices_field_name protoreflect.Name = "py_generic_services" FileOptions_Deprecated_field_name protoreflect.Name = "deprecated" FileOptions_CcEnableArenas_field_name protoreflect.Name = "cc_enable_arenas" FileOptions_ObjcClassPrefix_field_name protoreflect.Name = "objc_class_prefix" FileOptions_CsharpNamespace_field_name protoreflect.Name = "csharp_namespace" FileOptions_SwiftPrefix_field_name protoreflect.Name = "swift_prefix" FileOptions_PhpClassPrefix_field_name protoreflect.Name = "php_class_prefix" FileOptions_PhpNamespace_field_name protoreflect.Name = "php_namespace" FileOptions_PhpMetadataNamespace_field_name protoreflect.Name = "php_metadata_namespace" FileOptions_RubyPackage_field_name protoreflect.Name = "ruby_package" FileOptions_Features_field_name protoreflect.Name = "features" FileOptions_UninterpretedOption_field_name protoreflect.Name = "uninterpreted_option" FileOptions_JavaPackage_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_package" FileOptions_JavaOuterClassname_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_outer_classname" FileOptions_JavaMultipleFiles_field_fullname protoreflect.FullName = "google.protobuf.FileOptions.java_multiple_files"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/type_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/type_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_type_proto = "google/protobuf/type.proto" // Full and short names for google.protobuf.Syntax. const ( Syntax_enum_fullname = "google.protobuf.Syntax" Syntax_enum_name = "Syntax" ) // Enum values for google.protobuf.Syntax. const ( Syntax_SYNTAX_PROTO2_enum_value = 0 Syntax_SYNTAX_PROTO3_enum_value = 1 Syntax_SYNTAX_EDITIONS_enum_value = 2 ) // Names for google.protobuf.Type. const ( Type_message_name protoreflect.Name = "Type" Type_message_fullname protoreflect.FullName = "google.protobuf.Type" ) // Field names for google.protobuf.Type. const ( Type_Name_field_name protoreflect.Name = "name" Type_Fields_field_name protoreflect.Name = "fields" Type_Oneofs_field_name protoreflect.Name = "oneofs" Type_Options_field_name protoreflect.Name = "options" Type_SourceContext_field_name protoreflect.Name = "source_context" Type_Syntax_field_name protoreflect.Name = "syntax" Type_Edition_field_name protoreflect.Name = "edition" Type_Name_field_fullname protoreflect.FullName = "google.protobuf.Type.name" Type_Fields_field_fullname protoreflect.FullName = "google.protobuf.Type.fields" Type_Oneofs_field_fullname protoreflect.FullName = "google.protobuf.Type.oneofs" Type_Options_field_fullname protoreflect.FullName = "google.protobuf.Type.options" Type_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Type.source_context" Type_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Type.syntax" Type_Edition_field_fullname protoreflect.FullName = "google.protobuf.Type.edition" ) // Field numbers for google.protobuf.Type. const ( Type_Name_field_number protoreflect.FieldNumber = 1 Type_Fields_field_number protoreflect.FieldNumber = 2 Type_Oneofs_field_number protoreflect.FieldNumber = 3 Type_Options_field_number protoreflect.FieldNumber = 4 Type_SourceContext_field_number protoreflect.FieldNumber = 5 Type_Syntax_field_number protoreflect.FieldNumber = 6 Type_Edition_field_number protoreflect.FieldNumber = 7 ) // Names for google.protobuf.Field. const ( Field_message_name protoreflect.Name = "Field" Field_message_fullname protoreflect.FullName = "google.protobuf.Field" ) // Field names for google.protobuf.Field. const ( Field_Kind_field_name protoreflect.Name = "kind" Field_Cardinality_field_name protoreflect.Name = "cardinality" Field_Number_field_name protoreflect.Name = "number" Field_Name_field_name protoreflect.Name = "name" Field_TypeUrl_field_name protoreflect.Name = "type_url" Field_OneofIndex_field_name protoreflect.Name = "oneof_index" Field_Packed_field_name protoreflect.Name = "packed" Field_Options_field_name protoreflect.Name = "options" Field_JsonName_field_name protoreflect.Name = "json_name" Field_DefaultValue_field_name protoreflect.Name = "default_value" Field_Kind_field_fullname protoreflect.FullName = "google.protobuf.Field.kind" Field_Cardinality_field_fullname protoreflect.FullName = "google.protobuf.Field.cardinality" Field_Number_field_fullname protoreflect.FullName = "google.protobuf.Field.number" Field_Name_field_fullname protoreflect.FullName = "google.protobuf.Field.name" Field_TypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Field.type_url" Field_OneofIndex_field_fullname protoreflect.FullName = "google.protobuf.Field.oneof_index" Field_Packed_field_fullname protoreflect.FullName = "google.protobuf.Field.packed" Field_Options_field_fullname protoreflect.FullName = "google.protobuf.Field.options" Field_JsonName_field_fullname protoreflect.FullName = "google.protobuf.Field.json_name" Field_DefaultValue_field_fullname protoreflect.FullName = "google.protobuf.Field.default_value" ) // Field numbers for google.protobuf.Field. const ( Field_Kind_field_number protoreflect.FieldNumber = 1 Field_Cardinality_field_number protoreflect.FieldNumber = 2 Field_Number_field_number protoreflect.FieldNumber = 3 Field_Name_field_number protoreflect.FieldNumber = 4 Field_TypeUrl_field_number protoreflect.FieldNumber = 6 Field_OneofIndex_field_number protoreflect.FieldNumber = 7 Field_Packed_field_number protoreflect.FieldNumber = 8 Field_Options_field_number protoreflect.FieldNumber = 9 Field_JsonName_field_number protoreflect.FieldNumber = 10 Field_DefaultValue_field_number protoreflect.FieldNumber = 11 ) // Full and short names for google.protobuf.Field.Kind. const ( Field_Kind_enum_fullname = "google.protobuf.Field.Kind" Field_Kind_enum_name = "Kind" ) // Enum values for google.protobuf.Field.Kind. const ( Field_TYPE_UNKNOWN_enum_value = 0 Field_TYPE_DOUBLE_enum_value = 1 Field_TYPE_FLOAT_enum_value = 2 Field_TYPE_INT64_enum_value = 3 Field_TYPE_UINT64_enum_value = 4 Field_TYPE_INT32_enum_value = 5 Field_TYPE_FIXED64_enum_value = 6 Field_TYPE_FIXED32_enum_value = 7 Field_TYPE_BOOL_enum_value = 8 Field_TYPE_STRING_enum_value = 9 Field_TYPE_GROUP_enum_value = 10 Field_TYPE_MESSAGE_enum_value = 11 Field_TYPE_BYTES_enum_value = 12 Field_TYPE_UINT32_enum_value = 13 Field_TYPE_ENUM_enum_value = 14 Field_TYPE_SFIXED32_enum_value = 15 Field_TYPE_SFIXED64_enum_value = 16 Field_TYPE_SINT32_enum_value = 17 Field_TYPE_SINT64_enum_value = 18 ) // Full and short names for google.protobuf.Field.Cardinality. const ( Field_Cardinality_enum_fullname = "google.protobuf.Field.Cardinality" Field_Cardinality_enum_name = "Cardinality" ) // Enum values for google.protobuf.Field.Cardinality. const ( Field_CARDINALITY_UNKNOWN_enum_value = 0 Field_CARDINALITY_OPTIONAL_enum_value = 1 Field_CARDINALITY_REQUIRED_enum_value = 2 Field_CARDINALITY_REPEATED_enum_value = 3 ) // Names for google.protobuf.Enum. const ( Enum_message_name protoreflect.Name = "Enum" Enum_message_fullname protoreflect.FullName = "google.protobuf.Enum" ) // Field names for google.protobuf.Enum. const ( Enum_Name_field_name protoreflect.Name = "name" Enum_Enumvalue_field_name protoreflect.Name = "enumvalue" Enum_Options_field_name protoreflect.Name = "options" Enum_SourceContext_field_name protoreflect.Name = "source_context" Enum_Syntax_field_name protoreflect.Name = "syntax" Enum_Edition_field_name protoreflect.Name = "edition" Enum_Name_field_fullname protoreflect.FullName = "google.protobuf.Enum.name" Enum_Enumvalue_field_fullname protoreflect.FullName = "google.protobuf.Enum.enumvalue" Enum_Options_field_fullname protoreflect.FullName = "google.protobuf.Enum.options" Enum_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Enum.source_context" Enum_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Enum.syntax" Enum_Edition_field_fullname protoreflect.FullName = "google.protobuf.Enum.edition" ) // Field numbers for google.protobuf.Enum. const ( Enum_Name_field_number protoreflect.FieldNumber = 1 Enum_Enumvalue_field_number protoreflect.FieldNumber = 2 Enum_Options_field_number protoreflect.FieldNumber = 3 Enum_SourceContext_field_number protoreflect.FieldNumber = 4 Enum_Syntax_field_number protoreflect.FieldNumber = 5 Enum_Edition_field_number protoreflect.FieldNumber = 6 ) // Names for google.protobuf.EnumValue. const ( EnumValue_message_name protoreflect.Name = "EnumValue" EnumValue_message_fullname protoreflect.FullName = "google.protobuf.EnumValue" ) // Field names for google.protobuf.EnumValue. const ( EnumValue_Name_field_name protoreflect.Name = "name" EnumValue_Number_field_name protoreflect.Name = "number" EnumValue_Options_field_name protoreflect.Name = "options" EnumValue_Name_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.name" EnumValue_Number_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.number" EnumValue_Options_field_fullname protoreflect.FullName = "google.protobuf.EnumValue.options" ) // Field numbers for google.protobuf.EnumValue. const ( EnumValue_Name_field_number protoreflect.FieldNumber = 1 EnumValue_Number_field_number protoreflect.FieldNumber = 2 EnumValue_Options_field_number protoreflect.FieldNumber = 3 ) // Names for google.protobuf.Option. const ( Option_message_name protoreflect.Name = "Option" Option_message_fullname protoreflect.FullName = "google.protobuf.Option" ) // Field names for google.protobuf.Option. const ( Option_Name_field_name protoreflect.Name = "name" Option_Value_field_name protoreflect.Name = "value" Option_Name_field_fullname protoreflect.FullName = "google.protobuf.Option.name" Option_Value_field_fullname protoreflect.FullName = "google.protobuf.Option.value" ) // Field numbers for google.protobuf.Option. const ( Option_Name_field_number protoreflect.FieldNumber = 1 Option_Value_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/go_features_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/go_features_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_go_features_proto = "google/protobuf/go_features.proto" // Names for pb.GoFeatures. const ( GoFeatures_message_name protoreflect.Name = "GoFeatures" GoFeatures_message_fullname protoreflect.FullName = "pb.GoFeatures" ) // Field names for pb.GoFeatures. const ( GoFeatures_LegacyUnmarshalJsonEnum_field_name protoreflect.Name = "legacy_unmarshal_json_enum" GoFeatures_ApiLevel_field_name protoreflect.Name = "api_level" GoFeatures_StripEnumPrefix_field_name protoreflect.Name = "strip_enum_prefix" GoFeatures_LegacyUnmarshalJsonEnum_field_fullname protoreflect.FullName = "pb.GoFeatures.legacy_unmarshal_json_enum" GoFeatures_ApiLevel_field_fullname protoreflect.FullName = "pb.GoFeatures.api_level" GoFeatures_StripEnumPrefix_field_fullname protoreflect.FullName = "pb.GoFeatures.strip_enum_prefix" ) // Field numbers for pb.GoFeatures. const ( GoFeatures_LegacyUnmarshalJsonEnum_field_number protoreflect.FieldNumber = 1 GoFeatures_ApiLevel_field_number protoreflect.FieldNumber = 2 GoFeatures_StripEnumPrefix_field_number protoreflect.FieldNumber = 3 ) // Full and short names for pb.GoFeatures.APILevel. const ( GoFeatures_APILevel_enum_fullname = "pb.GoFeatures.APILevel" GoFeatures_APILevel_enum_name = "APILevel" ) // Enum values for pb.GoFeatures.APILevel. const ( GoFeatures_API_LEVEL_UNSPECIFIED_enum_value = 0 GoFeatures_API_OPEN_enum_value = 1 GoFeatures_API_HYBRID_enum_value = 2 GoFeatures_API_OPAQUE_enum_value = 3 ) // Full and short names for pb.GoFeatures.StripEnumPrefix. const ( GoFeatures_StripEnumPrefix_enum_fullname = "pb.GoFeatures.StripEnumPrefix" GoFeatures_StripEnumPrefix_enum_name = "StripEnumPrefix" ) // Enum values for pb.GoFeatures.StripEnumPrefix. const ( GoFeatures_STRIP_ENUM_PREFIX_UNSPECIFIED_enum_value = 0 GoFeatures_STRIP_ENUM_PREFIX_KEEP_enum_value = 1 GoFeatures_STRIP_ENUM_PREFIX_GENERATE_BOTH_enum_value = 2 GoFeatures_STRIP_ENUM_PREFIX_STRIP_enum_value = 3 ) // Extension numbers const ( FeatureSet_Go_ext_number protoreflect.FieldNumber = 1002 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/map_entry.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/map_entry.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid import "google.golang.org/protobuf/reflect/protoreflect" // Generic field names and numbers for synthetic map entry messages. const ( MapEntry_Key_field_name protoreflect.Name = "key" MapEntry_Value_field_name protoreflect.Name = "value" MapEntry_Key_field_number protoreflect.FieldNumber = 1 MapEntry_Value_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/name.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/name.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid const ( NoUnkeyedLiteral_goname = "noUnkeyedLiteral" NoUnkeyedLiteralA_goname = "XXX_NoUnkeyedLiteral" BuilderSuffix_goname = "_builder" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/empty_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_empty_proto = "google/protobuf/empty.proto" // Names for google.protobuf.Empty. const ( Empty_message_name protoreflect.Name = "Empty" Empty_message_fullname protoreflect.FullName = "google.protobuf.Empty" )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/wrappers_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_wrappers_proto = "google/protobuf/wrappers.proto" // Names for google.protobuf.DoubleValue. const ( DoubleValue_message_name protoreflect.Name = "DoubleValue" DoubleValue_message_fullname protoreflect.FullName = "google.protobuf.DoubleValue" ) // Field names for google.protobuf.DoubleValue. const ( DoubleValue_Value_field_name protoreflect.Name = "value" DoubleValue_Value_field_fullname protoreflect.FullName = "google.protobuf.DoubleValue.value" ) // Field numbers for google.protobuf.DoubleValue. const ( DoubleValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.FloatValue. const ( FloatValue_message_name protoreflect.Name = "FloatValue" FloatValue_message_fullname protoreflect.FullName = "google.protobuf.FloatValue" ) // Field names for google.protobuf.FloatValue. const ( FloatValue_Value_field_name protoreflect.Name = "value" FloatValue_Value_field_fullname protoreflect.FullName = "google.protobuf.FloatValue.value" ) // Field numbers for google.protobuf.FloatValue. const ( FloatValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Int64Value. const ( Int64Value_message_name protoreflect.Name = "Int64Value" Int64Value_message_fullname protoreflect.FullName = "google.protobuf.Int64Value" ) // Field names for google.protobuf.Int64Value. const ( Int64Value_Value_field_name protoreflect.Name = "value" Int64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int64Value.value" ) // Field numbers for google.protobuf.Int64Value. const ( Int64Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.UInt64Value. const ( UInt64Value_message_name protoreflect.Name = "UInt64Value" UInt64Value_message_fullname protoreflect.FullName = "google.protobuf.UInt64Value" ) // Field names for google.protobuf.UInt64Value. const ( UInt64Value_Value_field_name protoreflect.Name = "value" UInt64Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt64Value.value" ) // Field numbers for google.protobuf.UInt64Value. const ( UInt64Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Int32Value. const ( Int32Value_message_name protoreflect.Name = "Int32Value" Int32Value_message_fullname protoreflect.FullName = "google.protobuf.Int32Value" ) // Field names for google.protobuf.Int32Value. const ( Int32Value_Value_field_name protoreflect.Name = "value" Int32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.Int32Value.value" ) // Field numbers for google.protobuf.Int32Value. const ( Int32Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.UInt32Value. const ( UInt32Value_message_name protoreflect.Name = "UInt32Value" UInt32Value_message_fullname protoreflect.FullName = "google.protobuf.UInt32Value" ) // Field names for google.protobuf.UInt32Value. const ( UInt32Value_Value_field_name protoreflect.Name = "value" UInt32Value_Value_field_fullname protoreflect.FullName = "google.protobuf.UInt32Value.value" ) // Field numbers for google.protobuf.UInt32Value. const ( UInt32Value_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.BoolValue. const ( BoolValue_message_name protoreflect.Name = "BoolValue" BoolValue_message_fullname protoreflect.FullName = "google.protobuf.BoolValue" ) // Field names for google.protobuf.BoolValue. const ( BoolValue_Value_field_name protoreflect.Name = "value" BoolValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BoolValue.value" ) // Field numbers for google.protobuf.BoolValue. const ( BoolValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.StringValue. const ( StringValue_message_name protoreflect.Name = "StringValue" StringValue_message_fullname protoreflect.FullName = "google.protobuf.StringValue" ) // Field names for google.protobuf.StringValue. const ( StringValue_Value_field_name protoreflect.Name = "value" StringValue_Value_field_fullname protoreflect.FullName = "google.protobuf.StringValue.value" ) // Field numbers for google.protobuf.StringValue. const ( StringValue_Value_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.BytesValue. const ( BytesValue_message_name protoreflect.Name = "BytesValue" BytesValue_message_fullname protoreflect.FullName = "google.protobuf.BytesValue" ) // Field names for google.protobuf.BytesValue. const ( BytesValue_Value_field_name protoreflect.Name = "value" BytesValue_Value_field_fullname protoreflect.FullName = "google.protobuf.BytesValue.value" ) // Field numbers for google.protobuf.BytesValue. const ( BytesValue_Value_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/source_context_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_source_context_proto = "google/protobuf/source_context.proto" // Names for google.protobuf.SourceContext. const ( SourceContext_message_name protoreflect.Name = "SourceContext" SourceContext_message_fullname protoreflect.FullName = "google.protobuf.SourceContext" ) // Field names for google.protobuf.SourceContext. const ( SourceContext_FileName_field_name protoreflect.Name = "file_name" SourceContext_FileName_field_fullname protoreflect.FullName = "google.protobuf.SourceContext.file_name" ) // Field numbers for google.protobuf.SourceContext. const ( SourceContext_FileName_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/doc.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package genid contains constants for declarations in descriptor.proto // and the well-known types. package genid import "google.golang.org/protobuf/reflect/protoreflect" const GoogleProtobuf_package protoreflect.FullName = "google.protobuf"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/api_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/api_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_api_proto = "google/protobuf/api.proto" // Names for google.protobuf.Api. const ( Api_message_name protoreflect.Name = "Api" Api_message_fullname protoreflect.FullName = "google.protobuf.Api" ) // Field names for google.protobuf.Api. const ( Api_Name_field_name protoreflect.Name = "name" Api_Methods_field_name protoreflect.Name = "methods" Api_Options_field_name protoreflect.Name = "options" Api_Version_field_name protoreflect.Name = "version" Api_SourceContext_field_name protoreflect.Name = "source_context" Api_Mixins_field_name protoreflect.Name = "mixins" Api_Syntax_field_name protoreflect.Name = "syntax" Api_Name_field_fullname protoreflect.FullName = "google.protobuf.Api.name" Api_Methods_field_fullname protoreflect.FullName = "google.protobuf.Api.methods" Api_Options_field_fullname protoreflect.FullName = "google.protobuf.Api.options" Api_Version_field_fullname protoreflect.FullName = "google.protobuf.Api.version" Api_SourceContext_field_fullname protoreflect.FullName = "google.protobuf.Api.source_context" Api_Mixins_field_fullname protoreflect.FullName = "google.protobuf.Api.mixins" Api_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Api.syntax" ) // Field numbers for google.protobuf.Api. const ( Api_Name_field_number protoreflect.FieldNumber = 1 Api_Methods_field_number protoreflect.FieldNumber = 2 Api_Options_field_number protoreflect.FieldNumber = 3 Api_Version_field_number protoreflect.FieldNumber = 4 Api_SourceContext_field_number protoreflect.FieldNumber = 5 Api_Mixins_field_number protoreflect.FieldNumber = 6 Api_Syntax_field_number protoreflect.FieldNumber = 7 ) // Names for google.protobuf.Method. const ( Method_message_name protoreflect.Name = "Method" Method_message_fullname protoreflect.FullName = "google.protobuf.Method" ) // Field names for google.protobuf.Method. const ( Method_Name_field_name protoreflect.Name = "name" Method_RequestTypeUrl_field_name protoreflect.Name = "request_type_url" Method_RequestStreaming_field_name protoreflect.Name = "request_streaming" Method_ResponseTypeUrl_field_name protoreflect.Name = "response_type_url" Method_ResponseStreaming_field_name protoreflect.Name = "response_streaming" Method_Options_field_name protoreflect.Name = "options" Method_Syntax_field_name protoreflect.Name = "syntax" Method_Name_field_fullname protoreflect.FullName = "google.protobuf.Method.name" Method_RequestTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.request_type_url" Method_RequestStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.request_streaming" Method_ResponseTypeUrl_field_fullname protoreflect.FullName = "google.protobuf.Method.response_type_url" Method_ResponseStreaming_field_fullname protoreflect.FullName = "google.protobuf.Method.response_streaming" Method_Options_field_fullname protoreflect.FullName = "google.protobuf.Method.options" Method_Syntax_field_fullname protoreflect.FullName = "google.protobuf.Method.syntax" ) // Field numbers for google.protobuf.Method. const ( Method_Name_field_number protoreflect.FieldNumber = 1 Method_RequestTypeUrl_field_number protoreflect.FieldNumber = 2 Method_RequestStreaming_field_number protoreflect.FieldNumber = 3 Method_ResponseTypeUrl_field_number protoreflect.FieldNumber = 4 Method_ResponseStreaming_field_number protoreflect.FieldNumber = 5 Method_Options_field_number protoreflect.FieldNumber = 6 Method_Syntax_field_number protoreflect.FieldNumber = 7 ) // Names for google.protobuf.Mixin. const ( Mixin_message_name protoreflect.Name = "Mixin" Mixin_message_fullname protoreflect.FullName = "google.protobuf.Mixin" ) // Field names for google.protobuf.Mixin. const ( Mixin_Name_field_name protoreflect.Name = "name" Mixin_Root_field_name protoreflect.Name = "root" Mixin_Name_field_fullname protoreflect.FullName = "google.protobuf.Mixin.name" Mixin_Root_field_fullname protoreflect.FullName = "google.protobuf.Mixin.root" ) // Field numbers for google.protobuf.Mixin. const ( Mixin_Name_field_number protoreflect.FieldNumber = 1 Mixin_Root_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/wrappers.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/wrappers.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package genid import "google.golang.org/protobuf/reflect/protoreflect" // Generic field name and number for messages in wrappers.proto. const ( WrapperValue_Value_field_name protoreflect.Name = "value" WrapperValue_Value_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/timestamp_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_timestamp_proto = "google/protobuf/timestamp.proto" // Names for google.protobuf.Timestamp. const ( Timestamp_message_name protoreflect.Name = "Timestamp" Timestamp_message_fullname protoreflect.FullName = "google.protobuf.Timestamp" ) // Field names for google.protobuf.Timestamp. const ( Timestamp_Seconds_field_name protoreflect.Name = "seconds" Timestamp_Nanos_field_name protoreflect.Name = "nanos" Timestamp_Seconds_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.seconds" Timestamp_Nanos_field_fullname protoreflect.FullName = "google.protobuf.Timestamp.nanos" ) // Field numbers for google.protobuf.Timestamp. const ( Timestamp_Seconds_field_number protoreflect.FieldNumber = 1 Timestamp_Nanos_field_number protoreflect.FieldNumber = 2 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/genid/struct_gen.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-protos. DO NOT EDIT. package genid import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" ) const File_google_protobuf_struct_proto = "google/protobuf/struct.proto" // Full and short names for google.protobuf.NullValue. const ( NullValue_enum_fullname = "google.protobuf.NullValue" NullValue_enum_name = "NullValue" ) // Enum values for google.protobuf.NullValue. const ( NullValue_NULL_VALUE_enum_value = 0 ) // Names for google.protobuf.Struct. const ( Struct_message_name protoreflect.Name = "Struct" Struct_message_fullname protoreflect.FullName = "google.protobuf.Struct" ) // Field names for google.protobuf.Struct. const ( Struct_Fields_field_name protoreflect.Name = "fields" Struct_Fields_field_fullname protoreflect.FullName = "google.protobuf.Struct.fields" ) // Field numbers for google.protobuf.Struct. const ( Struct_Fields_field_number protoreflect.FieldNumber = 1 ) // Names for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_message_name protoreflect.Name = "FieldsEntry" Struct_FieldsEntry_message_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry" ) // Field names for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_Key_field_name protoreflect.Name = "key" Struct_FieldsEntry_Value_field_name protoreflect.Name = "value" Struct_FieldsEntry_Key_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.key" Struct_FieldsEntry_Value_field_fullname protoreflect.FullName = "google.protobuf.Struct.FieldsEntry.value" ) // Field numbers for google.protobuf.Struct.FieldsEntry. const ( Struct_FieldsEntry_Key_field_number protoreflect.FieldNumber = 1 Struct_FieldsEntry_Value_field_number protoreflect.FieldNumber = 2 ) // Names for google.protobuf.Value. const ( Value_message_name protoreflect.Name = "Value" Value_message_fullname protoreflect.FullName = "google.protobuf.Value" ) // Field names for google.protobuf.Value. const ( Value_NullValue_field_name protoreflect.Name = "null_value" Value_NumberValue_field_name protoreflect.Name = "number_value" Value_StringValue_field_name protoreflect.Name = "string_value" Value_BoolValue_field_name protoreflect.Name = "bool_value" Value_StructValue_field_name protoreflect.Name = "struct_value" Value_ListValue_field_name protoreflect.Name = "list_value" Value_NullValue_field_fullname protoreflect.FullName = "google.protobuf.Value.null_value" Value_NumberValue_field_fullname protoreflect.FullName = "google.protobuf.Value.number_value" Value_StringValue_field_fullname protoreflect.FullName = "google.protobuf.Value.string_value" Value_BoolValue_field_fullname protoreflect.FullName = "google.protobuf.Value.bool_value" Value_StructValue_field_fullname protoreflect.FullName = "google.protobuf.Value.struct_value" Value_ListValue_field_fullname protoreflect.FullName = "google.protobuf.Value.list_value" ) // Field numbers for google.protobuf.Value. const ( Value_NullValue_field_number protoreflect.FieldNumber = 1 Value_NumberValue_field_number protoreflect.FieldNumber = 2 Value_StringValue_field_number protoreflect.FieldNumber = 3 Value_BoolValue_field_number protoreflect.FieldNumber = 4 Value_StructValue_field_number protoreflect.FieldNumber = 5 Value_ListValue_field_number protoreflect.FieldNumber = 6 ) // Oneof names for google.protobuf.Value. const ( Value_Kind_oneof_name protoreflect.Name = "kind" Value_Kind_oneof_fullname protoreflect.FullName = "google.protobuf.Value.kind" ) // Names for google.protobuf.ListValue. const ( ListValue_message_name protoreflect.Name = "ListValue" ListValue_message_fullname protoreflect.FullName = "google.protobuf.ListValue" ) // Field names for google.protobuf.ListValue. const ( ListValue_Values_field_name protoreflect.Name = "values" ListValue_Values_field_fullname protoreflect.FullName = "google.protobuf.ListValue.values" ) // Field numbers for google.protobuf.ListValue. const ( ListValue_Values_field_number protoreflect.FieldNumber = 1 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/editionssupport/editions.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/editionssupport/editions.go
// Copyright 2024 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package editionssupport defines constants for editions that are supported. package editionssupport import "google.golang.org/protobuf/types/descriptorpb" const ( Minimum = descriptorpb.Edition_EDITION_PROTO2 Maximum = descriptorpb.Edition_EDITION_2023 // MaximumKnown is the maximum edition that is known to Go Protobuf, but not // declared as supported. In other words: end users cannot use it, but // testprotos inside Go Protobuf can. MaximumKnown = descriptorpb.Edition_EDITION_2024 )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/descopts/options.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/descopts/options.go
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package descopts contains the nil pointers to concrete descriptor options. // // This package exists as a form of reverse dependency injection so that certain // packages (e.g., internal/filedesc and internal/filetype can avoid a direct // dependency on the descriptor proto package). package descopts import "google.golang.org/protobuf/reflect/protoreflect" // These variables are set by the init function in descriptor.pb.go via logic // in internal/filetype. In other words, so long as the descriptor proto package // is linked in, these variables will be populated. // // Each variable is populated with a nil pointer to the options struct. var ( File protoreflect.ProtoMessage Enum protoreflect.ProtoMessage EnumValue protoreflect.ProtoMessage Message protoreflect.ProtoMessage Field protoreflect.ProtoMessage Oneof protoreflect.ProtoMessage ExtensionRange protoreflect.ProtoMessage Service protoreflect.ProtoMessage Method protoreflect.ProtoMessage )
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/set/ints.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/set/ints.go
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package set provides simple set data structures for uint64s. package set import "math/bits" // int64s represents a set of integers within the range of 0..63. type int64s uint64 func (bs *int64s) Len() int { return bits.OnesCount64(uint64(*bs)) } func (bs *int64s) Has(n uint64) bool { return uint64(*bs)&(uint64(1)<<n) > 0 } func (bs *int64s) Set(n uint64) { *(*uint64)(bs) |= uint64(1) << n } func (bs *int64s) Clear(n uint64) { *(*uint64)(bs) &^= uint64(1) << n } // Ints represents a set of integers within the range of 0..math.MaxUint64. type Ints struct { lo int64s hi map[uint64]struct{} } func (bs *Ints) Len() int { return bs.lo.Len() + len(bs.hi) } func (bs *Ints) Has(n uint64) bool { if n < 64 { return bs.lo.Has(n) } _, ok := bs.hi[n] return ok } func (bs *Ints) Set(n uint64) { if n < 64 { bs.lo.Set(n) return } if bs.hi == nil { bs.hi = make(map[uint64]struct{}) } bs.hi[n] = struct{}{} } func (bs *Ints) Clear(n uint64) { if n < 64 { bs.lo.Clear(n) return } delete(bs.hi, n) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/protoadapt/convert.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/protoadapt/convert.go
// Copyright 2023 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package protoadapt bridges the original and new proto APIs. package protoadapt import ( "google.golang.org/protobuf/proto" "google.golang.org/protobuf/runtime/protoiface" "google.golang.org/protobuf/runtime/protoimpl" ) // MessageV1 is the original [github.com/golang/protobuf/proto.Message] type. type MessageV1 = protoiface.MessageV1 // MessageV2 is the [google.golang.org/protobuf/proto.Message] type used by the // current [google.golang.org/protobuf] module, adding support for reflection. type MessageV2 = proto.Message // MessageV1Of converts a v2 message to a v1 message. // It returns nil if m is nil. func MessageV1Of(m MessageV2) MessageV1 { return protoimpl.X.ProtoMessageV1Of(m) } // MessageV2Of converts a v1 message to a v2 message. // It returns nil if m is nil. func MessageV2Of(m MessageV1) MessageV2 { return protoimpl.X.ProtoMessageV2Of(m) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver_wrapper.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/resolver_wrapper.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "strings" "sync" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/pretty" "google.golang.org/grpc/internal/resolver/delegatingresolver" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" ) // ccResolverWrapper is a wrapper on top of cc for resolvers. // It implements resolver.ClientConn interface. type ccResolverWrapper struct { // The following fields are initialized when the wrapper is created and are // read-only afterwards, and therefore can be accessed without a mutex. cc *ClientConn ignoreServiceConfig bool serializer *grpcsync.CallbackSerializer serializerCancel context.CancelFunc resolver resolver.Resolver // only accessed within the serializer // The following fields are protected by mu. Caller must take cc.mu before // taking mu. mu sync.Mutex curState resolver.State closed bool } // newCCResolverWrapper initializes the ccResolverWrapper. It can only be used // after calling start, which builds the resolver. func newCCResolverWrapper(cc *ClientConn) *ccResolverWrapper { ctx, cancel := context.WithCancel(cc.ctx) return &ccResolverWrapper{ cc: cc, ignoreServiceConfig: cc.dopts.disableServiceConfig, serializer: grpcsync.NewCallbackSerializer(ctx), serializerCancel: cancel, } } // start builds the name resolver using the resolver.Builder in cc and returns // any error encountered. It must always be the first operation performed on // any newly created ccResolverWrapper, except that close may be called instead. func (ccr *ccResolverWrapper) start() error { errCh := make(chan error) ccr.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil { return } opts := resolver.BuildOptions{ DisableServiceConfig: ccr.cc.dopts.disableServiceConfig, DialCreds: ccr.cc.dopts.copts.TransportCredentials, CredsBundle: ccr.cc.dopts.copts.CredsBundle, Dialer: ccr.cc.dopts.copts.Dialer, Authority: ccr.cc.authority, MetricsRecorder: ccr.cc.metricsRecorderList, } var err error // The delegating resolver is used unless: // - A custom dialer is provided via WithContextDialer dialoption or // - Proxy usage is disabled through WithNoProxy dialoption. // In these cases, the resolver is built based on the scheme of target, // using the appropriate resolver builder. if ccr.cc.dopts.copts.Dialer != nil || !ccr.cc.dopts.useProxy { ccr.resolver, err = ccr.cc.resolverBuilder.Build(ccr.cc.parsedTarget, ccr, opts) } else { ccr.resolver, err = delegatingresolver.New(ccr.cc.parsedTarget, ccr, opts, ccr.cc.resolverBuilder, ccr.cc.dopts.enableLocalDNSResolution) } errCh <- err }) return <-errCh } func (ccr *ccResolverWrapper) resolveNow(o resolver.ResolveNowOptions) { ccr.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || ccr.resolver == nil { return } ccr.resolver.ResolveNow(o) }) } // close initiates async shutdown of the wrapper. To determine the wrapper has // finished shutting down, the channel should block on ccr.serializer.Done() // without cc.mu held. func (ccr *ccResolverWrapper) close() { channelz.Info(logger, ccr.cc.channelz, "Closing the name resolver") ccr.mu.Lock() ccr.closed = true ccr.mu.Unlock() ccr.serializer.TrySchedule(func(context.Context) { if ccr.resolver == nil { return } ccr.resolver.Close() ccr.resolver = nil }) ccr.serializerCancel() } // UpdateState is called by resolver implementations to report new state to gRPC // which includes addresses and service config. func (ccr *ccResolverWrapper) UpdateState(s resolver.State) error { ccr.cc.mu.Lock() ccr.mu.Lock() if ccr.closed { ccr.mu.Unlock() ccr.cc.mu.Unlock() return nil } if s.Endpoints == nil { s.Endpoints = make([]resolver.Endpoint, 0, len(s.Addresses)) for _, a := range s.Addresses { ep := resolver.Endpoint{Addresses: []resolver.Address{a}, Attributes: a.BalancerAttributes} ep.Addresses[0].BalancerAttributes = nil s.Endpoints = append(s.Endpoints, ep) } } ccr.addChannelzTraceEvent(s) ccr.curState = s ccr.mu.Unlock() return ccr.cc.updateResolverStateAndUnlock(s, nil) } // ReportError is called by resolver implementations to report errors // encountered during name resolution to gRPC. func (ccr *ccResolverWrapper) ReportError(err error) { ccr.cc.mu.Lock() ccr.mu.Lock() if ccr.closed { ccr.mu.Unlock() ccr.cc.mu.Unlock() return } ccr.mu.Unlock() channelz.Warningf(logger, ccr.cc.channelz, "ccResolverWrapper: reporting error to cc: %v", err) ccr.cc.updateResolverStateAndUnlock(resolver.State{}, err) } // NewAddress is called by the resolver implementation to send addresses to // gRPC. func (ccr *ccResolverWrapper) NewAddress(addrs []resolver.Address) { ccr.cc.mu.Lock() ccr.mu.Lock() if ccr.closed { ccr.mu.Unlock() ccr.cc.mu.Unlock() return } s := resolver.State{Addresses: addrs, ServiceConfig: ccr.curState.ServiceConfig} ccr.addChannelzTraceEvent(s) ccr.curState = s ccr.mu.Unlock() ccr.cc.updateResolverStateAndUnlock(s, nil) } // ParseServiceConfig is called by resolver implementations to parse a JSON // representation of the service config. func (ccr *ccResolverWrapper) ParseServiceConfig(scJSON string) *serviceconfig.ParseResult { return parseServiceConfig(scJSON, ccr.cc.dopts.maxCallAttempts) } // addChannelzTraceEvent adds a channelz trace event containing the new // state received from resolver implementations. func (ccr *ccResolverWrapper) addChannelzTraceEvent(s resolver.State) { if !logger.V(0) && !channelz.IsOn() { return } var updates []string var oldSC, newSC *ServiceConfig var oldOK, newOK bool if ccr.curState.ServiceConfig != nil { oldSC, oldOK = ccr.curState.ServiceConfig.Config.(*ServiceConfig) } if s.ServiceConfig != nil { newSC, newOK = s.ServiceConfig.Config.(*ServiceConfig) } if oldOK != newOK || (oldOK && newOK && oldSC.rawJSONString != newSC.rawJSONString) { updates = append(updates, "service config updated") } if len(ccr.curState.Addresses) > 0 && len(s.Addresses) == 0 { updates = append(updates, "resolver returned an empty address list") } else if len(ccr.curState.Addresses) == 0 && len(s.Addresses) > 0 { updates = append(updates, "resolver returned new addresses") } channelz.Infof(logger, ccr.cc.channelz, "Resolver state updated: %s (%v)", pretty.ToJSON(s), strings.Join(updates, "; ")) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer_wrapper.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/balancer_wrapper.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "fmt" "sync" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/balancer/gracefulswitch" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/resolver" "google.golang.org/grpc/status" ) var ( setConnectedAddress = internal.SetConnectedAddress.(func(*balancer.SubConnState, resolver.Address)) // noOpRegisterHealthListenerFn is used when client side health checking is // disabled. It sends a single READY update on the registered listener. noOpRegisterHealthListenerFn = func(_ context.Context, listener func(balancer.SubConnState)) func() { listener(balancer.SubConnState{ConnectivityState: connectivity.Ready}) return func() {} } ) // ccBalancerWrapper sits between the ClientConn and the Balancer. // // ccBalancerWrapper implements methods corresponding to the ones on the // balancer.Balancer interface. The ClientConn is free to call these methods // concurrently and the ccBalancerWrapper ensures that calls from the ClientConn // to the Balancer happen in order by performing them in the serializer, without // any mutexes held. // // ccBalancerWrapper also implements the balancer.ClientConn interface and is // passed to the Balancer implementations. It invokes unexported methods on the // ClientConn to handle these calls from the Balancer. // // It uses the gracefulswitch.Balancer internally to ensure that balancer // switches happen in a graceful manner. type ccBalancerWrapper struct { internal.EnforceClientConnEmbedding // The following fields are initialized when the wrapper is created and are // read-only afterwards, and therefore can be accessed without a mutex. cc *ClientConn opts balancer.BuildOptions serializer *grpcsync.CallbackSerializer serializerCancel context.CancelFunc // The following fields are only accessed within the serializer or during // initialization. curBalancerName string balancer *gracefulswitch.Balancer // The following field is protected by mu. Caller must take cc.mu before // taking mu. mu sync.Mutex closed bool } // newCCBalancerWrapper creates a new balancer wrapper in idle state. The // underlying balancer is not created until the updateClientConnState() method // is invoked. func newCCBalancerWrapper(cc *ClientConn) *ccBalancerWrapper { ctx, cancel := context.WithCancel(cc.ctx) ccb := &ccBalancerWrapper{ cc: cc, opts: balancer.BuildOptions{ DialCreds: cc.dopts.copts.TransportCredentials, CredsBundle: cc.dopts.copts.CredsBundle, Dialer: cc.dopts.copts.Dialer, Authority: cc.authority, CustomUserAgent: cc.dopts.copts.UserAgent, ChannelzParent: cc.channelz, Target: cc.parsedTarget, }, serializer: grpcsync.NewCallbackSerializer(ctx), serializerCancel: cancel, } ccb.balancer = gracefulswitch.NewBalancer(ccb, ccb.opts) return ccb } func (ccb *ccBalancerWrapper) MetricsRecorder() stats.MetricsRecorder { return ccb.cc.metricsRecorderList } // updateClientConnState is invoked by grpc to push a ClientConnState update to // the underlying balancer. This is always executed from the serializer, so // it is safe to call into the balancer here. func (ccb *ccBalancerWrapper) updateClientConnState(ccs *balancer.ClientConnState) error { errCh := make(chan error) uccs := func(ctx context.Context) { defer close(errCh) if ctx.Err() != nil || ccb.balancer == nil { return } name := gracefulswitch.ChildName(ccs.BalancerConfig) if ccb.curBalancerName != name { ccb.curBalancerName = name channelz.Infof(logger, ccb.cc.channelz, "Channel switches to new LB policy %q", name) } err := ccb.balancer.UpdateClientConnState(*ccs) if logger.V(2) && err != nil { logger.Infof("error from balancer.UpdateClientConnState: %v", err) } errCh <- err } onFailure := func() { close(errCh) } // UpdateClientConnState can race with Close, and when the latter wins, the // serializer is closed, and the attempt to schedule the callback will fail. // It is acceptable to ignore this failure. But since we want to handle the // state update in a blocking fashion (when we successfully schedule the // callback), we have to use the ScheduleOr method and not the MaybeSchedule // method on the serializer. ccb.serializer.ScheduleOr(uccs, onFailure) return <-errCh } // resolverError is invoked by grpc to push a resolver error to the underlying // balancer. The call to the balancer is executed from the serializer. func (ccb *ccBalancerWrapper) resolverError(err error) { ccb.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || ccb.balancer == nil { return } ccb.balancer.ResolverError(err) }) } // close initiates async shutdown of the wrapper. cc.mu must be held when // calling this function. To determine the wrapper has finished shutting down, // the channel should block on ccb.serializer.Done() without cc.mu held. func (ccb *ccBalancerWrapper) close() { ccb.mu.Lock() ccb.closed = true ccb.mu.Unlock() channelz.Info(logger, ccb.cc.channelz, "ccBalancerWrapper: closing") ccb.serializer.TrySchedule(func(context.Context) { if ccb.balancer == nil { return } ccb.balancer.Close() ccb.balancer = nil }) ccb.serializerCancel() } // exitIdle invokes the balancer's exitIdle method in the serializer. func (ccb *ccBalancerWrapper) exitIdle() { ccb.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || ccb.balancer == nil { return } ccb.balancer.ExitIdle() }) } func (ccb *ccBalancerWrapper) NewSubConn(addrs []resolver.Address, opts balancer.NewSubConnOptions) (balancer.SubConn, error) { ccb.cc.mu.Lock() defer ccb.cc.mu.Unlock() ccb.mu.Lock() if ccb.closed { ccb.mu.Unlock() return nil, fmt.Errorf("balancer is being closed; no new SubConns allowed") } ccb.mu.Unlock() if len(addrs) == 0 { return nil, fmt.Errorf("grpc: cannot create SubConn with empty address list") } ac, err := ccb.cc.newAddrConnLocked(addrs, opts) if err != nil { channelz.Warningf(logger, ccb.cc.channelz, "acBalancerWrapper: NewSubConn: failed to newAddrConn: %v", err) return nil, err } acbw := &acBalancerWrapper{ ccb: ccb, ac: ac, producers: make(map[balancer.ProducerBuilder]*refCountedProducer), stateListener: opts.StateListener, healthData: newHealthData(connectivity.Idle), } ac.acbw = acbw return acbw, nil } func (ccb *ccBalancerWrapper) RemoveSubConn(balancer.SubConn) { // The graceful switch balancer will never call this. logger.Errorf("ccb RemoveSubConn(%v) called unexpectedly, sc") } func (ccb *ccBalancerWrapper) UpdateAddresses(sc balancer.SubConn, addrs []resolver.Address) { acbw, ok := sc.(*acBalancerWrapper) if !ok { return } acbw.UpdateAddresses(addrs) } func (ccb *ccBalancerWrapper) UpdateState(s balancer.State) { ccb.cc.mu.Lock() defer ccb.cc.mu.Unlock() if ccb.cc.conns == nil { // The CC has been closed; ignore this update. return } ccb.mu.Lock() if ccb.closed { ccb.mu.Unlock() return } ccb.mu.Unlock() // Update picker before updating state. Even though the ordering here does // not matter, it can lead to multiple calls of Pick in the common start-up // case where we wait for ready and then perform an RPC. If the picker is // updated later, we could call the "connecting" picker when the state is // updated, and then call the "ready" picker after the picker gets updated. // Note that there is no need to check if the balancer wrapper was closed, // as we know the graceful switch LB policy will not call cc if it has been // closed. ccb.cc.pickerWrapper.updatePicker(s.Picker) ccb.cc.csMgr.updateState(s.ConnectivityState) } func (ccb *ccBalancerWrapper) ResolveNow(o resolver.ResolveNowOptions) { ccb.cc.mu.RLock() defer ccb.cc.mu.RUnlock() ccb.mu.Lock() if ccb.closed { ccb.mu.Unlock() return } ccb.mu.Unlock() ccb.cc.resolveNowLocked(o) } func (ccb *ccBalancerWrapper) Target() string { return ccb.cc.target } // acBalancerWrapper is a wrapper on top of ac for balancers. // It implements balancer.SubConn interface. type acBalancerWrapper struct { internal.EnforceSubConnEmbedding ac *addrConn // read-only ccb *ccBalancerWrapper // read-only stateListener func(balancer.SubConnState) producersMu sync.Mutex producers map[balancer.ProducerBuilder]*refCountedProducer // Access to healthData is protected by healthMu. healthMu sync.Mutex // healthData is stored as a pointer to detect when the health listener is // dropped or updated. This is required as closures can't be compared for // equality. healthData *healthData } // healthData holds data related to health state reporting. type healthData struct { // connectivityState stores the most recent connectivity state delivered // to the LB policy. This is stored to avoid sending updates when the // SubConn has already exited connectivity state READY. connectivityState connectivity.State // closeHealthProducer stores function to close the ref counted health // producer. The health producer is automatically closed when the SubConn // state changes. closeHealthProducer func() } func newHealthData(s connectivity.State) *healthData { return &healthData{ connectivityState: s, closeHealthProducer: func() {}, } } // updateState is invoked by grpc to push a subConn state update to the // underlying balancer. func (acbw *acBalancerWrapper) updateState(s connectivity.State, curAddr resolver.Address, err error) { acbw.ccb.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || acbw.ccb.balancer == nil { return } // Invalidate all producers on any state change. acbw.closeProducers() // Even though it is optional for balancers, gracefulswitch ensures // opts.StateListener is set, so this cannot ever be nil. // TODO: delete this comment when UpdateSubConnState is removed. scs := balancer.SubConnState{ConnectivityState: s, ConnectionError: err} if s == connectivity.Ready { setConnectedAddress(&scs, curAddr) } // Invalidate the health listener by updating the healthData. acbw.healthMu.Lock() // A race may occur if a health listener is registered soon after the // connectivity state is set but before the stateListener is called. // Two cases may arise: // 1. The new state is not READY: RegisterHealthListener has checks to // ensure no updates are sent when the connectivity state is not // READY. // 2. The new state is READY: This means that the old state wasn't Ready. // The RegisterHealthListener API mentions that a health listener // must not be registered when a SubConn is not ready to avoid such // races. When this happens, the LB policy would get health updates // on the old listener. When the LB policy registers a new listener // on receiving the connectivity update, the health updates will be // sent to the new health listener. acbw.healthData = newHealthData(scs.ConnectivityState) acbw.healthMu.Unlock() acbw.stateListener(scs) }) } func (acbw *acBalancerWrapper) String() string { return fmt.Sprintf("SubConn(id:%d)", acbw.ac.channelz.ID) } func (acbw *acBalancerWrapper) UpdateAddresses(addrs []resolver.Address) { acbw.ac.updateAddrs(addrs) } func (acbw *acBalancerWrapper) Connect() { go acbw.ac.connect() } func (acbw *acBalancerWrapper) Shutdown() { acbw.closeProducers() acbw.ccb.cc.removeAddrConn(acbw.ac, errConnDrain) } // NewStream begins a streaming RPC on the addrConn. If the addrConn is not // ready, blocks until it is or ctx expires. Returns an error when the context // expires or the addrConn is shut down. func (acbw *acBalancerWrapper) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { transport := acbw.ac.getReadyTransport() if transport == nil { return nil, status.Errorf(codes.Unavailable, "SubConn state is not Ready") } return newNonRetryClientStream(ctx, desc, method, transport, acbw.ac, opts...) } // Invoke performs a unary RPC. If the addrConn is not ready, returns // errSubConnNotReady. func (acbw *acBalancerWrapper) Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error { cs, err := acbw.NewStream(ctx, unaryStreamDesc, method, opts...) if err != nil { return err } if err := cs.SendMsg(args); err != nil { return err } return cs.RecvMsg(reply) } type refCountedProducer struct { producer balancer.Producer refs int // number of current refs to the producer close func() // underlying producer's close function } func (acbw *acBalancerWrapper) GetOrBuildProducer(pb balancer.ProducerBuilder) (balancer.Producer, func()) { acbw.producersMu.Lock() defer acbw.producersMu.Unlock() // Look up existing producer from this builder. pData := acbw.producers[pb] if pData == nil { // Not found; create a new one and add it to the producers map. p, closeFn := pb.Build(acbw) pData = &refCountedProducer{producer: p, close: closeFn} acbw.producers[pb] = pData } // Account for this new reference. pData.refs++ // Return a cleanup function wrapped in a OnceFunc to remove this reference // and delete the refCountedProducer from the map if the total reference // count goes to zero. unref := func() { acbw.producersMu.Lock() // If closeProducers has already closed this producer instance, refs is // set to 0, so the check after decrementing will never pass, and the // producer will not be double-closed. pData.refs-- if pData.refs == 0 { defer pData.close() // Run outside the acbw mutex delete(acbw.producers, pb) } acbw.producersMu.Unlock() } return pData.producer, sync.OnceFunc(unref) } func (acbw *acBalancerWrapper) closeProducers() { acbw.producersMu.Lock() defer acbw.producersMu.Unlock() for pb, pData := range acbw.producers { pData.refs = 0 pData.close() delete(acbw.producers, pb) } } // healthProducerRegisterFn is a type alias for the health producer's function // for registering listeners. type healthProducerRegisterFn = func(context.Context, balancer.SubConn, string, func(balancer.SubConnState)) func() // healthListenerRegFn returns a function to register a listener for health // updates. If client side health checks are disabled, the registered listener // will get a single READY (raw connectivity state) update. // // Client side health checking is enabled when all the following // conditions are satisfied: // 1. Health checking is not disabled using the dial option. // 2. The health package is imported. // 3. The health check config is present in the service config. func (acbw *acBalancerWrapper) healthListenerRegFn() func(context.Context, func(balancer.SubConnState)) func() { if acbw.ccb.cc.dopts.disableHealthCheck { return noOpRegisterHealthListenerFn } regHealthLisFn := internal.RegisterClientHealthCheckListener if regHealthLisFn == nil { // The health package is not imported. return noOpRegisterHealthListenerFn } cfg := acbw.ac.cc.healthCheckConfig() if cfg == nil { return noOpRegisterHealthListenerFn } return func(ctx context.Context, listener func(balancer.SubConnState)) func() { return regHealthLisFn.(healthProducerRegisterFn)(ctx, acbw, cfg.ServiceName, listener) } } // RegisterHealthListener accepts a health listener from the LB policy. It sends // updates to the health listener as long as the SubConn's connectivity state // doesn't change and a new health listener is not registered. To invalidate // the currently registered health listener, acbw updates the healthData. If a // nil listener is registered, the active health listener is dropped. func (acbw *acBalancerWrapper) RegisterHealthListener(listener func(balancer.SubConnState)) { acbw.healthMu.Lock() defer acbw.healthMu.Unlock() acbw.healthData.closeHealthProducer() // listeners should not be registered when the connectivity state // isn't Ready. This may happen when the balancer registers a listener // after the connectivityState is updated, but before it is notified // of the update. if acbw.healthData.connectivityState != connectivity.Ready { return } // Replace the health data to stop sending updates to any previously // registered health listeners. hd := newHealthData(connectivity.Ready) acbw.healthData = hd if listener == nil { return } registerFn := acbw.healthListenerRegFn() acbw.ccb.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || acbw.ccb.balancer == nil { return } // Don't send updates if a new listener is registered. acbw.healthMu.Lock() defer acbw.healthMu.Unlock() if acbw.healthData != hd { return } // Serialize the health updates from the health producer with // other calls into the LB policy. listenerWrapper := func(scs balancer.SubConnState) { acbw.ccb.serializer.TrySchedule(func(ctx context.Context) { if ctx.Err() != nil || acbw.ccb.balancer == nil { return } acbw.healthMu.Lock() defer acbw.healthMu.Unlock() if acbw.healthData != hd { return } listener(scs) }) } hd.closeHealthProducer = registerFn(ctx, listenerWrapper) }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/preloader.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/preloader.go
/* * * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "google.golang.org/grpc/codes" "google.golang.org/grpc/mem" "google.golang.org/grpc/status" ) // PreparedMsg is responsible for creating a Marshalled and Compressed object. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type PreparedMsg struct { // Struct for preparing msg before sending them encodedData mem.BufferSlice hdr []byte payload mem.BufferSlice pf payloadFormat } // Encode marshalls and compresses the message using the codec and compressor for the stream. func (p *PreparedMsg) Encode(s Stream, msg any) error { ctx := s.Context() rpcInfo, ok := rpcInfoFromContext(ctx) if !ok { return status.Errorf(codes.Internal, "grpc: unable to get rpcInfo") } // check if the context has the relevant information to prepareMsg if rpcInfo.preloaderInfo == nil { return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo is nil") } if rpcInfo.preloaderInfo.codec == nil { return status.Errorf(codes.Internal, "grpc: rpcInfo.preloaderInfo.codec is nil") } // prepare the msg data, err := encode(rpcInfo.preloaderInfo.codec, msg) if err != nil { return err } materializedData := data.Materialize() data.Free() p.encodedData = mem.BufferSlice{mem.SliceBuffer(materializedData)} // TODO: it should be possible to grab the bufferPool from the underlying // stream implementation with a type cast to its actual type (such as // addrConnStream) and accessing the buffer pool directly. var compData mem.BufferSlice compData, p.pf, err = compress(p.encodedData, rpcInfo.preloaderInfo.cp, rpcInfo.preloaderInfo.comp, mem.DefaultBufferPool()) if err != nil { return err } if p.pf.isCompressed() { materializedCompData := compData.Materialize() compData.Free() compData = mem.BufferSlice{mem.SliceBuffer(materializedCompData)} } p.hdr, p.payload = msgHeader(p.encodedData, compData, p.pf) return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/service_config.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/service_config.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "encoding/json" "errors" "fmt" "reflect" "time" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/pickfirst" "google.golang.org/grpc/codes" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/balancer/gracefulswitch" internalserviceconfig "google.golang.org/grpc/internal/serviceconfig" "google.golang.org/grpc/serviceconfig" ) const maxInt = int(^uint(0) >> 1) // MethodConfig defines the configuration recommended by the service providers for a // particular method. // // Deprecated: Users should not use this struct. Service config should be received // through name resolver, as specified here // https://github.com/grpc/grpc/blob/master/doc/service_config.md type MethodConfig = internalserviceconfig.MethodConfig // ServiceConfig is provided by the service provider and contains parameters for how // clients that connect to the service should behave. // // Deprecated: Users should not use this struct. Service config should be received // through name resolver, as specified here // https://github.com/grpc/grpc/blob/master/doc/service_config.md type ServiceConfig struct { serviceconfig.Config // lbConfig is the service config's load balancing configuration. If // lbConfig and LB are both present, lbConfig will be used. lbConfig serviceconfig.LoadBalancingConfig // Methods contains a map for the methods in this service. If there is an // exact match for a method (i.e. /service/method) in the map, use the // corresponding MethodConfig. If there's no exact match, look for the // default config for the service (/service/) and use the corresponding // MethodConfig if it exists. Otherwise, the method has no MethodConfig to // use. Methods map[string]MethodConfig // If a retryThrottlingPolicy is provided, gRPC will automatically throttle // retry attempts and hedged RPCs when the client’s ratio of failures to // successes exceeds a threshold. // // For each server name, the gRPC client will maintain a token_count which is // initially set to maxTokens, and can take values between 0 and maxTokens. // // Every outgoing RPC (regardless of service or method invoked) will change // token_count as follows: // // - Every failed RPC will decrement the token_count by 1. // - Every successful RPC will increment the token_count by tokenRatio. // // If token_count is less than or equal to maxTokens / 2, then RPCs will not // be retried and hedged RPCs will not be sent. retryThrottling *retryThrottlingPolicy // healthCheckConfig must be set as one of the requirement to enable LB channel // health check. healthCheckConfig *healthCheckConfig // rawJSONString stores service config json string that get parsed into // this service config struct. rawJSONString string } // healthCheckConfig defines the go-native version of the LB channel health check config. type healthCheckConfig struct { // serviceName is the service name to use in the health-checking request. ServiceName string } type jsonRetryPolicy struct { MaxAttempts int InitialBackoff internalserviceconfig.Duration MaxBackoff internalserviceconfig.Duration BackoffMultiplier float64 RetryableStatusCodes []codes.Code } // retryThrottlingPolicy defines the go-native version of the retry throttling // policy defined by the service config here: // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#integration-with-service-config type retryThrottlingPolicy struct { // The number of tokens starts at maxTokens. The token_count will always be // between 0 and maxTokens. // // This field is required and must be greater than zero. MaxTokens float64 // The amount of tokens to add on each successful RPC. Typically this will // be some number between 0 and 1, e.g., 0.1. // // This field is required and must be greater than zero. Up to 3 decimal // places are supported. TokenRatio float64 } type jsonName struct { Service string Method string } var ( errDuplicatedName = errors.New("duplicated name") errEmptyServiceNonEmptyMethod = errors.New("cannot combine empty 'service' and non-empty 'method'") ) func (j jsonName) generatePath() (string, error) { if j.Service == "" { if j.Method != "" { return "", errEmptyServiceNonEmptyMethod } return "", nil } res := "/" + j.Service + "/" if j.Method != "" { res += j.Method } return res, nil } // TODO(lyuxuan): delete this struct after cleaning up old service config implementation. type jsonMC struct { Name *[]jsonName WaitForReady *bool Timeout *internalserviceconfig.Duration MaxRequestMessageBytes *int64 MaxResponseMessageBytes *int64 RetryPolicy *jsonRetryPolicy } // TODO(lyuxuan): delete this struct after cleaning up old service config implementation. type jsonSC struct { LoadBalancingPolicy *string LoadBalancingConfig *json.RawMessage MethodConfig *[]jsonMC RetryThrottling *retryThrottlingPolicy HealthCheckConfig *healthCheckConfig } func init() { internal.ParseServiceConfig = func(js string) *serviceconfig.ParseResult { return parseServiceConfig(js, defaultMaxCallAttempts) } } func parseServiceConfig(js string, maxAttempts int) *serviceconfig.ParseResult { if len(js) == 0 { return &serviceconfig.ParseResult{Err: fmt.Errorf("no JSON service config provided")} } var rsc jsonSC err := json.Unmarshal([]byte(js), &rsc) if err != nil { logger.Warningf("grpc: unmarshalling service config %s: %v", js, err) return &serviceconfig.ParseResult{Err: err} } sc := ServiceConfig{ Methods: make(map[string]MethodConfig), retryThrottling: rsc.RetryThrottling, healthCheckConfig: rsc.HealthCheckConfig, rawJSONString: js, } c := rsc.LoadBalancingConfig if c == nil { name := pickfirst.Name if rsc.LoadBalancingPolicy != nil { name = *rsc.LoadBalancingPolicy } if balancer.Get(name) == nil { name = pickfirst.Name } cfg := []map[string]any{{name: struct{}{}}} strCfg, err := json.Marshal(cfg) if err != nil { return &serviceconfig.ParseResult{Err: fmt.Errorf("unexpected error marshaling simple LB config: %w", err)} } r := json.RawMessage(strCfg) c = &r } cfg, err := gracefulswitch.ParseConfig(*c) if err != nil { return &serviceconfig.ParseResult{Err: err} } sc.lbConfig = cfg if rsc.MethodConfig == nil { return &serviceconfig.ParseResult{Config: &sc} } paths := map[string]struct{}{} for _, m := range *rsc.MethodConfig { if m.Name == nil { continue } mc := MethodConfig{ WaitForReady: m.WaitForReady, Timeout: (*time.Duration)(m.Timeout), } if mc.RetryPolicy, err = convertRetryPolicy(m.RetryPolicy, maxAttempts); err != nil { logger.Warningf("grpc: unmarshalling service config %s: %v", js, err) return &serviceconfig.ParseResult{Err: err} } if m.MaxRequestMessageBytes != nil { if *m.MaxRequestMessageBytes > int64(maxInt) { mc.MaxReqSize = newInt(maxInt) } else { mc.MaxReqSize = newInt(int(*m.MaxRequestMessageBytes)) } } if m.MaxResponseMessageBytes != nil { if *m.MaxResponseMessageBytes > int64(maxInt) { mc.MaxRespSize = newInt(maxInt) } else { mc.MaxRespSize = newInt(int(*m.MaxResponseMessageBytes)) } } for i, n := range *m.Name { path, err := n.generatePath() if err != nil { logger.Warningf("grpc: error unmarshalling service config %s due to methodConfig[%d]: %v", js, i, err) return &serviceconfig.ParseResult{Err: err} } if _, ok := paths[path]; ok { err = errDuplicatedName logger.Warningf("grpc: error unmarshalling service config %s due to methodConfig[%d]: %v", js, i, err) return &serviceconfig.ParseResult{Err: err} } paths[path] = struct{}{} sc.Methods[path] = mc } } if sc.retryThrottling != nil { if mt := sc.retryThrottling.MaxTokens; mt <= 0 || mt > 1000 { return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: maxTokens (%v) out of range (0, 1000]", mt)} } if tr := sc.retryThrottling.TokenRatio; tr <= 0 { return &serviceconfig.ParseResult{Err: fmt.Errorf("invalid retry throttling config: tokenRatio (%v) may not be negative", tr)} } } return &serviceconfig.ParseResult{Config: &sc} } func isValidRetryPolicy(jrp *jsonRetryPolicy) bool { return jrp.MaxAttempts > 1 && jrp.InitialBackoff > 0 && jrp.MaxBackoff > 0 && jrp.BackoffMultiplier > 0 && len(jrp.RetryableStatusCodes) > 0 } func convertRetryPolicy(jrp *jsonRetryPolicy, maxAttempts int) (p *internalserviceconfig.RetryPolicy, err error) { if jrp == nil { return nil, nil } if !isValidRetryPolicy(jrp) { return nil, fmt.Errorf("invalid retry policy (%+v): ", jrp) } if jrp.MaxAttempts < maxAttempts { maxAttempts = jrp.MaxAttempts } rp := &internalserviceconfig.RetryPolicy{ MaxAttempts: maxAttempts, InitialBackoff: time.Duration(jrp.InitialBackoff), MaxBackoff: time.Duration(jrp.MaxBackoff), BackoffMultiplier: jrp.BackoffMultiplier, RetryableStatusCodes: make(map[codes.Code]bool), } for _, code := range jrp.RetryableStatusCodes { rp.RetryableStatusCodes[code] = true } return rp, nil } func minPointers(a, b *int) *int { if *a < *b { return a } return b } func getMaxSize(mcMax, doptMax *int, defaultVal int) *int { if mcMax == nil && doptMax == nil { return &defaultVal } if mcMax != nil && doptMax != nil { return minPointers(mcMax, doptMax) } if mcMax != nil { return mcMax } return doptMax } func newInt(b int) *int { return &b } func init() { internal.EqualServiceConfigForTesting = equalServiceConfig } // equalServiceConfig compares two configs. The rawJSONString field is ignored, // because they may diff in white spaces. // // If any of them is NOT *ServiceConfig, return false. func equalServiceConfig(a, b serviceconfig.Config) bool { if a == nil && b == nil { return true } aa, ok := a.(*ServiceConfig) if !ok { return false } bb, ok := b.(*ServiceConfig) if !ok { return false } aaRaw := aa.rawJSONString aa.rawJSONString = "" bbRaw := bb.rawJSONString bb.rawJSONString = "" defer func() { aa.rawJSONString = aaRaw bb.rawJSONString = bbRaw }() // Using reflect.DeepEqual instead of cmp.Equal because many balancer // configs are unexported, and cmp.Equal cannot compare unexported fields // from unexported structs. return reflect.DeepEqual(aa, bb) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/clientconn.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/clientconn.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "errors" "fmt" "math" "net/url" "slices" "strings" "sync" "sync/atomic" "time" "google.golang.org/grpc/balancer" "google.golang.org/grpc/balancer/base" "google.golang.org/grpc/balancer/pickfirst" "google.golang.org/grpc/codes" "google.golang.org/grpc/connectivity" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/idle" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/stats" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/resolver" "google.golang.org/grpc/serviceconfig" "google.golang.org/grpc/status" _ "google.golang.org/grpc/balancer/roundrobin" // To register roundrobin. _ "google.golang.org/grpc/internal/resolver/passthrough" // To register passthrough resolver. _ "google.golang.org/grpc/internal/resolver/unix" // To register unix resolver. _ "google.golang.org/grpc/resolver/dns" // To register dns resolver. ) const ( // minimum time to give a connection to complete minConnectTimeout = 20 * time.Second ) var ( // ErrClientConnClosing indicates that the operation is illegal because // the ClientConn is closing. // // Deprecated: this error should not be relied upon by users; use the status // code of Canceled instead. ErrClientConnClosing = status.Error(codes.Canceled, "grpc: the client connection is closing") // errConnDrain indicates that the connection starts to be drained and does not accept any new RPCs. errConnDrain = errors.New("grpc: the connection is drained") // errConnClosing indicates that the connection is closing. errConnClosing = errors.New("grpc: the connection is closing") // errConnIdling indicates the connection is being closed as the channel // is moving to an idle mode due to inactivity. errConnIdling = errors.New("grpc: the connection is closing due to channel idleness") // invalidDefaultServiceConfigErrPrefix is used to prefix the json parsing error for the default // service config. invalidDefaultServiceConfigErrPrefix = "grpc: the provided default service config is invalid" // PickFirstBalancerName is the name of the pick_first balancer. PickFirstBalancerName = pickfirst.Name ) // The following errors are returned from Dial and DialContext var ( // errNoTransportSecurity indicates that there is no transport security // being set for ClientConn. Users should either set one or explicitly // call WithInsecure DialOption to disable security. errNoTransportSecurity = errors.New("grpc: no transport security set (use grpc.WithTransportCredentials(insecure.NewCredentials()) explicitly or set credentials)") // errTransportCredsAndBundle indicates that creds bundle is used together // with other individual Transport Credentials. errTransportCredsAndBundle = errors.New("grpc: credentials.Bundle may not be used with individual TransportCredentials") // errNoTransportCredsInBundle indicated that the configured creds bundle // returned a transport credentials which was nil. errNoTransportCredsInBundle = errors.New("grpc: credentials.Bundle must return non-nil transport credentials") // errTransportCredentialsMissing indicates that users want to transmit // security information (e.g., OAuth2 token) which requires secure // connection on an insecure connection. errTransportCredentialsMissing = errors.New("grpc: the credentials require transport level security (use grpc.WithTransportCredentials() to set)") ) const ( defaultClientMaxReceiveMessageSize = 1024 * 1024 * 4 defaultClientMaxSendMessageSize = math.MaxInt32 // http2IOBufSize specifies the buffer size for sending frames. defaultWriteBufSize = 32 * 1024 defaultReadBufSize = 32 * 1024 ) type defaultConfigSelector struct { sc *ServiceConfig } func (dcs *defaultConfigSelector) SelectConfig(rpcInfo iresolver.RPCInfo) (*iresolver.RPCConfig, error) { return &iresolver.RPCConfig{ Context: rpcInfo.Context, MethodConfig: getMethodConfig(dcs.sc, rpcInfo.Method), }, nil } // NewClient creates a new gRPC "channel" for the target URI provided. No I/O // is performed. Use of the ClientConn for RPCs will automatically cause it to // connect. The Connect method may be called to manually create a connection, // but for most users this should be unnecessary. // // The target name syntax is defined in // https://github.com/grpc/grpc/blob/master/doc/naming.md. E.g. to use the dns // name resolver, a "dns:///" prefix may be applied to the target. The default // name resolver will be used if no scheme is detected, or if the parsed scheme // is not a registered name resolver. The default resolver is "dns" but can be // overridden using the resolver package's SetDefaultScheme. // // Examples: // // - "foo.googleapis.com:8080" // - "dns:///foo.googleapis.com:8080" // - "dns:///foo.googleapis.com" // - "dns:///10.0.0.213:8080" // - "dns:///%5B2001:db8:85a3:8d3:1319:8a2e:370:7348%5D:443" // - "dns://8.8.8.8/foo.googleapis.com:8080" // - "dns://8.8.8.8/foo.googleapis.com" // - "zookeeper://zk.example.com:9900/example_service" // // The DialOptions returned by WithBlock, WithTimeout, // WithReturnConnectionError, and FailOnNonTempDialError are ignored by this // function. func NewClient(target string, opts ...DialOption) (conn *ClientConn, err error) { cc := &ClientConn{ target: target, conns: make(map[*addrConn]struct{}), dopts: defaultDialOptions(), } cc.retryThrottler.Store((*retryThrottler)(nil)) cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) cc.ctx, cc.cancel = context.WithCancel(context.Background()) // Apply dial options. disableGlobalOpts := false for _, opt := range opts { if _, ok := opt.(*disableGlobalDialOptions); ok { disableGlobalOpts = true break } } if !disableGlobalOpts { for _, opt := range globalDialOptions { opt.apply(&cc.dopts) } } for _, opt := range opts { opt.apply(&cc.dopts) } // Determine the resolver to use. if err := cc.initParsedTargetAndResolverBuilder(); err != nil { return nil, err } for _, opt := range globalPerTargetDialOptions { opt.DialOptionForTarget(cc.parsedTarget.URL).apply(&cc.dopts) } chainUnaryClientInterceptors(cc) chainStreamClientInterceptors(cc) if err := cc.validateTransportCredentials(); err != nil { return nil, err } if cc.dopts.defaultServiceConfigRawJSON != nil { scpr := parseServiceConfig(*cc.dopts.defaultServiceConfigRawJSON, cc.dopts.maxCallAttempts) if scpr.Err != nil { return nil, fmt.Errorf("%s: %v", invalidDefaultServiceConfigErrPrefix, scpr.Err) } cc.dopts.defaultServiceConfig, _ = scpr.Config.(*ServiceConfig) } cc.keepaliveParams = cc.dopts.copts.KeepaliveParams if err = cc.initAuthority(); err != nil { return nil, err } // Register ClientConn with channelz. Note that this is only done after // channel creation cannot fail. cc.channelzRegistration(target) channelz.Infof(logger, cc.channelz, "parsed dial target is: %#v", cc.parsedTarget) channelz.Infof(logger, cc.channelz, "Channel authority set to %q", cc.authority) cc.csMgr = newConnectivityStateManager(cc.ctx, cc.channelz) cc.pickerWrapper = newPickerWrapper(cc.dopts.copts.StatsHandlers) cc.metricsRecorderList = stats.NewMetricsRecorderList(cc.dopts.copts.StatsHandlers) cc.initIdleStateLocked() // Safe to call without the lock, since nothing else has a reference to cc. cc.idlenessMgr = idle.NewManager((*idler)(cc), cc.dopts.idleTimeout) return cc, nil } // Dial calls DialContext(context.Background(), target, opts...). // // Deprecated: use NewClient instead. Will be supported throughout 1.x. func Dial(target string, opts ...DialOption) (*ClientConn, error) { return DialContext(context.Background(), target, opts...) } // DialContext calls NewClient and then exits idle mode. If WithBlock(true) is // used, it calls Connect and WaitForStateChange until either the context // expires or the state of the ClientConn is Ready. // // One subtle difference between NewClient and Dial and DialContext is that the // former uses "dns" as the default name resolver, while the latter use // "passthrough" for backward compatibility. This distinction should not matter // to most users, but could matter to legacy users that specify a custom dialer // and expect it to receive the target string directly. // // Deprecated: use NewClient instead. Will be supported throughout 1.x. func DialContext(ctx context.Context, target string, opts ...DialOption) (conn *ClientConn, err error) { // At the end of this method, we kick the channel out of idle, rather than // waiting for the first rpc. // // WithLocalDNSResolution dial option in `grpc.Dial` ensures that it // preserves behavior: when default scheme passthrough is used, skip // hostname resolution, when "dns" is used for resolution, perform // resolution on the client. opts = append([]DialOption{withDefaultScheme("passthrough"), WithLocalDNSResolution()}, opts...) cc, err := NewClient(target, opts...) if err != nil { return nil, err } // We start the channel off in idle mode, but kick it out of idle now, // instead of waiting for the first RPC. This is the legacy behavior of // Dial. defer func() { if err != nil { cc.Close() } }() // This creates the name resolver, load balancer, etc. if err := cc.idlenessMgr.ExitIdleMode(); err != nil { return nil, err } // Return now for non-blocking dials. if !cc.dopts.block { return cc, nil } if cc.dopts.timeout > 0 { var cancel context.CancelFunc ctx, cancel = context.WithTimeout(ctx, cc.dopts.timeout) defer cancel() } defer func() { select { case <-ctx.Done(): switch { case ctx.Err() == err: conn = nil case err == nil || !cc.dopts.returnLastError: conn, err = nil, ctx.Err() default: conn, err = nil, fmt.Errorf("%v: %v", ctx.Err(), err) } default: } }() // A blocking dial blocks until the clientConn is ready. for { s := cc.GetState() if s == connectivity.Idle { cc.Connect() } if s == connectivity.Ready { return cc, nil } else if cc.dopts.copts.FailOnNonTempDialError && s == connectivity.TransientFailure { if err = cc.connectionError(); err != nil { terr, ok := err.(interface { Temporary() bool }) if ok && !terr.Temporary() { return nil, err } } } if !cc.WaitForStateChange(ctx, s) { // ctx got timeout or canceled. if err = cc.connectionError(); err != nil && cc.dopts.returnLastError { return nil, err } return nil, ctx.Err() } } } // addTraceEvent is a helper method to add a trace event on the channel. If the // channel is a nested one, the same event is also added on the parent channel. func (cc *ClientConn) addTraceEvent(msg string) { ted := &channelz.TraceEvent{ Desc: fmt.Sprintf("Channel %s", msg), Severity: channelz.CtInfo, } if cc.dopts.channelzParent != nil { ted.Parent = &channelz.TraceEvent{ Desc: fmt.Sprintf("Nested channel(id:%d) %s", cc.channelz.ID, msg), Severity: channelz.CtInfo, } } channelz.AddTraceEvent(logger, cc.channelz, 0, ted) } type idler ClientConn func (i *idler) EnterIdleMode() { (*ClientConn)(i).enterIdleMode() } func (i *idler) ExitIdleMode() error { return (*ClientConn)(i).exitIdleMode() } // exitIdleMode moves the channel out of idle mode by recreating the name // resolver and load balancer. This should never be called directly; use // cc.idlenessMgr.ExitIdleMode instead. func (cc *ClientConn) exitIdleMode() (err error) { cc.mu.Lock() if cc.conns == nil { cc.mu.Unlock() return errConnClosing } cc.mu.Unlock() // This needs to be called without cc.mu because this builds a new resolver // which might update state or report error inline, which would then need to // acquire cc.mu. if err := cc.resolverWrapper.start(); err != nil { return err } cc.addTraceEvent("exiting idle mode") return nil } // initIdleStateLocked initializes common state to how it should be while idle. func (cc *ClientConn) initIdleStateLocked() { cc.resolverWrapper = newCCResolverWrapper(cc) cc.balancerWrapper = newCCBalancerWrapper(cc) cc.firstResolveEvent = grpcsync.NewEvent() // cc.conns == nil is a proxy for the ClientConn being closed. So, instead // of setting it to nil here, we recreate the map. This also means that we // don't have to do this when exiting idle mode. cc.conns = make(map[*addrConn]struct{}) } // enterIdleMode puts the channel in idle mode, and as part of it shuts down the // name resolver, load balancer, and any subchannels. This should never be // called directly; use cc.idlenessMgr.EnterIdleMode instead. func (cc *ClientConn) enterIdleMode() { cc.mu.Lock() if cc.conns == nil { cc.mu.Unlock() return } conns := cc.conns rWrapper := cc.resolverWrapper rWrapper.close() cc.pickerWrapper.reset() bWrapper := cc.balancerWrapper bWrapper.close() cc.csMgr.updateState(connectivity.Idle) cc.addTraceEvent("entering idle mode") cc.initIdleStateLocked() cc.mu.Unlock() // Block until the name resolver and LB policy are closed. <-rWrapper.serializer.Done() <-bWrapper.serializer.Done() // Close all subchannels after the LB policy is closed. for ac := range conns { ac.tearDown(errConnIdling) } } // validateTransportCredentials performs a series of checks on the configured // transport credentials. It returns a non-nil error if any of these conditions // are met: // - no transport creds and no creds bundle is configured // - both transport creds and creds bundle are configured // - creds bundle is configured, but it lacks a transport credentials // - insecure transport creds configured alongside call creds that require // transport level security // // If none of the above conditions are met, the configured credentials are // deemed valid and a nil error is returned. func (cc *ClientConn) validateTransportCredentials() error { if cc.dopts.copts.TransportCredentials == nil && cc.dopts.copts.CredsBundle == nil { return errNoTransportSecurity } if cc.dopts.copts.TransportCredentials != nil && cc.dopts.copts.CredsBundle != nil { return errTransportCredsAndBundle } if cc.dopts.copts.CredsBundle != nil && cc.dopts.copts.CredsBundle.TransportCredentials() == nil { return errNoTransportCredsInBundle } transportCreds := cc.dopts.copts.TransportCredentials if transportCreds == nil { transportCreds = cc.dopts.copts.CredsBundle.TransportCredentials() } if transportCreds.Info().SecurityProtocol == "insecure" { for _, cd := range cc.dopts.copts.PerRPCCredentials { if cd.RequireTransportSecurity() { return errTransportCredentialsMissing } } } return nil } // channelzRegistration registers the newly created ClientConn with channelz and // stores the returned identifier in `cc.channelz`. A channelz trace event is // emitted for ClientConn creation. If the newly created ClientConn is a nested // one, i.e a valid parent ClientConn ID is specified via a dial option, the // trace event is also added to the parent. // // Doesn't grab cc.mu as this method is expected to be called only at Dial time. func (cc *ClientConn) channelzRegistration(target string) { parentChannel, _ := cc.dopts.channelzParent.(*channelz.Channel) cc.channelz = channelz.RegisterChannel(parentChannel, target) cc.addTraceEvent("created") } // chainUnaryClientInterceptors chains all unary client interceptors into one. func chainUnaryClientInterceptors(cc *ClientConn) { interceptors := cc.dopts.chainUnaryInts // Prepend dopts.unaryInt to the chaining interceptors if it exists, since unaryInt will // be executed before any other chained interceptors. if cc.dopts.unaryInt != nil { interceptors = append([]UnaryClientInterceptor{cc.dopts.unaryInt}, interceptors...) } var chainedInt UnaryClientInterceptor if len(interceptors) == 0 { chainedInt = nil } else if len(interceptors) == 1 { chainedInt = interceptors[0] } else { chainedInt = func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error { return interceptors[0](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, 0, invoker), opts...) } } cc.dopts.unaryInt = chainedInt } // getChainUnaryInvoker recursively generate the chained unary invoker. func getChainUnaryInvoker(interceptors []UnaryClientInterceptor, curr int, finalInvoker UnaryInvoker) UnaryInvoker { if curr == len(interceptors)-1 { return finalInvoker } return func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error { return interceptors[curr+1](ctx, method, req, reply, cc, getChainUnaryInvoker(interceptors, curr+1, finalInvoker), opts...) } } // chainStreamClientInterceptors chains all stream client interceptors into one. func chainStreamClientInterceptors(cc *ClientConn) { interceptors := cc.dopts.chainStreamInts // Prepend dopts.streamInt to the chaining interceptors if it exists, since streamInt will // be executed before any other chained interceptors. if cc.dopts.streamInt != nil { interceptors = append([]StreamClientInterceptor{cc.dopts.streamInt}, interceptors...) } var chainedInt StreamClientInterceptor if len(interceptors) == 0 { chainedInt = nil } else if len(interceptors) == 1 { chainedInt = interceptors[0] } else { chainedInt = func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) { return interceptors[0](ctx, desc, cc, method, getChainStreamer(interceptors, 0, streamer), opts...) } } cc.dopts.streamInt = chainedInt } // getChainStreamer recursively generate the chained client stream constructor. func getChainStreamer(interceptors []StreamClientInterceptor, curr int, finalStreamer Streamer) Streamer { if curr == len(interceptors)-1 { return finalStreamer } return func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { return interceptors[curr+1](ctx, desc, cc, method, getChainStreamer(interceptors, curr+1, finalStreamer), opts...) } } // newConnectivityStateManager creates an connectivityStateManager with // the specified channel. func newConnectivityStateManager(ctx context.Context, channel *channelz.Channel) *connectivityStateManager { return &connectivityStateManager{ channelz: channel, pubSub: grpcsync.NewPubSub(ctx), } } // connectivityStateManager keeps the connectivity.State of ClientConn. // This struct will eventually be exported so the balancers can access it. // // TODO: If possible, get rid of the `connectivityStateManager` type, and // provide this functionality using the `PubSub`, to avoid keeping track of // the connectivity state at two places. type connectivityStateManager struct { mu sync.Mutex state connectivity.State notifyChan chan struct{} channelz *channelz.Channel pubSub *grpcsync.PubSub } // updateState updates the connectivity.State of ClientConn. // If there's a change it notifies goroutines waiting on state change to // happen. func (csm *connectivityStateManager) updateState(state connectivity.State) { csm.mu.Lock() defer csm.mu.Unlock() if csm.state == connectivity.Shutdown { return } if csm.state == state { return } csm.state = state csm.channelz.ChannelMetrics.State.Store(&state) csm.pubSub.Publish(state) channelz.Infof(logger, csm.channelz, "Channel Connectivity change to %v", state) if csm.notifyChan != nil { // There are other goroutines waiting on this channel. close(csm.notifyChan) csm.notifyChan = nil } } func (csm *connectivityStateManager) getState() connectivity.State { csm.mu.Lock() defer csm.mu.Unlock() return csm.state } func (csm *connectivityStateManager) getNotifyChan() <-chan struct{} { csm.mu.Lock() defer csm.mu.Unlock() if csm.notifyChan == nil { csm.notifyChan = make(chan struct{}) } return csm.notifyChan } // ClientConnInterface defines the functions clients need to perform unary and // streaming RPCs. It is implemented by *ClientConn, and is only intended to // be referenced by generated code. type ClientConnInterface interface { // Invoke performs a unary RPC and returns after the response is received // into reply. Invoke(ctx context.Context, method string, args any, reply any, opts ...CallOption) error // NewStream begins a streaming RPC. NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) } // Assert *ClientConn implements ClientConnInterface. var _ ClientConnInterface = (*ClientConn)(nil) // ClientConn represents a virtual connection to a conceptual endpoint, to // perform RPCs. // // A ClientConn is free to have zero or more actual connections to the endpoint // based on configuration, load, etc. It is also free to determine which actual // endpoints to use and may change it every RPC, permitting client-side load // balancing. // // A ClientConn encapsulates a range of functionality including name // resolution, TCP connection establishment (with retries and backoff) and TLS // handshakes. It also handles errors on established connections by // re-resolving the name and reconnecting. type ClientConn struct { ctx context.Context // Initialized using the background context at dial time. cancel context.CancelFunc // Cancelled on close. // The following are initialized at dial time, and are read-only after that. target string // User's dial target. parsedTarget resolver.Target // See initParsedTargetAndResolverBuilder(). authority string // See initAuthority(). dopts dialOptions // Default and user specified dial options. channelz *channelz.Channel // Channelz object. resolverBuilder resolver.Builder // See initParsedTargetAndResolverBuilder(). idlenessMgr *idle.Manager metricsRecorderList *stats.MetricsRecorderList // The following provide their own synchronization, and therefore don't // require cc.mu to be held to access them. csMgr *connectivityStateManager pickerWrapper *pickerWrapper safeConfigSelector iresolver.SafeConfigSelector retryThrottler atomic.Value // Updated from service config. // mu protects the following fields. // TODO: split mu so the same mutex isn't used for everything. mu sync.RWMutex resolverWrapper *ccResolverWrapper // Always recreated whenever entering idle to simplify Close. balancerWrapper *ccBalancerWrapper // Always recreated whenever entering idle to simplify Close. sc *ServiceConfig // Latest service config received from the resolver. conns map[*addrConn]struct{} // Set to nil on close. keepaliveParams keepalive.ClientParameters // May be updated upon receipt of a GoAway. // firstResolveEvent is used to track whether the name resolver sent us at // least one update. RPCs block on this event. May be accessed without mu // if we know we cannot be asked to enter idle mode while accessing it (e.g. // when the idle manager has already been closed, or if we are already // entering idle mode). firstResolveEvent *grpcsync.Event lceMu sync.Mutex // protects lastConnectionError lastConnectionError error } // WaitForStateChange waits until the connectivity.State of ClientConn changes from sourceState or // ctx expires. A true value is returned in former case and false in latter. func (cc *ClientConn) WaitForStateChange(ctx context.Context, sourceState connectivity.State) bool { ch := cc.csMgr.getNotifyChan() if cc.csMgr.getState() != sourceState { return true } select { case <-ctx.Done(): return false case <-ch: return true } } // GetState returns the connectivity.State of ClientConn. func (cc *ClientConn) GetState() connectivity.State { return cc.csMgr.getState() } // Connect causes all subchannels in the ClientConn to attempt to connect if // the channel is idle. Does not wait for the connection attempts to begin // before returning. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a later // release. func (cc *ClientConn) Connect() { if err := cc.idlenessMgr.ExitIdleMode(); err != nil { cc.addTraceEvent(err.Error()) return } // If the ClientConn was not in idle mode, we need to call ExitIdle on the // LB policy so that connections can be created. cc.mu.Lock() cc.balancerWrapper.exitIdle() cc.mu.Unlock() } // waitForResolvedAddrs blocks until the resolver has provided addresses or the // context expires. Returns nil unless the context expires first; otherwise // returns a status error based on the context. func (cc *ClientConn) waitForResolvedAddrs(ctx context.Context) error { // This is on the RPC path, so we use a fast path to avoid the // more-expensive "select" below after the resolver has returned once. if cc.firstResolveEvent.HasFired() { return nil } select { case <-cc.firstResolveEvent.Done(): return nil case <-ctx.Done(): return status.FromContextError(ctx.Err()).Err() case <-cc.ctx.Done(): return ErrClientConnClosing } } var emptyServiceConfig *ServiceConfig func init() { cfg := parseServiceConfig("{}", defaultMaxCallAttempts) if cfg.Err != nil { panic(fmt.Sprintf("impossible error parsing empty service config: %v", cfg.Err)) } emptyServiceConfig = cfg.Config.(*ServiceConfig) internal.SubscribeToConnectivityStateChanges = func(cc *ClientConn, s grpcsync.Subscriber) func() { return cc.csMgr.pubSub.Subscribe(s) } internal.EnterIdleModeForTesting = func(cc *ClientConn) { cc.idlenessMgr.EnterIdleModeForTesting() } internal.ExitIdleModeForTesting = func(cc *ClientConn) error { return cc.idlenessMgr.ExitIdleMode() } } func (cc *ClientConn) maybeApplyDefaultServiceConfig() { if cc.sc != nil { cc.applyServiceConfigAndBalancer(cc.sc, nil) return } if cc.dopts.defaultServiceConfig != nil { cc.applyServiceConfigAndBalancer(cc.dopts.defaultServiceConfig, &defaultConfigSelector{cc.dopts.defaultServiceConfig}) } else { cc.applyServiceConfigAndBalancer(emptyServiceConfig, &defaultConfigSelector{emptyServiceConfig}) } } func (cc *ClientConn) updateResolverStateAndUnlock(s resolver.State, err error) error { defer cc.firstResolveEvent.Fire() // Check if the ClientConn is already closed. Some fields (e.g. // balancerWrapper) are set to nil when closing the ClientConn, and could // cause nil pointer panic if we don't have this check. if cc.conns == nil { cc.mu.Unlock() return nil } if err != nil { // May need to apply the initial service config in case the resolver // doesn't support service configs, or doesn't provide a service config // with the new addresses. cc.maybeApplyDefaultServiceConfig() cc.balancerWrapper.resolverError(err) // No addresses are valid with err set; return early. cc.mu.Unlock() return balancer.ErrBadResolverState } var ret error if cc.dopts.disableServiceConfig { channelz.Infof(logger, cc.channelz, "ignoring service config from resolver (%v) and applying the default because service config is disabled", s.ServiceConfig) cc.maybeApplyDefaultServiceConfig() } else if s.ServiceConfig == nil { cc.maybeApplyDefaultServiceConfig() // TODO: do we need to apply a failing LB policy if there is no // default, per the error handling design? } else { if sc, ok := s.ServiceConfig.Config.(*ServiceConfig); s.ServiceConfig.Err == nil && ok { configSelector := iresolver.GetConfigSelector(s) if configSelector != nil { if len(s.ServiceConfig.Config.(*ServiceConfig).Methods) != 0 { channelz.Infof(logger, cc.channelz, "method configs in service config will be ignored due to presence of config selector") } } else { configSelector = &defaultConfigSelector{sc} } cc.applyServiceConfigAndBalancer(sc, configSelector) } else { ret = balancer.ErrBadResolverState if cc.sc == nil { // Apply the failing LB only if we haven't received valid service config // from the name resolver in the past. cc.applyFailingLBLocked(s.ServiceConfig) cc.mu.Unlock() return ret } } } balCfg := cc.sc.lbConfig bw := cc.balancerWrapper cc.mu.Unlock() uccsErr := bw.updateClientConnState(&balancer.ClientConnState{ResolverState: s, BalancerConfig: balCfg}) if ret == nil { ret = uccsErr // prefer ErrBadResolver state since any other error is // currently meaningless to the caller. } return ret } // applyFailingLBLocked is akin to configuring an LB policy on the channel which // always fails RPCs. Here, an actual LB policy is not configured, but an always // erroring picker is configured, which returns errors with information about // what was invalid in the received service config. A config selector with no // service config is configured, and the connectivity state of the channel is // set to TransientFailure. func (cc *ClientConn) applyFailingLBLocked(sc *serviceconfig.ParseResult) { var err error if sc.Err != nil { err = status.Errorf(codes.Unavailable, "error parsing service config: %v", sc.Err) } else { err = status.Errorf(codes.Unavailable, "illegal service config type: %T", sc.Config) } cc.safeConfigSelector.UpdateConfigSelector(&defaultConfigSelector{nil}) cc.pickerWrapper.updatePicker(base.NewErrPicker(err)) cc.csMgr.updateState(connectivity.TransientFailure) } // Makes a copy of the input addresses slice. Addresses are passed during // subconn creation and address update operations. func copyAddresses(in []resolver.Address) []resolver.Address { out := make([]resolver.Address, len(in)) copy(out, in) return out } // newAddrConnLocked creates an addrConn for addrs and adds it to cc.conns. // // Caller needs to make sure len(addrs) > 0. func (cc *ClientConn) newAddrConnLocked(addrs []resolver.Address, opts balancer.NewSubConnOptions) (*addrConn, error) { if cc.conns == nil { return nil, ErrClientConnClosing } ac := &addrConn{ state: connectivity.Idle, cc: cc, addrs: copyAddresses(addrs), scopts: opts, dopts: cc.dopts, channelz: channelz.RegisterSubChannel(cc.channelz, ""), resetBackoff: make(chan struct{}), } ac.ctx, ac.cancel = context.WithCancel(cc.ctx) // Start with our address set to the first address; this may be updated if // we connect to different addresses. ac.channelz.ChannelMetrics.Target.Store(&addrs[0].Addr) channelz.AddTraceEvent(logger, ac.channelz, 0, &channelz.TraceEvent{ Desc: "Subchannel created", Severity: channelz.CtInfo, Parent: &channelz.TraceEvent{ Desc: fmt.Sprintf("Subchannel(id:%d) created", ac.channelz.ID), Severity: channelz.CtInfo, }, }) // Track ac in cc. This needs to be done before any getTransport(...) is called. cc.conns[ac] = struct{}{} return ac, nil } // removeAddrConn removes the addrConn in the subConn from clientConn. // It also tears down the ac with the given error. func (cc *ClientConn) removeAddrConn(ac *addrConn, err error) { cc.mu.Lock() if cc.conns == nil { cc.mu.Unlock() return } delete(cc.conns, ac) cc.mu.Unlock() ac.tearDown(err) } // Target returns the target string of the ClientConn. func (cc *ClientConn) Target() string { return cc.target } // CanonicalTarget returns the canonical target string used when creating cc. // // This always has the form "<scheme>://[authority]/<endpoint>". For example: // // - "dns:///example.com:42" // - "dns://8.8.8.8/example.com:42" // - "unix:///path/to/socket" func (cc *ClientConn) CanonicalTarget() string { return cc.parsedTarget.String() } func (cc *ClientConn) incrCallsStarted() { cc.channelz.ChannelMetrics.CallsStarted.Add(1) cc.channelz.ChannelMetrics.LastCallStartedTimestamp.Store(time.Now().UnixNano()) } func (cc *ClientConn) incrCallsSucceeded() { cc.channelz.ChannelMetrics.CallsSucceeded.Add(1) } func (cc *ClientConn) incrCallsFailed() {
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stream.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stream.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "errors" "io" "math" rand "math/rand/v2" "strconv" "sync" "time" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/encoding" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/balancerload" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcutil" imetadata "google.golang.org/grpc/internal/metadata" iresolver "google.golang.org/grpc/internal/resolver" "google.golang.org/grpc/internal/serviceconfig" istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) var metadataFromOutgoingContextRaw = internal.FromOutgoingContextRaw.(func(context.Context) (metadata.MD, [][]string, bool)) // StreamHandler defines the handler called by gRPC server to complete the // execution of a streaming RPC. // // If a StreamHandler returns an error, it should either be produced by the // status package, or be one of the context errors. Otherwise, gRPC will use // codes.Unknown as the status code and err.Error() as the status message of the // RPC. type StreamHandler func(srv any, stream ServerStream) error // StreamDesc represents a streaming RPC service's method specification. Used // on the server when registering services and on the client when initiating // new streams. type StreamDesc struct { // StreamName and Handler are only used when registering handlers on a // server. StreamName string // the name of the method excluding the service Handler StreamHandler // the handler called for the method // ServerStreams and ClientStreams are used for registering handlers on a // server as well as defining RPC behavior when passed to NewClientStream // and ClientConn.NewStream. At least one must be true. ServerStreams bool // indicates the server can perform streaming sends ClientStreams bool // indicates the client can perform streaming sends } // Stream defines the common interface a client or server stream has to satisfy. // // Deprecated: See ClientStream and ServerStream documentation instead. type Stream interface { // Deprecated: See ClientStream and ServerStream documentation instead. Context() context.Context // Deprecated: See ClientStream and ServerStream documentation instead. SendMsg(m any) error // Deprecated: See ClientStream and ServerStream documentation instead. RecvMsg(m any) error } // ClientStream defines the client-side behavior of a streaming RPC. // // All errors returned from ClientStream methods are compatible with the // status package. type ClientStream interface { // Header returns the header metadata received from the server if there // is any. It blocks if the metadata is not ready to read. If the metadata // is nil and the error is also nil, then the stream was terminated without // headers, and the status can be discovered by calling RecvMsg. Header() (metadata.MD, error) // Trailer returns the trailer metadata from the server, if there is any. // It must only be called after stream.CloseAndRecv has returned, or // stream.Recv has returned a non-nil error (including io.EOF). Trailer() metadata.MD // CloseSend closes the send direction of the stream. It closes the stream // when non-nil error is met. It is also not safe to call CloseSend // concurrently with SendMsg. CloseSend() error // Context returns the context for this stream. // // It should not be called until after Header or RecvMsg has returned. Once // called, subsequent client-side retries are disabled. Context() context.Context // SendMsg is generally called by generated code. On error, SendMsg aborts // the stream. If the error was generated by the client, the status is // returned directly; otherwise, io.EOF is returned and the status of // the stream may be discovered using RecvMsg. For unary or server-streaming // RPCs (StreamDesc.ClientStreams is false), a nil error is returned // unconditionally. // // SendMsg blocks until: // - There is sufficient flow control to schedule m with the transport, or // - The stream is done, or // - The stream breaks. // // SendMsg does not wait until the message is received by the server. An // untimely stream closure may result in lost messages. To ensure delivery, // users should ensure the RPC completed successfully using RecvMsg. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not safe // to call SendMsg on the same stream in different goroutines. It is also // not safe to call CloseSend concurrently with SendMsg. // // It is not safe to modify the message after calling SendMsg. Tracing // libraries and stats handlers may use the message lazily. SendMsg(m any) error // RecvMsg blocks until it receives a message into m or the stream is // done. It returns io.EOF when the stream completes successfully. On // any other error, the stream is aborted and the error contains the RPC // status. // // It is safe to have a goroutine calling SendMsg and another goroutine // calling RecvMsg on the same stream at the same time, but it is not // safe to call RecvMsg on the same stream in different goroutines. RecvMsg(m any) error } // NewStream creates a new Stream for the client side. This is typically // called by generated code. ctx is used for the lifetime of the stream. // // To ensure resources are not leaked due to the stream returned, one of the following // actions must be performed: // // 1. Call Close on the ClientConn. // 2. Cancel the context provided. // 3. Call RecvMsg until a non-nil error is returned. A protobuf-generated // client-streaming RPC, for instance, might use the helper function // CloseAndRecv (note that CloseSend does not Recv, therefore is not // guaranteed to release all resources). // 4. Receive a non-nil, non-io.EOF error from Header or SendMsg. // // If none of the above happen, a goroutine and a context will be leaked, and grpc // will not call the optionally-configured stats handler with a stats.End message. func (cc *ClientConn) NewStream(ctx context.Context, desc *StreamDesc, method string, opts ...CallOption) (ClientStream, error) { // allow interceptor to see all applicable call options, which means those // configured as defaults from dial option as well as per-call options opts = combine(cc.dopts.callOptions, opts) if cc.dopts.streamInt != nil { return cc.dopts.streamInt(ctx, desc, cc, method, newClientStream, opts...) } return newClientStream(ctx, desc, cc, method, opts...) } // NewClientStream is a wrapper for ClientConn.NewStream. func NewClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) { return cc.NewStream(ctx, desc, method, opts...) } func newClientStream(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (_ ClientStream, err error) { // Start tracking the RPC for idleness purposes. This is where a stream is // created for both streaming and unary RPCs, and hence is a good place to // track active RPC count. if err := cc.idlenessMgr.OnCallBegin(); err != nil { return nil, err } // Add a calloption, to decrement the active call count, that gets executed // when the RPC completes. opts = append([]CallOption{OnFinish(func(error) { cc.idlenessMgr.OnCallEnd() })}, opts...) if md, added, ok := metadataFromOutgoingContextRaw(ctx); ok { // validate md if err := imetadata.Validate(md); err != nil { return nil, status.Error(codes.Internal, err.Error()) } // validate added for _, kvs := range added { for i := 0; i < len(kvs); i += 2 { if err := imetadata.ValidatePair(kvs[i], kvs[i+1]); err != nil { return nil, status.Error(codes.Internal, err.Error()) } } } } if channelz.IsOn() { cc.incrCallsStarted() defer func() { if err != nil { cc.incrCallsFailed() } }() } // Provide an opportunity for the first RPC to see the first service config // provided by the resolver. if err := cc.waitForResolvedAddrs(ctx); err != nil { return nil, err } var mc serviceconfig.MethodConfig var onCommit func() newStream := func(ctx context.Context, done func()) (iresolver.ClientStream, error) { return newClientStreamWithParams(ctx, desc, cc, method, mc, onCommit, done, opts...) } rpcInfo := iresolver.RPCInfo{Context: ctx, Method: method} rpcConfig, err := cc.safeConfigSelector.SelectConfig(rpcInfo) if err != nil { if st, ok := status.FromError(err); ok { // Restrict the code to the list allowed by gRFC A54. if istatus.IsRestrictedControlPlaneCode(st) { err = status.Errorf(codes.Internal, "config selector returned illegal status: %v", err) } return nil, err } return nil, toRPCErr(err) } if rpcConfig != nil { if rpcConfig.Context != nil { ctx = rpcConfig.Context } mc = rpcConfig.MethodConfig onCommit = rpcConfig.OnCommitted if rpcConfig.Interceptor != nil { rpcInfo.Context = nil ns := newStream newStream = func(ctx context.Context, done func()) (iresolver.ClientStream, error) { cs, err := rpcConfig.Interceptor.NewStream(ctx, rpcInfo, done, ns) if err != nil { return nil, toRPCErr(err) } return cs, nil } } } return newStream(ctx, func() {}) } func newClientStreamWithParams(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, mc serviceconfig.MethodConfig, onCommit, doneFunc func(), opts ...CallOption) (_ iresolver.ClientStream, err error) { callInfo := defaultCallInfo() if mc.WaitForReady != nil { callInfo.failFast = !*mc.WaitForReady } // Possible context leak: // The cancel function for the child context we create will only be called // when RecvMsg returns a non-nil error, if the ClientConn is closed, or if // an error is generated by SendMsg. // https://github.com/grpc/grpc-go/issues/1818. var cancel context.CancelFunc if mc.Timeout != nil && *mc.Timeout >= 0 { ctx, cancel = context.WithTimeout(ctx, *mc.Timeout) } else { ctx, cancel = context.WithCancel(ctx) } defer func() { if err != nil { cancel() } }() for _, o := range opts { if err := o.before(callInfo); err != nil { return nil, toRPCErr(err) } } callInfo.maxSendMessageSize = getMaxSize(mc.MaxReqSize, callInfo.maxSendMessageSize, defaultClientMaxSendMessageSize) callInfo.maxReceiveMessageSize = getMaxSize(mc.MaxRespSize, callInfo.maxReceiveMessageSize, defaultClientMaxReceiveMessageSize) if err := setCallInfoCodec(callInfo); err != nil { return nil, err } callHdr := &transport.CallHdr{ Host: cc.authority, Method: method, ContentSubtype: callInfo.contentSubtype, DoneFunc: doneFunc, } // Set our outgoing compression according to the UseCompressor CallOption, if // set. In that case, also find the compressor from the encoding package. // Otherwise, use the compressor configured by the WithCompressor DialOption, // if set. var compressorV0 Compressor var compressorV1 encoding.Compressor if ct := callInfo.compressorName; ct != "" { callHdr.SendCompress = ct if ct != encoding.Identity { compressorV1 = encoding.GetCompressor(ct) if compressorV1 == nil { return nil, status.Errorf(codes.Internal, "grpc: Compressor is not installed for requested grpc-encoding %q", ct) } } } else if cc.dopts.compressorV0 != nil { callHdr.SendCompress = cc.dopts.compressorV0.Type() compressorV0 = cc.dopts.compressorV0 } if callInfo.creds != nil { callHdr.Creds = callInfo.creds } cs := &clientStream{ callHdr: callHdr, ctx: ctx, methodConfig: &mc, opts: opts, callInfo: callInfo, cc: cc, desc: desc, codec: callInfo.codec, compressorV0: compressorV0, compressorV1: compressorV1, cancel: cancel, firstAttempt: true, onCommit: onCommit, } if !cc.dopts.disableRetry { cs.retryThrottler = cc.retryThrottler.Load().(*retryThrottler) } if ml := binarylog.GetMethodLogger(method); ml != nil { cs.binlogs = append(cs.binlogs, ml) } if cc.dopts.binaryLogger != nil { if ml := cc.dopts.binaryLogger.GetMethodLogger(method); ml != nil { cs.binlogs = append(cs.binlogs, ml) } } // Pick the transport to use and create a new stream on the transport. // Assign cs.attempt upon success. op := func(a *csAttempt) error { if err := a.getTransport(); err != nil { return err } if err := a.newStream(); err != nil { return err } // Because this operation is always called either here (while creating // the clientStream) or by the retry code while locked when replaying // the operation, it is safe to access cs.attempt directly. cs.attempt = a return nil } if err := cs.withRetry(op, func() { cs.bufferForRetryLocked(0, op, nil) }); err != nil { return nil, err } if len(cs.binlogs) != 0 { md, _ := metadata.FromOutgoingContext(ctx) logEntry := &binarylog.ClientHeader{ OnClientSide: true, Header: md, MethodName: method, Authority: cs.cc.authority, } if deadline, ok := ctx.Deadline(); ok { logEntry.Timeout = time.Until(deadline) if logEntry.Timeout < 0 { logEntry.Timeout = 0 } } for _, binlog := range cs.binlogs { binlog.Log(cs.ctx, logEntry) } } if desc != unaryStreamDesc { // Listen on cc and stream contexts to cleanup when the user closes the // ClientConn or cancels the stream context. In all other cases, an error // should already be injected into the recv buffer by the transport, which // the client will eventually receive, and then we will cancel the stream's // context in clientStream.finish. go func() { select { case <-cc.ctx.Done(): cs.finish(ErrClientConnClosing) case <-ctx.Done(): cs.finish(toRPCErr(ctx.Err())) } }() } return cs, nil } // newAttemptLocked creates a new csAttempt without a transport or stream. func (cs *clientStream) newAttemptLocked(isTransparent bool) (*csAttempt, error) { if err := cs.ctx.Err(); err != nil { return nil, toRPCErr(err) } if err := cs.cc.ctx.Err(); err != nil { return nil, ErrClientConnClosing } ctx := newContextWithRPCInfo(cs.ctx, cs.callInfo.failFast, cs.callInfo.codec, cs.compressorV0, cs.compressorV1) method := cs.callHdr.Method var beginTime time.Time shs := cs.cc.dopts.copts.StatsHandlers for _, sh := range shs { ctx = sh.TagRPC(ctx, &stats.RPCTagInfo{FullMethodName: method, FailFast: cs.callInfo.failFast}) beginTime = time.Now() begin := &stats.Begin{ Client: true, BeginTime: beginTime, FailFast: cs.callInfo.failFast, IsClientStream: cs.desc.ClientStreams, IsServerStream: cs.desc.ServerStreams, IsTransparentRetryAttempt: isTransparent, } sh.HandleRPC(ctx, begin) } var trInfo *traceInfo if EnableTracing { trInfo = &traceInfo{ tr: newTrace("grpc.Sent."+methodFamily(method), method), firstLine: firstLine{ client: true, }, } if deadline, ok := ctx.Deadline(); ok { trInfo.firstLine.deadline = time.Until(deadline) } trInfo.tr.LazyLog(&trInfo.firstLine, false) ctx = newTraceContext(ctx, trInfo.tr) } if cs.cc.parsedTarget.URL.Scheme == internal.GRPCResolverSchemeExtraMetadata { // Add extra metadata (metadata that will be added by transport) to context // so the balancer can see them. ctx = grpcutil.WithExtraMetadata(ctx, metadata.Pairs( "content-type", grpcutil.ContentType(cs.callHdr.ContentSubtype), )) } return &csAttempt{ ctx: ctx, beginTime: beginTime, cs: cs, decompressorV0: cs.cc.dopts.dc, statsHandlers: shs, trInfo: trInfo, }, nil } func (a *csAttempt) getTransport() error { cs := a.cs var err error a.transport, a.pickResult, err = cs.cc.getTransport(a.ctx, cs.callInfo.failFast, cs.callHdr.Method) if err != nil { if de, ok := err.(dropError); ok { err = de.error a.drop = true } return err } if a.trInfo != nil { a.trInfo.firstLine.SetRemoteAddr(a.transport.RemoteAddr()) } return nil } func (a *csAttempt) newStream() error { cs := a.cs cs.callHdr.PreviousAttempts = cs.numRetries // Merge metadata stored in PickResult, if any, with existing call metadata. // It is safe to overwrite the csAttempt's context here, since all state // maintained in it are local to the attempt. When the attempt has to be // retried, a new instance of csAttempt will be created. if a.pickResult.Metadata != nil { // We currently do not have a function it the metadata package which // merges given metadata with existing metadata in a context. Existing // function `AppendToOutgoingContext()` takes a variadic argument of key // value pairs. // // TODO: Make it possible to retrieve key value pairs from metadata.MD // in a form passable to AppendToOutgoingContext(), or create a version // of AppendToOutgoingContext() that accepts a metadata.MD. md, _ := metadata.FromOutgoingContext(a.ctx) md = metadata.Join(md, a.pickResult.Metadata) a.ctx = metadata.NewOutgoingContext(a.ctx, md) } s, err := a.transport.NewStream(a.ctx, cs.callHdr) if err != nil { nse, ok := err.(*transport.NewStreamError) if !ok { // Unexpected. return err } if nse.AllowTransparentRetry { a.allowTransparentRetry = true } // Unwrap and convert error. return toRPCErr(nse.Err) } a.transportStream = s a.ctx = s.Context() a.parser = &parser{r: s, bufferPool: a.cs.cc.dopts.copts.BufferPool} return nil } // clientStream implements a client side Stream. type clientStream struct { callHdr *transport.CallHdr opts []CallOption callInfo *callInfo cc *ClientConn desc *StreamDesc codec baseCodec compressorV0 Compressor compressorV1 encoding.Compressor cancel context.CancelFunc // cancels all attempts sentLast bool // sent an end stream methodConfig *MethodConfig ctx context.Context // the application's context, wrapped by stats/tracing retryThrottler *retryThrottler // The throttler active when the RPC began. binlogs []binarylog.MethodLogger // serverHeaderBinlogged is a boolean for whether server header has been // logged. Server header will be logged when the first time one of those // happens: stream.Header(), stream.Recv(). // // It's only read and used by Recv() and Header(), so it doesn't need to be // synchronized. serverHeaderBinlogged bool mu sync.Mutex firstAttempt bool // if true, transparent retry is valid numRetries int // exclusive of transparent retry attempt(s) numRetriesSincePushback int // retries since pushback; to reset backoff finished bool // TODO: replace with atomic cmpxchg or sync.Once? // attempt is the active client stream attempt. // The only place where it is written is the newAttemptLocked method and this method never writes nil. // So, attempt can be nil only inside newClientStream function when clientStream is first created. // One of the first things done after clientStream's creation, is to call newAttemptLocked which either // assigns a non nil value to the attempt or returns an error. If an error is returned from newAttemptLocked, // then newClientStream calls finish on the clientStream and returns. So, finish method is the only // place where we need to check if the attempt is nil. attempt *csAttempt // TODO(hedging): hedging will have multiple attempts simultaneously. committed bool // active attempt committed for retry? onCommit func() replayBuffer []replayOp // operations to replay on retry replayBufferSize int // current size of replayBuffer } type replayOp struct { op func(a *csAttempt) error cleanup func() } // csAttempt implements a single transport stream attempt within a // clientStream. type csAttempt struct { ctx context.Context cs *clientStream transport transport.ClientTransport transportStream *transport.ClientStream parser *parser pickResult balancer.PickResult finished bool decompressorV0 Decompressor decompressorV1 encoding.Compressor decompressorSet bool mu sync.Mutex // guards trInfo.tr // trInfo may be nil (if EnableTracing is false). // trInfo.tr is set when created (if EnableTracing is true), // and cleared when the finish method is called. trInfo *traceInfo statsHandlers []stats.Handler beginTime time.Time // set for newStream errors that may be transparently retried allowTransparentRetry bool // set for pick errors that are returned as a status drop bool } func (cs *clientStream) commitAttemptLocked() { if !cs.committed && cs.onCommit != nil { cs.onCommit() } cs.committed = true for _, op := range cs.replayBuffer { if op.cleanup != nil { op.cleanup() } } cs.replayBuffer = nil } func (cs *clientStream) commitAttempt() { cs.mu.Lock() cs.commitAttemptLocked() cs.mu.Unlock() } // shouldRetry returns nil if the RPC should be retried; otherwise it returns // the error that should be returned by the operation. If the RPC should be // retried, the bool indicates whether it is being retried transparently. func (a *csAttempt) shouldRetry(err error) (bool, error) { cs := a.cs if cs.finished || cs.committed || a.drop { // RPC is finished or committed or was dropped by the picker; cannot retry. return false, err } if a.transportStream == nil && a.allowTransparentRetry { return true, nil } // Wait for the trailers. unprocessed := false if a.transportStream != nil { <-a.transportStream.Done() unprocessed = a.transportStream.Unprocessed() } if cs.firstAttempt && unprocessed { // First attempt, stream unprocessed: transparently retry. return true, nil } if cs.cc.dopts.disableRetry { return false, err } pushback := 0 hasPushback := false if a.transportStream != nil { if !a.transportStream.TrailersOnly() { return false, err } // TODO(retry): Move down if the spec changes to not check server pushback // before considering this a failure for throttling. sps := a.transportStream.Trailer()["grpc-retry-pushback-ms"] if len(sps) == 1 { var e error if pushback, e = strconv.Atoi(sps[0]); e != nil || pushback < 0 { channelz.Infof(logger, cs.cc.channelz, "Server retry pushback specified to abort (%q).", sps[0]) cs.retryThrottler.throttle() // This counts as a failure for throttling. return false, err } hasPushback = true } else if len(sps) > 1 { channelz.Warningf(logger, cs.cc.channelz, "Server retry pushback specified multiple values (%q); not retrying.", sps) cs.retryThrottler.throttle() // This counts as a failure for throttling. return false, err } } var code codes.Code if a.transportStream != nil { code = a.transportStream.Status().Code() } else { code = status.Code(err) } rp := cs.methodConfig.RetryPolicy if rp == nil || !rp.RetryableStatusCodes[code] { return false, err } // Note: the ordering here is important; we count this as a failure // only if the code matched a retryable code. if cs.retryThrottler.throttle() { return false, err } if cs.numRetries+1 >= rp.MaxAttempts { return false, err } var dur time.Duration if hasPushback { dur = time.Millisecond * time.Duration(pushback) cs.numRetriesSincePushback = 0 } else { fact := math.Pow(rp.BackoffMultiplier, float64(cs.numRetriesSincePushback)) cur := min(float64(rp.InitialBackoff)*fact, float64(rp.MaxBackoff)) // Apply jitter by multiplying with a random factor between 0.8 and 1.2 cur *= 0.8 + 0.4*rand.Float64() dur = time.Duration(int64(cur)) cs.numRetriesSincePushback++ } // TODO(dfawley): we could eagerly fail here if dur puts us past the // deadline, but unsure if it is worth doing. t := time.NewTimer(dur) select { case <-t.C: cs.numRetries++ return false, nil case <-cs.ctx.Done(): t.Stop() return false, status.FromContextError(cs.ctx.Err()).Err() } } // Returns nil if a retry was performed and succeeded; error otherwise. func (cs *clientStream) retryLocked(attempt *csAttempt, lastErr error) error { for { attempt.finish(toRPCErr(lastErr)) isTransparent, err := attempt.shouldRetry(lastErr) if err != nil { cs.commitAttemptLocked() return err } cs.firstAttempt = false attempt, err = cs.newAttemptLocked(isTransparent) if err != nil { // Only returns error if the clientconn is closed or the context of // the stream is canceled. return err } // Note that the first op in replayBuffer always sets cs.attempt // if it is able to pick a transport and create a stream. if lastErr = cs.replayBufferLocked(attempt); lastErr == nil { return nil } } } func (cs *clientStream) Context() context.Context { cs.commitAttempt() // No need to lock before using attempt, since we know it is committed and // cannot change. if cs.attempt.transportStream != nil { return cs.attempt.transportStream.Context() } return cs.ctx } func (cs *clientStream) withRetry(op func(a *csAttempt) error, onSuccess func()) error { cs.mu.Lock() for { if cs.committed { cs.mu.Unlock() // toRPCErr is used in case the error from the attempt comes from // NewClientStream, which intentionally doesn't return a status // error to allow for further inspection; all other errors should // already be status errors. return toRPCErr(op(cs.attempt)) } if len(cs.replayBuffer) == 0 { // For the first op, which controls creation of the stream and // assigns cs.attempt, we need to create a new attempt inline // before executing the first op. On subsequent ops, the attempt // is created immediately before replaying the ops. var err error if cs.attempt, err = cs.newAttemptLocked(false /* isTransparent */); err != nil { cs.mu.Unlock() cs.finish(err) return err } } a := cs.attempt cs.mu.Unlock() err := op(a) cs.mu.Lock() if a != cs.attempt { // We started another attempt already. continue } if err == io.EOF { <-a.transportStream.Done() } if err == nil || (err == io.EOF && a.transportStream.Status().Code() == codes.OK) { onSuccess() cs.mu.Unlock() return err } if err := cs.retryLocked(a, err); err != nil { cs.mu.Unlock() return err } } } func (cs *clientStream) Header() (metadata.MD, error) { var m metadata.MD err := cs.withRetry(func(a *csAttempt) error { var err error m, err = a.transportStream.Header() return toRPCErr(err) }, cs.commitAttemptLocked) if m == nil && err == nil { // The stream ended with success. Finish the clientStream. err = io.EOF } if err != nil { cs.finish(err) // Do not return the error. The user should get it by calling Recv(). return nil, nil } if len(cs.binlogs) != 0 && !cs.serverHeaderBinlogged && m != nil { // Only log if binary log is on and header has not been logged, and // there is actually headers to log. logEntry := &binarylog.ServerHeader{ OnClientSide: true, Header: m, PeerAddr: nil, } if peer, ok := peer.FromContext(cs.Context()); ok { logEntry.PeerAddr = peer.Addr } cs.serverHeaderBinlogged = true for _, binlog := range cs.binlogs { binlog.Log(cs.ctx, logEntry) } } return m, nil } func (cs *clientStream) Trailer() metadata.MD { // On RPC failure, we never need to retry, because usage requires that // RecvMsg() returned a non-nil error before calling this function is valid. // We would have retried earlier if necessary. // // Commit the attempt anyway, just in case users are not following those // directions -- it will prevent races and should not meaningfully impact // performance. cs.commitAttempt() if cs.attempt.transportStream == nil { return nil } return cs.attempt.transportStream.Trailer() } func (cs *clientStream) replayBufferLocked(attempt *csAttempt) error { for _, f := range cs.replayBuffer { if err := f.op(attempt); err != nil { return err } } return nil } func (cs *clientStream) bufferForRetryLocked(sz int, op func(a *csAttempt) error, cleanup func()) { // Note: we still will buffer if retry is disabled (for transparent retries). if cs.committed { return } cs.replayBufferSize += sz if cs.replayBufferSize > cs.callInfo.maxRetryRPCBufferSize { cs.commitAttemptLocked() cleanup() return } cs.replayBuffer = append(cs.replayBuffer, replayOp{op: op, cleanup: cleanup}) } func (cs *clientStream) SendMsg(m any) (err error) { defer func() { if err != nil && err != io.EOF { // Call finish on the client stream for errors generated by this SendMsg // call, as these indicate problems created by this client. (Transport // errors are converted to an io.EOF error in csAttempt.sendMsg; the real // error will be returned from RecvMsg eventually in that case, or be // retried.) cs.finish(err) } }() if cs.sentLast { return status.Errorf(codes.Internal, "SendMsg called after CloseSend") } if !cs.desc.ClientStreams { cs.sentLast = true } // load hdr, payload, data hdr, data, payload, pf, err := prepareMsg(m, cs.codec, cs.compressorV0, cs.compressorV1, cs.cc.dopts.copts.BufferPool) if err != nil { return err } defer func() { data.Free() // only free payload if compression was made, and therefore it is a different set // of buffers from data. if pf.isCompressed() { payload.Free() } }() dataLen := data.Len() payloadLen := payload.Len() // TODO(dfawley): should we be checking len(data) instead? if payloadLen > *cs.callInfo.maxSendMessageSize { return status.Errorf(codes.ResourceExhausted, "trying to send message larger than max (%d vs. %d)", payloadLen, *cs.callInfo.maxSendMessageSize) } // always take an extra ref in case data == payload (i.e. when the data isn't // compressed). The original ref will always be freed by the deferred free above. payload.Ref() op := func(a *csAttempt) error { return a.sendMsg(m, hdr, payload, dataLen, payloadLen) } // onSuccess is invoked when the op is captured for a subsequent retry. If the // stream was established by a previous message and therefore retries are // disabled, onSuccess will not be invoked, and payloadRef can be freed // immediately. onSuccessCalled := false err = cs.withRetry(op, func() { cs.bufferForRetryLocked(len(hdr)+payloadLen, op, payload.Free) onSuccessCalled = true }) if !onSuccessCalled { payload.Free() } if len(cs.binlogs) != 0 && err == nil { cm := &binarylog.ClientMessage{ OnClientSide: true, Message: data.Materialize(), } for _, binlog := range cs.binlogs { binlog.Log(cs.ctx, cm) } } return err } func (cs *clientStream) RecvMsg(m any) error { if len(cs.binlogs) != 0 && !cs.serverHeaderBinlogged { // Call Header() to binary log header if it's not already logged. cs.Header() } var recvInfo *payloadInfo if len(cs.binlogs) != 0 { recvInfo = &payloadInfo{} defer recvInfo.free() } err := cs.withRetry(func(a *csAttempt) error { return a.recvMsg(m, recvInfo) }, cs.commitAttemptLocked) if len(cs.binlogs) != 0 && err == nil { sm := &binarylog.ServerMessage{ OnClientSide: true, Message: recvInfo.uncompressedBytes.Materialize(), } for _, binlog := range cs.binlogs { binlog.Log(cs.ctx, sm) } } if err != nil || !cs.desc.ServerStreams { // err != nil or non-server-streaming indicates end of stream. cs.finish(err) } return err } func (cs *clientStream) CloseSend() error { if cs.sentLast { // TODO: return an error and finish the stream instead, due to API misuse? return nil } cs.sentLast = true op := func(a *csAttempt) error { a.transportStream.Write(nil, nil, &transport.WriteOptions{Last: true}) // Always return nil; io.EOF is the only error that might make sense
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace_withtrace.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace_withtrace.go
//go:build !grpcnotrace /* * * Copyright 2024 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" t "golang.org/x/net/trace" ) func newTrace(family, title string) traceLog { return t.New(family, title) } func newTraceContext(ctx context.Context, tr traceLog) context.Context { return t.NewContext(ctx, tr) } func newTraceEventLog(family, title string) traceEventLog { return t.NewEventLog(family, title) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/backoff.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/backoff.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // See internal/backoff package for the backoff implementation. This file is // kept for the exported types and API backward compatibility. package grpc import ( "time" "google.golang.org/grpc/backoff" ) // DefaultBackoffConfig uses values specified for backoff in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. // // Deprecated: use ConnectParams instead. Will be supported throughout 1.x. var DefaultBackoffConfig = BackoffConfig{ MaxDelay: 120 * time.Second, } // BackoffConfig defines the parameters for the default gRPC backoff strategy. // // Deprecated: use ConnectParams instead. Will be supported throughout 1.x. type BackoffConfig struct { // MaxDelay is the upper bound of backoff delay. MaxDelay time.Duration } // ConnectParams defines the parameters for connecting and retrying. Users are // encouraged to use this instead of the BackoffConfig type defined above. See // here for more details: // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type ConnectParams struct { // Backoff specifies the configuration options for connection backoff. Backoff backoff.Config // MinConnectTimeout is the minimum amount of time we are willing to give a // connection to complete. MinConnectTimeout time.Duration }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/interceptor.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/interceptor.go
/* * * Copyright 2016 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" ) // UnaryInvoker is called by UnaryClientInterceptor to complete RPCs. type UnaryInvoker func(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error // UnaryClientInterceptor intercepts the execution of a unary RPC on the client. // Unary interceptors can be specified as a DialOption, using // WithUnaryInterceptor() or WithChainUnaryInterceptor(), when creating a // ClientConn. When a unary interceptor(s) is set on a ClientConn, gRPC // delegates all unary RPC invocations to the interceptor, and it is the // responsibility of the interceptor to call invoker to complete the processing // of the RPC. // // method is the RPC name. req and reply are the corresponding request and // response messages. cc is the ClientConn on which the RPC was invoked. invoker // is the handler to complete the RPC and it is the responsibility of the // interceptor to call it. opts contain all applicable call options, including // defaults from the ClientConn as well as per-call options. // // The returned error must be compatible with the status package. type UnaryClientInterceptor func(ctx context.Context, method string, req, reply any, cc *ClientConn, invoker UnaryInvoker, opts ...CallOption) error // Streamer is called by StreamClientInterceptor to create a ClientStream. type Streamer func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, opts ...CallOption) (ClientStream, error) // StreamClientInterceptor intercepts the creation of a ClientStream. Stream // interceptors can be specified as a DialOption, using WithStreamInterceptor() // or WithChainStreamInterceptor(), when creating a ClientConn. When a stream // interceptor(s) is set on the ClientConn, gRPC delegates all stream creations // to the interceptor, and it is the responsibility of the interceptor to call // streamer. // // desc contains a description of the stream. cc is the ClientConn on which the // RPC was invoked. streamer is the handler to create a ClientStream and it is // the responsibility of the interceptor to call it. opts contain all applicable // call options, including defaults from the ClientConn as well as per-call // options. // // StreamClientInterceptor may return a custom ClientStream to intercept all I/O // operations. The returned error must be compatible with the status package. type StreamClientInterceptor func(ctx context.Context, desc *StreamDesc, cc *ClientConn, method string, streamer Streamer, opts ...CallOption) (ClientStream, error) // UnaryServerInfo consists of various information about a unary RPC on // server side. All per-rpc information may be mutated by the interceptor. type UnaryServerInfo struct { // Server is the service implementation the user provides. This is read-only. Server any // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string } // UnaryHandler defines the handler invoked by UnaryServerInterceptor to complete the normal // execution of a unary RPC. // // If a UnaryHandler returns an error, it should either be produced by the // status package, or be one of the context errors. Otherwise, gRPC will use // codes.Unknown as the status code and err.Error() as the status message of the // RPC. type UnaryHandler func(ctx context.Context, req any) (any, error) // UnaryServerInterceptor provides a hook to intercept the execution of a unary RPC on the server. info // contains all the information of this RPC the interceptor can operate on. And handler is the wrapper // of the service method implementation. It is the responsibility of the interceptor to invoke handler // to complete the RPC. type UnaryServerInterceptor func(ctx context.Context, req any, info *UnaryServerInfo, handler UnaryHandler) (resp any, err error) // StreamServerInfo consists of various information about a streaming RPC on // server side. All per-rpc information may be mutated by the interceptor. type StreamServerInfo struct { // FullMethod is the full RPC method string, i.e., /package.service/method. FullMethod string // IsClientStream indicates whether the RPC is a client streaming RPC. IsClientStream bool // IsServerStream indicates whether the RPC is a server streaming RPC. IsServerStream bool } // StreamServerInterceptor provides a hook to intercept the execution of a streaming RPC on the server. // info contains all the information of this RPC the interceptor can operate on. And handler is the // service method implementation. It is the responsibility of the interceptor to invoke handler to // complete the RPC. type StreamServerInterceptor func(srv any, ss ServerStream, info *StreamServerInfo, handler StreamHandler) error
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace.go
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "bytes" "fmt" "io" "net" "strings" "sync" "time" ) // EnableTracing controls whether to trace RPCs using the golang.org/x/net/trace package. // This should only be set before any RPCs are sent or received by this program. var EnableTracing bool // methodFamily returns the trace family for the given method. // It turns "/pkg.Service/GetFoo" into "pkg.Service". func methodFamily(m string) string { m = strings.TrimPrefix(m, "/") // remove leading slash if i := strings.Index(m, "/"); i >= 0 { m = m[:i] // remove everything from second slash } return m } // traceEventLog mirrors golang.org/x/net/trace.EventLog. // // It exists in order to avoid importing x/net/trace on grpcnotrace builds. type traceEventLog interface { Printf(format string, a ...any) Errorf(format string, a ...any) Finish() } // traceLog mirrors golang.org/x/net/trace.Trace. // // It exists in order to avoid importing x/net/trace on grpcnotrace builds. type traceLog interface { LazyLog(x fmt.Stringer, sensitive bool) LazyPrintf(format string, a ...any) SetError() SetRecycler(f func(any)) SetTraceInfo(traceID, spanID uint64) SetMaxEvents(m int) Finish() } // traceInfo contains tracing information for an RPC. type traceInfo struct { tr traceLog firstLine firstLine } // firstLine is the first line of an RPC trace. // It may be mutated after construction; remoteAddr specifically may change // during client-side use. type firstLine struct { mu sync.Mutex client bool // whether this is a client (outgoing) RPC remoteAddr net.Addr deadline time.Duration // may be zero } func (f *firstLine) SetRemoteAddr(addr net.Addr) { f.mu.Lock() f.remoteAddr = addr f.mu.Unlock() } func (f *firstLine) String() string { f.mu.Lock() defer f.mu.Unlock() var line bytes.Buffer io.WriteString(&line, "RPC: ") if f.client { io.WriteString(&line, "to") } else { io.WriteString(&line, "from") } fmt.Fprintf(&line, " %v deadline:", f.remoteAddr) if f.deadline != 0 { fmt.Fprint(&line, f.deadline) } else { io.WriteString(&line, "none") } return line.String() } const truncateSize = 100 func truncate(x string, l int) string { if l > len(x) { return x } return x[:l] } // payload represents an RPC request or response payload. type payload struct { sent bool // whether this is an outgoing payload msg any // e.g. a proto.Message // TODO(dsymonds): add stringifying info to codec, and limit how much we hold here? } func (p payload) String() string { if p.sent { return truncate(fmt.Sprintf("sent: %v", p.msg), truncateSize) } return truncate(fmt.Sprintf("recv: %v", p.msg), truncateSize) } type fmtStringer struct { format string a []any } func (f *fmtStringer) String() string { return fmt.Sprintf(f.format, f.a...) } type stringer string func (s stringer) String() string { return string(s) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stream_interfaces.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/stream_interfaces.go
/* * * Copyright 2024 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc // ServerStreamingClient represents the client side of a server-streaming (one // request, many responses) RPC. It is generic over the type of the response // message. It is used in generated code. type ServerStreamingClient[Res any] interface { // Recv receives the next response message from the server. The client may // repeatedly call Recv to read messages from the response stream. If // io.EOF is returned, the stream has terminated with an OK status. Any // other error is compatible with the status package and indicates the // RPC's status code and message. Recv() (*Res, error) // ClientStream is embedded to provide Context, Header, and Trailer // functionality. No other methods in the ClientStream should be called // directly. ClientStream } // ServerStreamingServer represents the server side of a server-streaming (one // request, many responses) RPC. It is generic over the type of the response // message. It is used in generated code. // // To terminate the response stream, return from the handler method and return // an error from the status package, or use nil to indicate an OK status code. type ServerStreamingServer[Res any] interface { // Send sends a response message to the client. The server handler may // call Send multiple times to send multiple messages to the client. An // error is returned if the stream was terminated unexpectedly, and the // handler method should return, as the stream is no longer usable. Send(*Res) error // ServerStream is embedded to provide Context, SetHeader, SendHeader, and // SetTrailer functionality. No other methods in the ServerStream should // be called directly. ServerStream } // ClientStreamingClient represents the client side of a client-streaming (many // requests, one response) RPC. It is generic over both the type of the request // message stream and the type of the unary response message. It is used in // generated code. type ClientStreamingClient[Req any, Res any] interface { // Send sends a request message to the server. The client may call Send // multiple times to send multiple messages to the server. On error, Send // aborts the stream. If the error was generated by the client, the status // is returned directly. Otherwise, io.EOF is returned, and the status of // the stream may be discovered using CloseAndRecv(). Send(*Req) error // CloseAndRecv closes the request stream and waits for the server's // response. This method must be called once and only once after sending // all request messages. Any error returned is implemented by the status // package. CloseAndRecv() (*Res, error) // ClientStream is embedded to provide Context, Header, and Trailer // functionality. No other methods in the ClientStream should be called // directly. ClientStream } // ClientStreamingServer represents the server side of a client-streaming (many // requests, one response) RPC. It is generic over both the type of the request // message stream and the type of the unary response message. It is used in // generated code. // // To terminate the RPC, call SendAndClose and return nil from the method // handler or do not call SendAndClose and return an error from the status // package. type ClientStreamingServer[Req any, Res any] interface { // Recv receives the next request message from the client. The server may // repeatedly call Recv to read messages from the request stream. If // io.EOF is returned, it indicates the client called CloseAndRecv on its // ClientStreamingClient. Any other error indicates the stream was // terminated unexpectedly, and the handler method should return, as the // stream is no longer usable. Recv() (*Req, error) // SendAndClose sends a single response message to the client and closes // the stream. This method must be called once and only once after all // request messages have been processed. Recv should not be called after // calling SendAndClose. SendAndClose(*Res) error // ServerStream is embedded to provide Context, SetHeader, SendHeader, and // SetTrailer functionality. No other methods in the ServerStream should // be called directly. ServerStream } // BidiStreamingClient represents the client side of a bidirectional-streaming // (many requests, many responses) RPC. It is generic over both the type of the // request message stream and the type of the response message stream. It is // used in generated code. type BidiStreamingClient[Req any, Res any] interface { // Send sends a request message to the server. The client may call Send // multiple times to send multiple messages to the server. On error, Send // aborts the stream. If the error was generated by the client, the status // is returned directly. Otherwise, io.EOF is returned, and the status of // the stream may be discovered using Recv(). Send(*Req) error // Recv receives the next response message from the server. The client may // repeatedly call Recv to read messages from the response stream. If // io.EOF is returned, the stream has terminated with an OK status. Any // other error is compatible with the status package and indicates the // RPC's status code and message. Recv() (*Res, error) // ClientStream is embedded to provide Context, Header, Trailer, and // CloseSend functionality. No other methods in the ClientStream should be // called directly. ClientStream } // BidiStreamingServer represents the server side of a bidirectional-streaming // (many requests, many responses) RPC. It is generic over both the type of the // request message stream and the type of the response message stream. It is // used in generated code. // // To terminate the stream, return from the handler method and return // an error from the status package, or use nil to indicate an OK status code. type BidiStreamingServer[Req any, Res any] interface { // Recv receives the next request message from the client. The server may // repeatedly call Recv to read messages from the request stream. If // io.EOF is returned, it indicates the client called CloseSend on its // BidiStreamingClient. Any other error indicates the stream was // terminated unexpectedly, and the handler method should return, as the // stream is no longer usable. Recv() (*Req, error) // Send sends a response message to the client. The server handler may // call Send multiple times to send multiple messages to the client. An // error is returned if the stream was terminated unexpectedly, and the // handler method should return, as the stream is no longer usable. Send(*Res) error // ServerStream is embedded to provide Context, SetHeader, SendHeader, and // SetTrailer functionality. No other methods in the ServerStream should // be called directly. ServerStream } // GenericClientStream implements the ServerStreamingClient, ClientStreamingClient, // and BidiStreamingClient interfaces. It is used in generated code. type GenericClientStream[Req any, Res any] struct { ClientStream } var _ ServerStreamingClient[string] = (*GenericClientStream[int, string])(nil) var _ ClientStreamingClient[int, string] = (*GenericClientStream[int, string])(nil) var _ BidiStreamingClient[int, string] = (*GenericClientStream[int, string])(nil) // Send pushes one message into the stream of requests to be consumed by the // server. The type of message which can be sent is determined by the Req type // parameter of the GenericClientStream receiver. func (x *GenericClientStream[Req, Res]) Send(m *Req) error { return x.ClientStream.SendMsg(m) } // Recv reads one message from the stream of responses generated by the server. // The type of the message returned is determined by the Res type parameter // of the GenericClientStream receiver. func (x *GenericClientStream[Req, Res]) Recv() (*Res, error) { m := new(Res) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // CloseAndRecv closes the sending side of the stream, then receives the unary // response from the server. The type of message which it returns is determined // by the Res type parameter of the GenericClientStream receiver. func (x *GenericClientStream[Req, Res]) CloseAndRecv() (*Res, error) { if err := x.ClientStream.CloseSend(); err != nil { return nil, err } m := new(Res) if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err } return m, nil } // GenericServerStream implements the ServerStreamingServer, ClientStreamingServer, // and BidiStreamingServer interfaces. It is used in generated code. type GenericServerStream[Req any, Res any] struct { ServerStream } var _ ServerStreamingServer[string] = (*GenericServerStream[int, string])(nil) var _ ClientStreamingServer[int, string] = (*GenericServerStream[int, string])(nil) var _ BidiStreamingServer[int, string] = (*GenericServerStream[int, string])(nil) // Send pushes one message into the stream of responses to be consumed by the // client. The type of message which can be sent is determined by the Res // type parameter of the serverStreamServer receiver. func (x *GenericServerStream[Req, Res]) Send(m *Res) error { return x.ServerStream.SendMsg(m) } // SendAndClose pushes the unary response to the client. The type of message // which can be sent is determined by the Res type parameter of the // clientStreamServer receiver. func (x *GenericServerStream[Req, Res]) SendAndClose(m *Res) error { return x.ServerStream.SendMsg(m) } // Recv reads one message from the stream of requests generated by the client. // The type of the message returned is determined by the Req type parameter // of the clientStreamServer receiver. func (x *GenericServerStream[Req, Res]) Recv() (*Req, error) { m := new(Req) if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err } return m, nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/rpc_util.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/rpc_util.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "compress/gzip" "context" "encoding/binary" "fmt" "io" "math" "strings" "sync" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding/proto" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // Compressor defines the interface gRPC uses to compress a message. // // Deprecated: use package encoding. type Compressor interface { // Do compresses p into w. Do(w io.Writer, p []byte) error // Type returns the compression algorithm the Compressor uses. Type() string } type gzipCompressor struct { pool sync.Pool } // NewGZIPCompressor creates a Compressor based on GZIP. // // Deprecated: use package encoding/gzip. func NewGZIPCompressor() Compressor { c, _ := NewGZIPCompressorWithLevel(gzip.DefaultCompression) return c } // NewGZIPCompressorWithLevel is like NewGZIPCompressor but specifies the gzip compression level instead // of assuming DefaultCompression. // // The error returned will be nil if the level is valid. // // Deprecated: use package encoding/gzip. func NewGZIPCompressorWithLevel(level int) (Compressor, error) { if level < gzip.DefaultCompression || level > gzip.BestCompression { return nil, fmt.Errorf("grpc: invalid compression level: %d", level) } return &gzipCompressor{ pool: sync.Pool{ New: func() any { w, err := gzip.NewWriterLevel(io.Discard, level) if err != nil { panic(err) } return w }, }, }, nil } func (c *gzipCompressor) Do(w io.Writer, p []byte) error { z := c.pool.Get().(*gzip.Writer) defer c.pool.Put(z) z.Reset(w) if _, err := z.Write(p); err != nil { return err } return z.Close() } func (c *gzipCompressor) Type() string { return "gzip" } // Decompressor defines the interface gRPC uses to decompress a message. // // Deprecated: use package encoding. type Decompressor interface { // Do reads the data from r and uncompress them. Do(r io.Reader) ([]byte, error) // Type returns the compression algorithm the Decompressor uses. Type() string } type gzipDecompressor struct { pool sync.Pool } // NewGZIPDecompressor creates a Decompressor based on GZIP. // // Deprecated: use package encoding/gzip. func NewGZIPDecompressor() Decompressor { return &gzipDecompressor{} } func (d *gzipDecompressor) Do(r io.Reader) ([]byte, error) { var z *gzip.Reader switch maybeZ := d.pool.Get().(type) { case nil: newZ, err := gzip.NewReader(r) if err != nil { return nil, err } z = newZ case *gzip.Reader: z = maybeZ if err := z.Reset(r); err != nil { d.pool.Put(z) return nil, err } } defer func() { z.Close() d.pool.Put(z) }() return io.ReadAll(z) } func (d *gzipDecompressor) Type() string { return "gzip" } // callInfo contains all related configuration and information about an RPC. type callInfo struct { compressorName string failFast bool maxReceiveMessageSize *int maxSendMessageSize *int creds credentials.PerRPCCredentials contentSubtype string codec baseCodec maxRetryRPCBufferSize int onFinish []func(err error) } func defaultCallInfo() *callInfo { return &callInfo{ failFast: true, maxRetryRPCBufferSize: 256 * 1024, // 256KB } } // CallOption configures a Call before it starts or extracts information from // a Call after it completes. type CallOption interface { // before is called before the call is sent to any server. If before // returns a non-nil error, the RPC fails with that error. before(*callInfo) error // after is called after the call has completed. after cannot return an // error, so any failures should be reported via output parameters. after(*callInfo, *csAttempt) } // EmptyCallOption does not alter the Call configuration. // It can be embedded in another structure to carry satellite data for use // by interceptors. type EmptyCallOption struct{} func (EmptyCallOption) before(*callInfo) error { return nil } func (EmptyCallOption) after(*callInfo, *csAttempt) {} // StaticMethod returns a CallOption which specifies that a call is being made // to a method that is static, which means the method is known at compile time // and doesn't change at runtime. This can be used as a signal to stats plugins // that this method is safe to include as a key to a measurement. func StaticMethod() CallOption { return StaticMethodCallOption{} } // StaticMethodCallOption is a CallOption that specifies that a call comes // from a static method. type StaticMethodCallOption struct { EmptyCallOption } // Header returns a CallOptions that retrieves the header metadata // for a unary RPC. func Header(md *metadata.MD) CallOption { return HeaderCallOption{HeaderAddr: md} } // HeaderCallOption is a CallOption for collecting response header metadata. // The metadata field will be populated *after* the RPC completes. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type HeaderCallOption struct { HeaderAddr *metadata.MD } func (o HeaderCallOption) before(*callInfo) error { return nil } func (o HeaderCallOption) after(_ *callInfo, attempt *csAttempt) { *o.HeaderAddr, _ = attempt.transportStream.Header() } // Trailer returns a CallOptions that retrieves the trailer metadata // for a unary RPC. func Trailer(md *metadata.MD) CallOption { return TrailerCallOption{TrailerAddr: md} } // TrailerCallOption is a CallOption for collecting response trailer metadata. // The metadata field will be populated *after* the RPC completes. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type TrailerCallOption struct { TrailerAddr *metadata.MD } func (o TrailerCallOption) before(*callInfo) error { return nil } func (o TrailerCallOption) after(_ *callInfo, attempt *csAttempt) { *o.TrailerAddr = attempt.transportStream.Trailer() } // Peer returns a CallOption that retrieves peer information for a unary RPC. // The peer field will be populated *after* the RPC completes. func Peer(p *peer.Peer) CallOption { return PeerCallOption{PeerAddr: p} } // PeerCallOption is a CallOption for collecting the identity of the remote // peer. The peer field will be populated *after* the RPC completes. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type PeerCallOption struct { PeerAddr *peer.Peer } func (o PeerCallOption) before(*callInfo) error { return nil } func (o PeerCallOption) after(_ *callInfo, attempt *csAttempt) { if x, ok := peer.FromContext(attempt.transportStream.Context()); ok { *o.PeerAddr = *x } } // WaitForReady configures the RPC's behavior when the client is in // TRANSIENT_FAILURE, which occurs when all addresses fail to connect. If // waitForReady is false, the RPC will fail immediately. Otherwise, the client // will wait until a connection becomes available or the RPC's deadline is // reached. // // By default, RPCs do not "wait for ready". func WaitForReady(waitForReady bool) CallOption { return FailFastCallOption{FailFast: !waitForReady} } // FailFast is the opposite of WaitForReady. // // Deprecated: use WaitForReady. func FailFast(failFast bool) CallOption { return FailFastCallOption{FailFast: failFast} } // FailFastCallOption is a CallOption for indicating whether an RPC should fail // fast or not. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type FailFastCallOption struct { FailFast bool } func (o FailFastCallOption) before(c *callInfo) error { c.failFast = o.FailFast return nil } func (o FailFastCallOption) after(*callInfo, *csAttempt) {} // OnFinish returns a CallOption that configures a callback to be called when // the call completes. The error passed to the callback is the status of the // RPC, and may be nil. The onFinish callback provided will only be called once // by gRPC. This is mainly used to be used by streaming interceptors, to be // notified when the RPC completes along with information about the status of // the RPC. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func OnFinish(onFinish func(err error)) CallOption { return OnFinishCallOption{ OnFinish: onFinish, } } // OnFinishCallOption is CallOption that indicates a callback to be called when // the call completes. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type OnFinishCallOption struct { OnFinish func(error) } func (o OnFinishCallOption) before(c *callInfo) error { c.onFinish = append(c.onFinish, o.OnFinish) return nil } func (o OnFinishCallOption) after(*callInfo, *csAttempt) {} // MaxCallRecvMsgSize returns a CallOption which sets the maximum message size // in bytes the client can receive. If this is not set, gRPC uses the default // 4MB. func MaxCallRecvMsgSize(bytes int) CallOption { return MaxRecvMsgSizeCallOption{MaxRecvMsgSize: bytes} } // MaxRecvMsgSizeCallOption is a CallOption that indicates the maximum message // size in bytes the client can receive. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type MaxRecvMsgSizeCallOption struct { MaxRecvMsgSize int } func (o MaxRecvMsgSizeCallOption) before(c *callInfo) error { c.maxReceiveMessageSize = &o.MaxRecvMsgSize return nil } func (o MaxRecvMsgSizeCallOption) after(*callInfo, *csAttempt) {} // MaxCallSendMsgSize returns a CallOption which sets the maximum message size // in bytes the client can send. If this is not set, gRPC uses the default // `math.MaxInt32`. func MaxCallSendMsgSize(bytes int) CallOption { return MaxSendMsgSizeCallOption{MaxSendMsgSize: bytes} } // MaxSendMsgSizeCallOption is a CallOption that indicates the maximum message // size in bytes the client can send. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type MaxSendMsgSizeCallOption struct { MaxSendMsgSize int } func (o MaxSendMsgSizeCallOption) before(c *callInfo) error { c.maxSendMessageSize = &o.MaxSendMsgSize return nil } func (o MaxSendMsgSizeCallOption) after(*callInfo, *csAttempt) {} // PerRPCCredentials returns a CallOption that sets credentials.PerRPCCredentials // for a call. func PerRPCCredentials(creds credentials.PerRPCCredentials) CallOption { return PerRPCCredsCallOption{Creds: creds} } // PerRPCCredsCallOption is a CallOption that indicates the per-RPC // credentials to use for the call. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type PerRPCCredsCallOption struct { Creds credentials.PerRPCCredentials } func (o PerRPCCredsCallOption) before(c *callInfo) error { c.creds = o.Creds return nil } func (o PerRPCCredsCallOption) after(*callInfo, *csAttempt) {} // UseCompressor returns a CallOption which sets the compressor used when // sending the request. If WithCompressor is also set, UseCompressor has // higher priority. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func UseCompressor(name string) CallOption { return CompressorCallOption{CompressorType: name} } // CompressorCallOption is a CallOption that indicates the compressor to use. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type CompressorCallOption struct { CompressorType string } func (o CompressorCallOption) before(c *callInfo) error { c.compressorName = o.CompressorType return nil } func (o CompressorCallOption) after(*callInfo, *csAttempt) {} // CallContentSubtype returns a CallOption that will set the content-subtype // for a call. For example, if content-subtype is "json", the Content-Type over // the wire will be "application/grpc+json". The content-subtype is converted // to lowercase before being included in Content-Type. See Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. // // If ForceCodec is not also used, the content-subtype will be used to look up // the Codec to use in the registry controlled by RegisterCodec. See the // documentation on RegisterCodec for details on registration. The lookup of // content-subtype is case-insensitive. If no such Codec is found, the call // will result in an error with code codes.Internal. // // If ForceCodec is also used, that Codec will be used for all request and // response messages, with the content-subtype set to the given contentSubtype // here for requests. func CallContentSubtype(contentSubtype string) CallOption { return ContentSubtypeCallOption{ContentSubtype: strings.ToLower(contentSubtype)} } // ContentSubtypeCallOption is a CallOption that indicates the content-subtype // used for marshaling messages. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type ContentSubtypeCallOption struct { ContentSubtype string } func (o ContentSubtypeCallOption) before(c *callInfo) error { c.contentSubtype = o.ContentSubtype return nil } func (o ContentSubtypeCallOption) after(*callInfo, *csAttempt) {} // ForceCodec returns a CallOption that will set codec to be used for all // request and response messages for a call. The result of calling Name() will // be used as the content-subtype after converting to lowercase, unless // CallContentSubtype is also used. // // See Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. Also see the documentation on RegisterCodec and // CallContentSubtype for more details on the interaction between Codec and // content-subtype. // // This function is provided for advanced users; prefer to use only // CallContentSubtype to select a registered codec instead. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func ForceCodec(codec encoding.Codec) CallOption { return ForceCodecCallOption{Codec: codec} } // ForceCodecCallOption is a CallOption that indicates the codec used for // marshaling messages. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type ForceCodecCallOption struct { Codec encoding.Codec } func (o ForceCodecCallOption) before(c *callInfo) error { c.codec = newCodecV1Bridge(o.Codec) return nil } func (o ForceCodecCallOption) after(*callInfo, *csAttempt) {} // ForceCodecV2 returns a CallOption that will set codec to be used for all // request and response messages for a call. The result of calling Name() will // be used as the content-subtype after converting to lowercase, unless // CallContentSubtype is also used. // // See Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. Also see the documentation on RegisterCodec and // CallContentSubtype for more details on the interaction between Codec and // content-subtype. // // This function is provided for advanced users; prefer to use only // CallContentSubtype to select a registered codec instead. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func ForceCodecV2(codec encoding.CodecV2) CallOption { return ForceCodecV2CallOption{CodecV2: codec} } // ForceCodecV2CallOption is a CallOption that indicates the codec used for // marshaling messages. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type ForceCodecV2CallOption struct { CodecV2 encoding.CodecV2 } func (o ForceCodecV2CallOption) before(c *callInfo) error { c.codec = o.CodecV2 return nil } func (o ForceCodecV2CallOption) after(*callInfo, *csAttempt) {} // CallCustomCodec behaves like ForceCodec, but accepts a grpc.Codec instead of // an encoding.Codec. // // Deprecated: use ForceCodec instead. func CallCustomCodec(codec Codec) CallOption { return CustomCodecCallOption{Codec: codec} } // CustomCodecCallOption is a CallOption that indicates the codec used for // marshaling messages. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type CustomCodecCallOption struct { Codec Codec } func (o CustomCodecCallOption) before(c *callInfo) error { c.codec = newCodecV0Bridge(o.Codec) return nil } func (o CustomCodecCallOption) after(*callInfo, *csAttempt) {} // MaxRetryRPCBufferSize returns a CallOption that limits the amount of memory // used for buffering this RPC's requests for retry purposes. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func MaxRetryRPCBufferSize(bytes int) CallOption { return MaxRetryRPCBufferSizeCallOption{bytes} } // MaxRetryRPCBufferSizeCallOption is a CallOption indicating the amount of // memory to be used for caching this RPC for retry purposes. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type MaxRetryRPCBufferSizeCallOption struct { MaxRetryRPCBufferSize int } func (o MaxRetryRPCBufferSizeCallOption) before(c *callInfo) error { c.maxRetryRPCBufferSize = o.MaxRetryRPCBufferSize return nil } func (o MaxRetryRPCBufferSizeCallOption) after(*callInfo, *csAttempt) {} // The format of the payload: compressed or not? type payloadFormat uint8 const ( compressionNone payloadFormat = 0 // no compression compressionMade payloadFormat = 1 // compressed ) func (pf payloadFormat) isCompressed() bool { return pf == compressionMade } type streamReader interface { ReadMessageHeader(header []byte) error Read(n int) (mem.BufferSlice, error) } // parser reads complete gRPC messages from the underlying reader. type parser struct { // r is the underlying reader. // See the comment on recvMsg for the permissible // error types. r streamReader // The header of a gRPC message. Find more detail at // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md header [5]byte // bufferPool is the pool of shared receive buffers. bufferPool mem.BufferPool } // recvMsg reads a complete gRPC message from the stream. // // It returns the message and its payload (compression/encoding) // format. The caller owns the returned msg memory. // // If there is an error, possible values are: // - io.EOF, when no messages remain // - io.ErrUnexpectedEOF // - of type transport.ConnectionError // - an error from the status package // // No other error values or types must be returned, which also means // that the underlying streamReader must not return an incompatible // error. func (p *parser) recvMsg(maxReceiveMessageSize int) (payloadFormat, mem.BufferSlice, error) { err := p.r.ReadMessageHeader(p.header[:]) if err != nil { return 0, nil, err } pf := payloadFormat(p.header[0]) length := binary.BigEndian.Uint32(p.header[1:]) if int64(length) > int64(maxInt) { return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max length allowed on current machine (%d vs. %d)", length, maxInt) } if int(length) > maxReceiveMessageSize { return 0, nil, status.Errorf(codes.ResourceExhausted, "grpc: received message larger than max (%d vs. %d)", length, maxReceiveMessageSize) } data, err := p.r.Read(int(length)) if err != nil { if err == io.EOF { err = io.ErrUnexpectedEOF } return 0, nil, err } return pf, data, nil } // encode serializes msg and returns a buffer containing the message, or an // error if it is too large to be transmitted by grpc. If msg is nil, it // generates an empty message. func encode(c baseCodec, msg any) (mem.BufferSlice, error) { if msg == nil { // NOTE: typed nils will not be caught by this check return nil, nil } b, err := c.Marshal(msg) if err != nil { return nil, status.Errorf(codes.Internal, "grpc: error while marshaling: %v", err.Error()) } if bufSize := uint(b.Len()); bufSize > math.MaxUint32 { b.Free() return nil, status.Errorf(codes.ResourceExhausted, "grpc: message too large (%d bytes)", bufSize) } return b, nil } // compress returns the input bytes compressed by compressor or cp. // If both compressors are nil, or if the message has zero length, returns nil, // indicating no compression was done. // // TODO(dfawley): eliminate cp parameter by wrapping Compressor in an encoding.Compressor. func compress(in mem.BufferSlice, cp Compressor, compressor encoding.Compressor, pool mem.BufferPool) (mem.BufferSlice, payloadFormat, error) { if (compressor == nil && cp == nil) || in.Len() == 0 { return nil, compressionNone, nil } var out mem.BufferSlice w := mem.NewWriter(&out, pool) wrapErr := func(err error) error { out.Free() return status.Errorf(codes.Internal, "grpc: error while compressing: %v", err.Error()) } if compressor != nil { z, err := compressor.Compress(w) if err != nil { return nil, 0, wrapErr(err) } for _, b := range in { if _, err := z.Write(b.ReadOnlyData()); err != nil { return nil, 0, wrapErr(err) } } if err := z.Close(); err != nil { return nil, 0, wrapErr(err) } } else { // This is obviously really inefficient since it fully materializes the data, but // there is no way around this with the old Compressor API. At least it attempts // to return the buffer to the provider, in the hopes it can be reused (maybe // even by a subsequent call to this very function). buf := in.MaterializeToBuffer(pool) defer buf.Free() if err := cp.Do(w, buf.ReadOnlyData()); err != nil { return nil, 0, wrapErr(err) } } return out, compressionMade, nil } const ( payloadLen = 1 sizeLen = 4 headerLen = payloadLen + sizeLen ) // msgHeader returns a 5-byte header for the message being transmitted and the // payload, which is compData if non-nil or data otherwise. func msgHeader(data, compData mem.BufferSlice, pf payloadFormat) (hdr []byte, payload mem.BufferSlice) { hdr = make([]byte, headerLen) hdr[0] = byte(pf) var length uint32 if pf.isCompressed() { length = uint32(compData.Len()) payload = compData } else { length = uint32(data.Len()) payload = data } // Write length of payload into buf binary.BigEndian.PutUint32(hdr[payloadLen:], length) return hdr, payload } func outPayload(client bool, msg any, dataLength, payloadLength int, t time.Time) *stats.OutPayload { return &stats.OutPayload{ Client: client, Payload: msg, Length: dataLength, WireLength: payloadLength + headerLen, CompressedLength: payloadLength, SentTime: t, } } func checkRecvPayload(pf payloadFormat, recvCompress string, haveCompressor bool, isServer bool) *status.Status { switch pf { case compressionNone: case compressionMade: if recvCompress == "" || recvCompress == encoding.Identity { return status.New(codes.Internal, "grpc: compressed flag set with identity or empty encoding") } if !haveCompressor { if isServer { return status.Newf(codes.Unimplemented, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) } return status.Newf(codes.Internal, "grpc: Decompressor is not installed for grpc-encoding %q", recvCompress) } default: return status.Newf(codes.Internal, "grpc: received unexpected payload format %d", pf) } return nil } type payloadInfo struct { compressedLength int // The compressed length got from wire. uncompressedBytes mem.BufferSlice } func (p *payloadInfo) free() { if p != nil && p.uncompressedBytes != nil { p.uncompressedBytes.Free() } } // recvAndDecompress reads a message from the stream, decompressing it if necessary. // // Cancelling the returned cancel function releases the buffer back to the pool. So the caller should cancel as soon as // the buffer is no longer needed. // TODO: Refactor this function to reduce the number of arguments. // See: https://google.github.io/styleguide/go/best-practices.html#function-argument-lists func recvAndDecompress(p *parser, s recvCompressor, dc Decompressor, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool, ) (out mem.BufferSlice, err error) { pf, compressed, err := p.recvMsg(maxReceiveMessageSize) if err != nil { return nil, err } compressedLength := compressed.Len() if st := checkRecvPayload(pf, s.RecvCompress(), compressor != nil || dc != nil, isServer); st != nil { compressed.Free() return nil, st.Err() } if pf.isCompressed() { defer compressed.Free() // To match legacy behavior, if the decompressor is set by WithDecompressor or RPCDecompressor, // use this decompressor as the default. out, err = decompress(compressor, compressed, dc, maxReceiveMessageSize, p.bufferPool) if err != nil { return nil, err } } else { out = compressed } if payInfo != nil { payInfo.compressedLength = compressedLength out.Ref() payInfo.uncompressedBytes = out } return out, nil } // decompress processes the given data by decompressing it using either a custom decompressor or a standard compressor. // If a custom decompressor is provided, it takes precedence. The function validates that the decompressed data // does not exceed the specified maximum size and returns an error if this limit is exceeded. // On success, it returns the decompressed data. Otherwise, it returns an error if decompression fails or the data exceeds the size limit. func decompress(compressor encoding.Compressor, d mem.BufferSlice, dc Decompressor, maxReceiveMessageSize int, pool mem.BufferPool) (mem.BufferSlice, error) { if dc != nil { uncompressed, err := dc.Do(d.Reader()) if err != nil { return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the received message: %v", err) } if len(uncompressed) > maxReceiveMessageSize { return nil, status.Errorf(codes.ResourceExhausted, "grpc: message after decompression larger than max (%d vs. %d)", len(uncompressed), maxReceiveMessageSize) } return mem.BufferSlice{mem.SliceBuffer(uncompressed)}, nil } if compressor != nil { dcReader, err := compressor.Decompress(d.Reader()) if err != nil { return nil, status.Errorf(codes.Internal, "grpc: failed to decompress the message: %v", err) } out, err := mem.ReadAll(io.LimitReader(dcReader, int64(maxReceiveMessageSize)), pool) if err != nil { out.Free() return nil, status.Errorf(codes.Internal, "grpc: failed to read decompressed data: %v", err) } if out.Len() == maxReceiveMessageSize && !atEOF(dcReader) { out.Free() return nil, status.Errorf(codes.ResourceExhausted, "grpc: received message after decompression larger than max %d", maxReceiveMessageSize) } return out, nil } return nil, status.Errorf(codes.Internal, "grpc: no decompressor available for compressed payload") } // atEOF reads data from r and returns true if zero bytes could be read and r.Read returns EOF. func atEOF(dcReader io.Reader) bool { n, err := dcReader.Read(make([]byte, 1)) return n == 0 && err == io.EOF } type recvCompressor interface { RecvCompress() string } // For the two compressor parameters, both should not be set, but if they are, // dc takes precedence over compressor. // TODO(dfawley): wrap the old compressor/decompressor using the new API? func recv(p *parser, c baseCodec, s recvCompressor, dc Decompressor, m any, maxReceiveMessageSize int, payInfo *payloadInfo, compressor encoding.Compressor, isServer bool) error { data, err := recvAndDecompress(p, s, dc, maxReceiveMessageSize, payInfo, compressor, isServer) if err != nil { return err } // If the codec wants its own reference to the data, it can get it. Otherwise, always // free the buffers. defer data.Free() if err := c.Unmarshal(data, m); err != nil { return status.Errorf(codes.Internal, "grpc: failed to unmarshal the received message: %v", err) } return nil } // Information about RPC type rpcInfo struct { failfast bool preloaderInfo *compressorInfo } // Information about Preloader // Responsible for storing codec, and compressors // If stream (s) has context s.Context which stores rpcInfo that has non nil // pointers to codec, and compressors, then we can use preparedMsg for Async message prep // and reuse marshalled bytes type compressorInfo struct { codec baseCodec cp Compressor comp encoding.Compressor } type rpcInfoContextKey struct{} func newContextWithRPCInfo(ctx context.Context, failfast bool, codec baseCodec, cp Compressor, comp encoding.Compressor) context.Context { return context.WithValue(ctx, rpcInfoContextKey{}, &rpcInfo{ failfast: failfast, preloaderInfo: &compressorInfo{ codec: codec, cp: cp, comp: comp, }, }) } func rpcInfoFromContext(ctx context.Context) (s *rpcInfo, ok bool) { s, ok = ctx.Value(rpcInfoContextKey{}).(*rpcInfo) return } // Code returns the error code for err if it was produced by the rpc system. // Otherwise, it returns codes.Unknown. // // Deprecated: use status.Code instead. func Code(err error) codes.Code { return status.Code(err) } // ErrorDesc returns the error description of err if it was produced by the rpc system. // Otherwise, it returns err.Error() or empty string when err is nil. // // Deprecated: use status.Convert and Message method instead. func ErrorDesc(err error) string { return status.Convert(err).Message() } // Errorf returns an error containing an error code and a description; // Errorf returns nil if c is OK. // // Deprecated: use status.Errorf instead. func Errorf(c codes.Code, format string, a ...any) error { return status.Errorf(c, format, a...) } var errContextCanceled = status.Error(codes.Canceled, context.Canceled.Error()) var errContextDeadline = status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error()) // toRPCErr converts an error into an error from the status package. func toRPCErr(err error) error { switch err { case nil, io.EOF: return err case context.DeadlineExceeded: return errContextDeadline case context.Canceled: return errContextCanceled case io.ErrUnexpectedEOF: return status.Error(codes.Internal, err.Error()) } switch e := err.(type) { case transport.ConnectionError: return status.Error(codes.Unavailable, e.Desc) case *transport.NewStreamError: return toRPCErr(e.Err) } if _, ok := status.FromError(err); ok { return err } return status.Error(codes.Unknown, err.Error()) } // setCallInfoCodec should only be called after CallOptions have been applied. func setCallInfoCodec(c *callInfo) error { if c.codec != nil { // codec was already set by a CallOption; use it, but set the content // subtype if it is not set. if c.contentSubtype == "" { // c.codec is a baseCodec to hide the difference between grpc.Codec and // encoding.Codec (Name vs. String method name). We only support // setting content subtype from encoding.Codec to avoid a behavior // change with the deprecated version. if ec, ok := c.codec.(encoding.CodecV2); ok { c.contentSubtype = strings.ToLower(ec.Name()) } } return nil } if c.contentSubtype == "" { // No codec specified in CallOptions; use proto by default. c.codec = getCodec(proto.Name) return nil } // c.contentSubtype is already lowercased in CallContentSubtype c.codec = getCodec(c.contentSubtype) if c.codec == nil { return status.Errorf(codes.Internal, "no codec registered for content-subtype %s", c.contentSubtype) } return nil } // The SupportPackageIsVersion variables are referenced from generated protocol // buffer files to ensure compatibility with the gRPC version used. The latest // support package version is 9. // // Older versions are kept for compatibility. //
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace_notrace.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/trace_notrace.go
//go:build grpcnotrace /* * * Copyright 2024 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc // grpcnotrace can be used to avoid importing golang.org/x/net/trace, which in // turn enables binaries using gRPC-Go for dead code elimination, which can // yield 10-15% improvements in binary size when tracing is not needed. import ( "context" "fmt" ) type notrace struct{} func (notrace) LazyLog(x fmt.Stringer, sensitive bool) {} func (notrace) LazyPrintf(format string, a ...any) {} func (notrace) SetError() {} func (notrace) SetRecycler(f func(any)) {} func (notrace) SetTraceInfo(traceID, spanID uint64) {} func (notrace) SetMaxEvents(m int) {} func (notrace) Finish() {} func newTrace(family, title string) traceLog { return notrace{} } func newTraceContext(ctx context.Context, tr traceLog) context.Context { return ctx } func newTraceEventLog(family, title string) traceEventLog { return nil }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/call.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/call.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" ) // Invoke sends the RPC request on the wire and returns after response is // received. This is typically called by generated code. // // All errors returned by Invoke are compatible with the status package. func (cc *ClientConn) Invoke(ctx context.Context, method string, args, reply any, opts ...CallOption) error { // allow interceptor to see all applicable call options, which means those // configured as defaults from dial option as well as per-call options opts = combine(cc.dopts.callOptions, opts) if cc.dopts.unaryInt != nil { return cc.dopts.unaryInt(ctx, method, args, reply, cc, invoke, opts...) } return invoke(ctx, method, args, reply, cc, opts...) } func combine(o1 []CallOption, o2 []CallOption) []CallOption { // we don't use append because o1 could have extra capacity whose // elements would be overwritten, which could cause inadvertent // sharing (and race conditions) between concurrent calls if len(o1) == 0 { return o2 } else if len(o2) == 0 { return o1 } ret := make([]CallOption, len(o1)+len(o2)) copy(ret, o1) copy(ret[len(o1):], o2) return ret } // Invoke sends the RPC request on the wire and returns after response is // received. This is typically called by generated code. // // DEPRECATED: Use ClientConn.Invoke instead. func Invoke(ctx context.Context, method string, args, reply any, cc *ClientConn, opts ...CallOption) error { return cc.Invoke(ctx, method, args, reply, opts...) } var unaryStreamDesc = &StreamDesc{ServerStreams: false, ClientStreams: false} func invoke(ctx context.Context, method string, req, reply any, cc *ClientConn, opts ...CallOption) error { cs, err := newClientStream(ctx, unaryStreamDesc, cc, method, opts...) if err != nil { return err } if err := cs.SendMsg(req); err != nil { return err } return cs.RecvMsg(reply) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/picker_wrapper.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/picker_wrapper.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "fmt" "io" "sync/atomic" "google.golang.org/grpc/balancer" "google.golang.org/grpc/codes" "google.golang.org/grpc/internal/channelz" istatus "google.golang.org/grpc/internal/status" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" ) // pickerGeneration stores a picker and a channel used to signal that a picker // newer than this one is available. type pickerGeneration struct { // picker is the picker produced by the LB policy. May be nil if a picker // has never been produced. picker balancer.Picker // blockingCh is closed when the picker has been invalidated because there // is a new one available. blockingCh chan struct{} } // pickerWrapper is a wrapper of balancer.Picker. It blocks on certain pick // actions and unblock when there's a picker update. type pickerWrapper struct { // If pickerGen holds a nil pointer, the pickerWrapper is closed. pickerGen atomic.Pointer[pickerGeneration] statsHandlers []stats.Handler // to record blocking picker calls } func newPickerWrapper(statsHandlers []stats.Handler) *pickerWrapper { pw := &pickerWrapper{ statsHandlers: statsHandlers, } pw.pickerGen.Store(&pickerGeneration{ blockingCh: make(chan struct{}), }) return pw } // updatePicker is called by UpdateState calls from the LB policy. It // unblocks all blocked pick. func (pw *pickerWrapper) updatePicker(p balancer.Picker) { old := pw.pickerGen.Swap(&pickerGeneration{ picker: p, blockingCh: make(chan struct{}), }) close(old.blockingCh) } // doneChannelzWrapper performs the following: // - increments the calls started channelz counter // - wraps the done function in the passed in result to increment the calls // failed or calls succeeded channelz counter before invoking the actual // done function. func doneChannelzWrapper(acbw *acBalancerWrapper, result *balancer.PickResult) { ac := acbw.ac ac.incrCallsStarted() done := result.Done result.Done = func(b balancer.DoneInfo) { if b.Err != nil && b.Err != io.EOF { ac.incrCallsFailed() } else { ac.incrCallsSucceeded() } if done != nil { done(b) } } } // pick returns the transport that will be used for the RPC. // It may block in the following cases: // - there's no picker // - the current picker returns ErrNoSubConnAvailable // - the current picker returns other errors and failfast is false. // - the subConn returned by the current picker is not READY // When one of these situations happens, pick blocks until the picker gets updated. func (pw *pickerWrapper) pick(ctx context.Context, failfast bool, info balancer.PickInfo) (transport.ClientTransport, balancer.PickResult, error) { var ch chan struct{} var lastPickErr error for { pg := pw.pickerGen.Load() if pg == nil { return nil, balancer.PickResult{}, ErrClientConnClosing } if pg.picker == nil { ch = pg.blockingCh } if ch == pg.blockingCh { // This could happen when either: // - pw.picker is nil (the previous if condition), or // - we have already called pick on the current picker. select { case <-ctx.Done(): var errStr string if lastPickErr != nil { errStr = "latest balancer error: " + lastPickErr.Error() } else { errStr = fmt.Sprintf("%v while waiting for connections to become ready", ctx.Err()) } switch ctx.Err() { case context.DeadlineExceeded: return nil, balancer.PickResult{}, status.Error(codes.DeadlineExceeded, errStr) case context.Canceled: return nil, balancer.PickResult{}, status.Error(codes.Canceled, errStr) } case <-ch: } continue } // If the channel is set, it means that the pick call had to wait for a // new picker at some point. Either it's the first iteration and this // function received the first picker, or a picker errored with // ErrNoSubConnAvailable or errored with failfast set to false, which // will trigger a continue to the next iteration. In the first case this // conditional will hit if this call had to block (the channel is set). // In the second case, the only way it will get to this conditional is // if there is a new picker. if ch != nil { for _, sh := range pw.statsHandlers { sh.HandleRPC(ctx, &stats.PickerUpdated{}) } } ch = pg.blockingCh p := pg.picker pickResult, err := p.Pick(info) if err != nil { if err == balancer.ErrNoSubConnAvailable { continue } if st, ok := status.FromError(err); ok { // Status error: end the RPC unconditionally with this status. // First restrict the code to the list allowed by gRFC A54. if istatus.IsRestrictedControlPlaneCode(st) { err = status.Errorf(codes.Internal, "received picker error with illegal status: %v", err) } return nil, balancer.PickResult{}, dropError{error: err} } // For all other errors, wait for ready RPCs should block and other // RPCs should fail with unavailable. if !failfast { lastPickErr = err continue } return nil, balancer.PickResult{}, status.Error(codes.Unavailable, err.Error()) } acbw, ok := pickResult.SubConn.(*acBalancerWrapper) if !ok { logger.Errorf("subconn returned from pick is type %T, not *acBalancerWrapper", pickResult.SubConn) continue } if t := acbw.ac.getReadyTransport(); t != nil { if channelz.IsOn() { doneChannelzWrapper(acbw, &pickResult) return t, pickResult, nil } return t, pickResult, nil } if pickResult.Done != nil { // Calling done with nil error, no bytes sent and no bytes received. // DoneInfo with default value works. pickResult.Done(balancer.DoneInfo{}) } logger.Infof("blockingPicker: the picked transport is not ready, loop back to repick") // If ok == false, ac.state is not READY. // A valid picker always returns READY subConn. This means the state of ac // just changed, and picker will be updated shortly. // continue back to the beginning of the for loop to repick. } } func (pw *pickerWrapper) close() { old := pw.pickerGen.Swap(nil) close(old.blockingCh) } // reset clears the pickerWrapper and prepares it for being used again when idle // mode is exited. func (pw *pickerWrapper) reset() { old := pw.pickerGen.Swap(&pickerGeneration{blockingCh: make(chan struct{})}) close(old.blockingCh) } // dropError is a wrapper error that indicates the LB policy wishes to drop the // RPC and not retry it. type dropError struct { error }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/server.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/server.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "errors" "fmt" "io" "math" "net" "net/http" "reflect" "runtime" "strings" "sync" "sync/atomic" "time" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/encoding" "google.golang.org/grpc/encoding/proto" estats "google.golang.org/grpc/experimental/stats" "google.golang.org/grpc/grpclog" "google.golang.org/grpc/internal" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/channelz" "google.golang.org/grpc/internal/grpcsync" "google.golang.org/grpc/internal/grpcutil" istats "google.golang.org/grpc/internal/stats" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/metadata" "google.golang.org/grpc/peer" "google.golang.org/grpc/stats" "google.golang.org/grpc/status" "google.golang.org/grpc/tap" ) const ( defaultServerMaxReceiveMessageSize = 1024 * 1024 * 4 defaultServerMaxSendMessageSize = math.MaxInt32 // Server transports are tracked in a map which is keyed on listener // address. For regular gRPC traffic, connections are accepted in Serve() // through a call to Accept(), and we use the actual listener address as key // when we add it to the map. But for connections received through // ServeHTTP(), we do not have a listener and hence use this dummy value. listenerAddressForServeHTTP = "listenerAddressForServeHTTP" ) func init() { internal.GetServerCredentials = func(srv *Server) credentials.TransportCredentials { return srv.opts.creds } internal.IsRegisteredMethod = func(srv *Server, method string) bool { return srv.isRegisteredMethod(method) } internal.ServerFromContext = serverFromContext internal.AddGlobalServerOptions = func(opt ...ServerOption) { globalServerOptions = append(globalServerOptions, opt...) } internal.ClearGlobalServerOptions = func() { globalServerOptions = nil } internal.BinaryLogger = binaryLogger internal.JoinServerOptions = newJoinServerOption internal.BufferPool = bufferPool internal.MetricsRecorderForServer = func(srv *Server) estats.MetricsRecorder { return istats.NewMetricsRecorderList(srv.opts.statsHandlers) } } var statusOK = status.New(codes.OK, "") var logger = grpclog.Component("core") // MethodHandler is a function type that processes a unary RPC method call. type MethodHandler func(srv any, ctx context.Context, dec func(any) error, interceptor UnaryServerInterceptor) (any, error) // MethodDesc represents an RPC service's method specification. type MethodDesc struct { MethodName string Handler MethodHandler } // ServiceDesc represents an RPC service's specification. type ServiceDesc struct { ServiceName string // The pointer to the service interface. Used to check whether the user // provided implementation satisfies the interface requirements. HandlerType any Methods []MethodDesc Streams []StreamDesc Metadata any } // serviceInfo wraps information about a service. It is very similar to // ServiceDesc and is constructed from it for internal purposes. type serviceInfo struct { // Contains the implementation for the methods in this service. serviceImpl any methods map[string]*MethodDesc streams map[string]*StreamDesc mdata any } // Server is a gRPC server to serve RPC requests. type Server struct { opts serverOptions mu sync.Mutex // guards following lis map[net.Listener]bool // conns contains all active server transports. It is a map keyed on a // listener address with the value being the set of active transports // belonging to that listener. conns map[string]map[transport.ServerTransport]bool serve bool drain bool cv *sync.Cond // signaled when connections close for GracefulStop services map[string]*serviceInfo // service name -> service info events traceEventLog quit *grpcsync.Event done *grpcsync.Event channelzRemoveOnce sync.Once serveWG sync.WaitGroup // counts active Serve goroutines for Stop/GracefulStop handlersWG sync.WaitGroup // counts active method handler goroutines channelz *channelz.Server serverWorkerChannel chan func() serverWorkerChannelClose func() } type serverOptions struct { creds credentials.TransportCredentials codec baseCodec cp Compressor dc Decompressor unaryInt UnaryServerInterceptor streamInt StreamServerInterceptor chainUnaryInts []UnaryServerInterceptor chainStreamInts []StreamServerInterceptor binaryLogger binarylog.Logger inTapHandle tap.ServerInHandle statsHandlers []stats.Handler maxConcurrentStreams uint32 maxReceiveMessageSize int maxSendMessageSize int unknownStreamDesc *StreamDesc keepaliveParams keepalive.ServerParameters keepalivePolicy keepalive.EnforcementPolicy initialWindowSize int32 initialConnWindowSize int32 writeBufferSize int readBufferSize int sharedWriteBuffer bool connectionTimeout time.Duration maxHeaderListSize *uint32 headerTableSize *uint32 numServerWorkers uint32 bufferPool mem.BufferPool waitForHandlers bool } var defaultServerOptions = serverOptions{ maxConcurrentStreams: math.MaxUint32, maxReceiveMessageSize: defaultServerMaxReceiveMessageSize, maxSendMessageSize: defaultServerMaxSendMessageSize, connectionTimeout: 120 * time.Second, writeBufferSize: defaultWriteBufSize, readBufferSize: defaultReadBufSize, bufferPool: mem.DefaultBufferPool(), } var globalServerOptions []ServerOption // A ServerOption sets options such as credentials, codec and keepalive parameters, etc. type ServerOption interface { apply(*serverOptions) } // EmptyServerOption does not alter the server configuration. It can be embedded // in another structure to build custom server options. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type EmptyServerOption struct{} func (EmptyServerOption) apply(*serverOptions) {} // funcServerOption wraps a function that modifies serverOptions into an // implementation of the ServerOption interface. type funcServerOption struct { f func(*serverOptions) } func (fdo *funcServerOption) apply(do *serverOptions) { fdo.f(do) } func newFuncServerOption(f func(*serverOptions)) *funcServerOption { return &funcServerOption{ f: f, } } // joinServerOption provides a way to combine arbitrary number of server // options into one. type joinServerOption struct { opts []ServerOption } func (mdo *joinServerOption) apply(do *serverOptions) { for _, opt := range mdo.opts { opt.apply(do) } } func newJoinServerOption(opts ...ServerOption) ServerOption { return &joinServerOption{opts: opts} } // SharedWriteBuffer allows reusing per-connection transport write buffer. // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func SharedWriteBuffer(val bool) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.sharedWriteBuffer = val }) } // WriteBufferSize determines how much data can be batched before doing a write // on the wire. The default value for this buffer is 32KB. Zero or negative // values will disable the write buffer such that each write will be on underlying // connection. Note: A Send call may not directly translate to a write. func WriteBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.writeBufferSize = s }) } // ReadBufferSize lets you set the size of read buffer, this determines how much // data can be read at most for one read syscall. The default value for this // buffer is 32KB. Zero or negative values will disable read buffer for a // connection so data framer can access the underlying conn directly. func ReadBufferSize(s int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.readBufferSize = s }) } // InitialWindowSize returns a ServerOption that sets window size for stream. // The lower bound for window size is 64K and any value smaller than that will be ignored. func InitialWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialWindowSize = s }) } // InitialConnWindowSize returns a ServerOption that sets window size for a connection. // The lower bound for window size is 64K and any value smaller than that will be ignored. func InitialConnWindowSize(s int32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.initialConnWindowSize = s }) } // KeepaliveParams returns a ServerOption that sets keepalive and max-age parameters for the server. func KeepaliveParams(kp keepalive.ServerParameters) ServerOption { if kp.Time > 0 && kp.Time < internal.KeepaliveMinServerPingTime { logger.Warning("Adjusting keepalive ping interval to minimum period of 1s") kp.Time = internal.KeepaliveMinServerPingTime } return newFuncServerOption(func(o *serverOptions) { o.keepaliveParams = kp }) } // KeepaliveEnforcementPolicy returns a ServerOption that sets keepalive enforcement policy for the server. func KeepaliveEnforcementPolicy(kep keepalive.EnforcementPolicy) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.keepalivePolicy = kep }) } // CustomCodec returns a ServerOption that sets a codec for message marshaling and unmarshaling. // // This will override any lookups by content-subtype for Codecs registered with RegisterCodec. // // Deprecated: register codecs using encoding.RegisterCodec. The server will // automatically use registered codecs based on the incoming requests' headers. // See also // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec. // Will be supported throughout 1.x. func CustomCodec(codec Codec) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.codec = newCodecV0Bridge(codec) }) } // ForceServerCodec returns a ServerOption that sets a codec for message // marshaling and unmarshaling. // // This will override any lookups by content-subtype for Codecs registered // with RegisterCodec. // // See Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. Also see the documentation on RegisterCodec and // CallContentSubtype for more details on the interaction between encoding.Codec // and content-subtype. // // This function is provided for advanced users; prefer to register codecs // using encoding.RegisterCodec. // The server will automatically use registered codecs based on the incoming // requests' headers. See also // https://github.com/grpc/grpc-go/blob/master/Documentation/encoding.md#using-a-codec. // Will be supported throughout 1.x. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func ForceServerCodec(codec encoding.Codec) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.codec = newCodecV1Bridge(codec) }) } // ForceServerCodecV2 is the equivalent of ForceServerCodec, but for the new // CodecV2 interface. // // Will be supported throughout 1.x. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func ForceServerCodecV2(codecV2 encoding.CodecV2) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.codec = codecV2 }) } // RPCCompressor returns a ServerOption that sets a compressor for outbound // messages. For backward compatibility, all outbound messages will be sent // using this compressor, regardless of incoming message compression. By // default, server messages will be sent using the same compressor with which // request messages were sent. // // Deprecated: use encoding.RegisterCompressor instead. Will be supported // throughout 1.x. func RPCCompressor(cp Compressor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.cp = cp }) } // RPCDecompressor returns a ServerOption that sets a decompressor for inbound // messages. It has higher priority than decompressors registered via // encoding.RegisterCompressor. // // Deprecated: use encoding.RegisterCompressor instead. Will be supported // throughout 1.x. func RPCDecompressor(dc Decompressor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.dc = dc }) } // MaxMsgSize returns a ServerOption to set the max message size in bytes the server can receive. // If this is not set, gRPC uses the default limit. // // Deprecated: use MaxRecvMsgSize instead. Will be supported throughout 1.x. func MaxMsgSize(m int) ServerOption { return MaxRecvMsgSize(m) } // MaxRecvMsgSize returns a ServerOption to set the max message size in bytes the server can receive. // If this is not set, gRPC uses the default 4MB. func MaxRecvMsgSize(m int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxReceiveMessageSize = m }) } // MaxSendMsgSize returns a ServerOption to set the max message size in bytes the server can send. // If this is not set, gRPC uses the default `math.MaxInt32`. func MaxSendMsgSize(m int) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.maxSendMessageSize = m }) } // MaxConcurrentStreams returns a ServerOption that will apply a limit on the number // of concurrent streams to each ServerTransport. func MaxConcurrentStreams(n uint32) ServerOption { if n == 0 { n = math.MaxUint32 } return newFuncServerOption(func(o *serverOptions) { o.maxConcurrentStreams = n }) } // Creds returns a ServerOption that sets credentials for server connections. func Creds(c credentials.TransportCredentials) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.creds = c }) } // UnaryInterceptor returns a ServerOption that sets the UnaryServerInterceptor for the // server. Only one unary interceptor can be installed. The construction of multiple // interceptors (e.g., chaining) can be implemented at the caller. func UnaryInterceptor(i UnaryServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.unaryInt != nil { panic("The unary server interceptor was already set and may not be reset.") } o.unaryInt = i }) } // ChainUnaryInterceptor returns a ServerOption that specifies the chained interceptor // for unary RPCs. The first interceptor will be the outer most, // while the last interceptor will be the inner most wrapper around the real call. // All unary interceptors added by this method will be chained. func ChainUnaryInterceptor(interceptors ...UnaryServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.chainUnaryInts = append(o.chainUnaryInts, interceptors...) }) } // StreamInterceptor returns a ServerOption that sets the StreamServerInterceptor for the // server. Only one stream interceptor can be installed. func StreamInterceptor(i StreamServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.streamInt != nil { panic("The stream server interceptor was already set and may not be reset.") } o.streamInt = i }) } // ChainStreamInterceptor returns a ServerOption that specifies the chained interceptor // for streaming RPCs. The first interceptor will be the outer most, // while the last interceptor will be the inner most wrapper around the real call. // All stream interceptors added by this method will be chained. func ChainStreamInterceptor(interceptors ...StreamServerInterceptor) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.chainStreamInts = append(o.chainStreamInts, interceptors...) }) } // InTapHandle returns a ServerOption that sets the tap handle for all the server // transport to be created. Only one can be installed. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func InTapHandle(h tap.ServerInHandle) ServerOption { return newFuncServerOption(func(o *serverOptions) { if o.inTapHandle != nil { panic("The tap handle was already set and may not be reset.") } o.inTapHandle = h }) } // StatsHandler returns a ServerOption that sets the stats handler for the server. func StatsHandler(h stats.Handler) ServerOption { return newFuncServerOption(func(o *serverOptions) { if h == nil { logger.Error("ignoring nil parameter in grpc.StatsHandler ServerOption") // Do not allow a nil stats handler, which would otherwise cause // panics. return } o.statsHandlers = append(o.statsHandlers, h) }) } // binaryLogger returns a ServerOption that can set the binary logger for the // server. func binaryLogger(bl binarylog.Logger) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.binaryLogger = bl }) } // UnknownServiceHandler returns a ServerOption that allows for adding a custom // unknown service handler. The provided method is a bidi-streaming RPC service // handler that will be invoked instead of returning the "unimplemented" gRPC // error whenever a request is received for an unregistered service or method. // The handling function and stream interceptor (if set) have full access to // the ServerStream, including its Context. func UnknownServiceHandler(streamHandler StreamHandler) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.unknownStreamDesc = &StreamDesc{ StreamName: "unknown_service_handler", Handler: streamHandler, // We need to assume that the users of the streamHandler will want to use both. ClientStreams: true, ServerStreams: true, } }) } // ConnectionTimeout returns a ServerOption that sets the timeout for // connection establishment (up to and including HTTP/2 handshaking) for all // new connections. If this is not set, the default is 120 seconds. A zero or // negative value will result in an immediate timeout. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func ConnectionTimeout(d time.Duration) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.connectionTimeout = d }) } // MaxHeaderListSizeServerOption is a ServerOption that sets the max // (uncompressed) size of header list that the server is prepared to accept. type MaxHeaderListSizeServerOption struct { MaxHeaderListSize uint32 } func (o MaxHeaderListSizeServerOption) apply(so *serverOptions) { so.maxHeaderListSize = &o.MaxHeaderListSize } // MaxHeaderListSize returns a ServerOption that sets the max (uncompressed) size // of header list that the server is prepared to accept. func MaxHeaderListSize(s uint32) ServerOption { return MaxHeaderListSizeServerOption{ MaxHeaderListSize: s, } } // HeaderTableSize returns a ServerOption that sets the size of dynamic // header table for stream. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func HeaderTableSize(s uint32) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.headerTableSize = &s }) } // NumStreamWorkers returns a ServerOption that sets the number of worker // goroutines that should be used to process incoming streams. Setting this to // zero (default) will disable workers and spawn a new goroutine for each // stream. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func NumStreamWorkers(numServerWorkers uint32) ServerOption { // TODO: If/when this API gets stabilized (i.e. stream workers become the // only way streams are processed), change the behavior of the zero value to // a sane default. Preliminary experiments suggest that a value equal to the // number of CPUs available is most performant; requires thorough testing. return newFuncServerOption(func(o *serverOptions) { o.numServerWorkers = numServerWorkers }) } // WaitForHandlers cause Stop to wait until all outstanding method handlers have // exited before returning. If false, Stop will return as soon as all // connections have closed, but method handlers may still be running. By // default, Stop does not wait for method handlers to return. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WaitForHandlers(w bool) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.waitForHandlers = w }) } func bufferPool(bufferPool mem.BufferPool) ServerOption { return newFuncServerOption(func(o *serverOptions) { o.bufferPool = bufferPool }) } // serverWorkerResetThreshold defines how often the stack must be reset. Every // N requests, by spawning a new goroutine in its place, a worker can reset its // stack so that large stacks don't live in memory forever. 2^16 should allow // each goroutine stack to live for at least a few seconds in a typical // workload (assuming a QPS of a few thousand requests/sec). const serverWorkerResetThreshold = 1 << 16 // serverWorker blocks on a *transport.ServerStream channel forever and waits // for data to be fed by serveStreams. This allows multiple requests to be // processed by the same goroutine, removing the need for expensive stack // re-allocations (see the runtime.morestack problem [1]). // // [1] https://github.com/golang/go/issues/18138 func (s *Server) serverWorker() { for completed := 0; completed < serverWorkerResetThreshold; completed++ { f, ok := <-s.serverWorkerChannel if !ok { return } f() } go s.serverWorker() } // initServerWorkers creates worker goroutines and a channel to process incoming // connections to reduce the time spent overall on runtime.morestack. func (s *Server) initServerWorkers() { s.serverWorkerChannel = make(chan func()) s.serverWorkerChannelClose = sync.OnceFunc(func() { close(s.serverWorkerChannel) }) for i := uint32(0); i < s.opts.numServerWorkers; i++ { go s.serverWorker() } } // NewServer creates a gRPC server which has no service registered and has not // started to accept requests yet. func NewServer(opt ...ServerOption) *Server { opts := defaultServerOptions for _, o := range globalServerOptions { o.apply(&opts) } for _, o := range opt { o.apply(&opts) } s := &Server{ lis: make(map[net.Listener]bool), opts: opts, conns: make(map[string]map[transport.ServerTransport]bool), services: make(map[string]*serviceInfo), quit: grpcsync.NewEvent(), done: grpcsync.NewEvent(), channelz: channelz.RegisterServer(""), } chainUnaryServerInterceptors(s) chainStreamServerInterceptors(s) s.cv = sync.NewCond(&s.mu) if EnableTracing { _, file, line, _ := runtime.Caller(1) s.events = newTraceEventLog("grpc.Server", fmt.Sprintf("%s:%d", file, line)) } if s.opts.numServerWorkers > 0 { s.initServerWorkers() } channelz.Info(logger, s.channelz, "Server created") return s } // printf records an event in s's event log, unless s has been stopped. // REQUIRES s.mu is held. func (s *Server) printf(format string, a ...any) { if s.events != nil { s.events.Printf(format, a...) } } // errorf records an error in s's event log, unless s has been stopped. // REQUIRES s.mu is held. func (s *Server) errorf(format string, a ...any) { if s.events != nil { s.events.Errorf(format, a...) } } // ServiceRegistrar wraps a single method that supports service registration. It // enables users to pass concrete types other than grpc.Server to the service // registration methods exported by the IDL generated code. type ServiceRegistrar interface { // RegisterService registers a service and its implementation to the // concrete type implementing this interface. It may not be called // once the server has started serving. // desc describes the service and its methods and handlers. impl is the // service implementation which is passed to the method handlers. RegisterService(desc *ServiceDesc, impl any) } // RegisterService registers a service and its implementation to the gRPC // server. It is called from the IDL generated code. This must be called before // invoking Serve. If ss is non-nil (for legacy code), its type is checked to // ensure it implements sd.HandlerType. func (s *Server) RegisterService(sd *ServiceDesc, ss any) { if ss != nil { ht := reflect.TypeOf(sd.HandlerType).Elem() st := reflect.TypeOf(ss) if !st.Implements(ht) { logger.Fatalf("grpc: Server.RegisterService found the handler of type %v that does not satisfy %v", st, ht) } } s.register(sd, ss) } func (s *Server) register(sd *ServiceDesc, ss any) { s.mu.Lock() defer s.mu.Unlock() s.printf("RegisterService(%q)", sd.ServiceName) if s.serve { logger.Fatalf("grpc: Server.RegisterService after Server.Serve for %q", sd.ServiceName) } if _, ok := s.services[sd.ServiceName]; ok { logger.Fatalf("grpc: Server.RegisterService found duplicate service registration for %q", sd.ServiceName) } info := &serviceInfo{ serviceImpl: ss, methods: make(map[string]*MethodDesc), streams: make(map[string]*StreamDesc), mdata: sd.Metadata, } for i := range sd.Methods { d := &sd.Methods[i] info.methods[d.MethodName] = d } for i := range sd.Streams { d := &sd.Streams[i] info.streams[d.StreamName] = d } s.services[sd.ServiceName] = info } // MethodInfo contains the information of an RPC including its method name and type. type MethodInfo struct { // Name is the method name only, without the service name or package name. Name string // IsClientStream indicates whether the RPC is a client streaming RPC. IsClientStream bool // IsServerStream indicates whether the RPC is a server streaming RPC. IsServerStream bool } // ServiceInfo contains unary RPC method info, streaming RPC method info and metadata for a service. type ServiceInfo struct { Methods []MethodInfo // Metadata is the metadata specified in ServiceDesc when registering service. Metadata any } // GetServiceInfo returns a map from service names to ServiceInfo. // Service names include the package names, in the form of <package>.<service>. func (s *Server) GetServiceInfo() map[string]ServiceInfo { ret := make(map[string]ServiceInfo) for n, srv := range s.services { methods := make([]MethodInfo, 0, len(srv.methods)+len(srv.streams)) for m := range srv.methods { methods = append(methods, MethodInfo{ Name: m, IsClientStream: false, IsServerStream: false, }) } for m, d := range srv.streams { methods = append(methods, MethodInfo{ Name: m, IsClientStream: d.ClientStreams, IsServerStream: d.ServerStreams, }) } ret[n] = ServiceInfo{ Methods: methods, Metadata: srv.mdata, } } return ret } // ErrServerStopped indicates that the operation is now illegal because of // the server being stopped. var ErrServerStopped = errors.New("grpc: the server has been stopped") type listenSocket struct { net.Listener channelz *channelz.Socket } func (l *listenSocket) Close() error { err := l.Listener.Close() channelz.RemoveEntry(l.channelz.ID) channelz.Info(logger, l.channelz, "ListenSocket deleted") return err } // Serve accepts incoming connections on the listener lis, creating a new // ServerTransport and service goroutine for each. The service goroutines // read gRPC requests and then call the registered handlers to reply to them. // Serve returns when lis.Accept fails with fatal errors. lis will be closed when // this method returns. // Serve will return a non-nil error unless Stop or GracefulStop is called. // // Note: All supported releases of Go (as of December 2023) override the OS // defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive // with OS defaults for keepalive time and interval, callers need to do the // following two things: // - pass a net.Listener created by calling the Listen method on a // net.ListenConfig with the `KeepAlive` field set to a negative value. This // will result in the Go standard library not overriding OS defaults for TCP // keepalive interval and time. But this will also result in the Go standard // library not enabling TCP keepalives by default. // - override the Accept method on the passed in net.Listener and set the // SO_KEEPALIVE socket option to enable TCP keepalives, with OS defaults. func (s *Server) Serve(lis net.Listener) error { s.mu.Lock() s.printf("serving") s.serve = true if s.lis == nil { // Serve called after Stop or GracefulStop. s.mu.Unlock() lis.Close() return ErrServerStopped } s.serveWG.Add(1) defer func() { s.serveWG.Done() if s.quit.HasFired() { // Stop or GracefulStop called; block until done and return nil. <-s.done.Done() } }() ls := &listenSocket{ Listener: lis, channelz: channelz.RegisterSocket(&channelz.Socket{ SocketType: channelz.SocketTypeListen, Parent: s.channelz, RefName: lis.Addr().String(), LocalAddr: lis.Addr(), SocketOptions: channelz.GetSocketOption(lis)}, ), } s.lis[ls] = true defer func() { s.mu.Lock() if s.lis != nil && s.lis[ls] { ls.Close() delete(s.lis, ls) } s.mu.Unlock() }() s.mu.Unlock() channelz.Info(logger, ls.channelz, "ListenSocket created") var tempDelay time.Duration // how long to sleep on accept failure for { rawConn, err := lis.Accept() if err != nil { if ne, ok := err.(interface { Temporary() bool }); ok && ne.Temporary() { if tempDelay == 0 { tempDelay = 5 * time.Millisecond } else { tempDelay *= 2 } if max := 1 * time.Second; tempDelay > max { tempDelay = max } s.mu.Lock() s.printf("Accept error: %v; retrying in %v", err, tempDelay) s.mu.Unlock() timer := time.NewTimer(tempDelay) select { case <-timer.C: case <-s.quit.Done(): timer.Stop() return nil } continue } s.mu.Lock() s.printf("done serving; Accept = %v", err) s.mu.Unlock() if s.quit.HasFired() { return nil } return err } tempDelay = 0 // Start a new goroutine to deal with rawConn so we don't stall this Accept // loop goroutine. // // Make sure we account for the goroutine so GracefulStop doesn't nil out // s.conns before this conn can be added. s.serveWG.Add(1) go func() { s.handleRawConn(lis.Addr().String(), rawConn) s.serveWG.Done() }() } } // handleRawConn forks a goroutine to handle a just-accepted connection that // has not had any I/O performed on it yet. func (s *Server) handleRawConn(lisAddr string, rawConn net.Conn) { if s.quit.HasFired() { rawConn.Close() return } rawConn.SetDeadline(time.Now().Add(s.opts.connectionTimeout)) // Finish handshaking (HTTP2) st := s.newHTTP2Transport(rawConn) rawConn.SetDeadline(time.Time{}) if st == nil { return } if cc, ok := rawConn.(interface { PassServerTransport(transport.ServerTransport) }); ok { cc.PassServerTransport(st) } if !s.addConn(lisAddr, st) { return } go func() { s.serveStreams(context.Background(), st, rawConn) s.removeConn(lisAddr, st) }() } // newHTTP2Transport sets up a http/2 transport (using the // gRPC http2 server transport in transport/http2_server.go). func (s *Server) newHTTP2Transport(c net.Conn) transport.ServerTransport { config := &transport.ServerConfig{ MaxStreams: s.opts.maxConcurrentStreams, ConnectionTimeout: s.opts.connectionTimeout, Credentials: s.opts.creds, InTapHandle: s.opts.inTapHandle, StatsHandlers: s.opts.statsHandlers, KeepaliveParams: s.opts.keepaliveParams, KeepalivePolicy: s.opts.keepalivePolicy, InitialWindowSize: s.opts.initialWindowSize, InitialConnWindowSize: s.opts.initialConnWindowSize, WriteBufferSize: s.opts.writeBufferSize,
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
true
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/version.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/version.go
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc // Version is the current grpc version. const Version = "1.71.0"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/doc.go
/* * * Copyright 2015 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ //go:generate ./scripts/regenerate.sh /* Package grpc implements an RPC system called gRPC. See grpc.io for more information about gRPC. */ package grpc // import "google.golang.org/grpc"
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/dialoptions.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/dialoptions.go
/* * * Copyright 2018 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "context" "net" "net/url" "time" "google.golang.org/grpc/backoff" "google.golang.org/grpc/channelz" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" "google.golang.org/grpc/internal" internalbackoff "google.golang.org/grpc/internal/backoff" "google.golang.org/grpc/internal/binarylog" "google.golang.org/grpc/internal/transport" "google.golang.org/grpc/keepalive" "google.golang.org/grpc/mem" "google.golang.org/grpc/resolver" "google.golang.org/grpc/stats" ) const ( // https://github.com/grpc/proposal/blob/master/A6-client-retries.md#limits-on-retries-and-hedges defaultMaxCallAttempts = 5 ) func init() { internal.AddGlobalDialOptions = func(opt ...DialOption) { globalDialOptions = append(globalDialOptions, opt...) } internal.ClearGlobalDialOptions = func() { globalDialOptions = nil } internal.AddGlobalPerTargetDialOptions = func(opt any) { if ptdo, ok := opt.(perTargetDialOption); ok { globalPerTargetDialOptions = append(globalPerTargetDialOptions, ptdo) } } internal.ClearGlobalPerTargetDialOptions = func() { globalPerTargetDialOptions = nil } internal.WithBinaryLogger = withBinaryLogger internal.JoinDialOptions = newJoinDialOption internal.DisableGlobalDialOptions = newDisableGlobalDialOptions internal.WithBufferPool = withBufferPool } // dialOptions configure a Dial call. dialOptions are set by the DialOption // values passed to Dial. type dialOptions struct { unaryInt UnaryClientInterceptor streamInt StreamClientInterceptor chainUnaryInts []UnaryClientInterceptor chainStreamInts []StreamClientInterceptor compressorV0 Compressor dc Decompressor bs internalbackoff.Strategy block bool returnLastError bool timeout time.Duration authority string binaryLogger binarylog.Logger copts transport.ConnectOptions callOptions []CallOption channelzParent channelz.Identifier disableServiceConfig bool disableRetry bool disableHealthCheck bool minConnectTimeout func() time.Duration defaultServiceConfig *ServiceConfig // defaultServiceConfig is parsed from defaultServiceConfigRawJSON. defaultServiceConfigRawJSON *string resolvers []resolver.Builder idleTimeout time.Duration defaultScheme string maxCallAttempts int enableLocalDNSResolution bool // Specifies if target hostnames should be resolved when proxying is enabled. useProxy bool // Specifies if a server should be connected via proxy. } // DialOption configures how we set up the connection. type DialOption interface { apply(*dialOptions) } var globalDialOptions []DialOption // perTargetDialOption takes a parsed target and returns a dial option to apply. // // This gets called after NewClient() parses the target, and allows per target // configuration set through a returned DialOption. The DialOption will not take // effect if specifies a resolver builder, as that Dial Option is factored in // while parsing target. type perTargetDialOption interface { // DialOption returns a Dial Option to apply. DialOptionForTarget(parsedTarget url.URL) DialOption } var globalPerTargetDialOptions []perTargetDialOption // EmptyDialOption does not alter the dial configuration. It can be embedded in // another structure to build custom dial options. // // # Experimental // // Notice: This type is EXPERIMENTAL and may be changed or removed in a // later release. type EmptyDialOption struct{} func (EmptyDialOption) apply(*dialOptions) {} type disableGlobalDialOptions struct{} func (disableGlobalDialOptions) apply(*dialOptions) {} // newDisableGlobalDialOptions returns a DialOption that prevents the ClientConn // from applying the global DialOptions (set via AddGlobalDialOptions). func newDisableGlobalDialOptions() DialOption { return &disableGlobalDialOptions{} } // funcDialOption wraps a function that modifies dialOptions into an // implementation of the DialOption interface. type funcDialOption struct { f func(*dialOptions) } func (fdo *funcDialOption) apply(do *dialOptions) { fdo.f(do) } func newFuncDialOption(f func(*dialOptions)) *funcDialOption { return &funcDialOption{ f: f, } } type joinDialOption struct { opts []DialOption } func (jdo *joinDialOption) apply(do *dialOptions) { for _, opt := range jdo.opts { opt.apply(do) } } func newJoinDialOption(opts ...DialOption) DialOption { return &joinDialOption{opts: opts} } // WithSharedWriteBuffer allows reusing per-connection transport write buffer. // If this option is set to true every connection will release the buffer after // flushing the data on the wire. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithSharedWriteBuffer(val bool) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.SharedWriteBuffer = val }) } // WithWriteBufferSize determines how much data can be batched before doing a // write on the wire. The default value for this buffer is 32KB. // // Zero or negative values will disable the write buffer such that each write // will be on underlying connection. Note: A Send call may not directly // translate to a write. func WithWriteBufferSize(s int) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.WriteBufferSize = s }) } // WithReadBufferSize lets you set the size of read buffer, this determines how // much data can be read at most for each read syscall. // // The default value for this buffer is 32KB. Zero or negative values will // disable read buffer for a connection so data framer can access the // underlying conn directly. func WithReadBufferSize(s int) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.ReadBufferSize = s }) } // WithInitialWindowSize returns a DialOption which sets the value for initial // window size on a stream. The lower bound for window size is 64K and any value // smaller than that will be ignored. func WithInitialWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialWindowSize = s }) } // WithInitialConnWindowSize returns a DialOption which sets the value for // initial window size on a connection. The lower bound for window size is 64K // and any value smaller than that will be ignored. func WithInitialConnWindowSize(s int32) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.InitialConnWindowSize = s }) } // WithMaxMsgSize returns a DialOption which sets the maximum message size the // client can receive. // // Deprecated: use WithDefaultCallOptions(MaxCallRecvMsgSize(s)) instead. Will // be supported throughout 1.x. func WithMaxMsgSize(s int) DialOption { return WithDefaultCallOptions(MaxCallRecvMsgSize(s)) } // WithDefaultCallOptions returns a DialOption which sets the default // CallOptions for calls over the connection. func WithDefaultCallOptions(cos ...CallOption) DialOption { return newFuncDialOption(func(o *dialOptions) { o.callOptions = append(o.callOptions, cos...) }) } // WithCodec returns a DialOption which sets a codec for message marshaling and // unmarshaling. // // Deprecated: use WithDefaultCallOptions(ForceCodec(_)) instead. Will be // supported throughout 1.x. func WithCodec(c Codec) DialOption { return WithDefaultCallOptions(CallCustomCodec(c)) } // WithCompressor returns a DialOption which sets a Compressor to use for // message compression. It has lower priority than the compressor set by the // UseCompressor CallOption. // // Deprecated: use UseCompressor instead. Will be supported throughout 1.x. func WithCompressor(cp Compressor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.compressorV0 = cp }) } // WithDecompressor returns a DialOption which sets a Decompressor to use for // incoming message decompression. If incoming response messages are encoded // using the decompressor's Type(), it will be used. Otherwise, the message // encoding will be used to look up the compressor registered via // encoding.RegisterCompressor, which will then be used to decompress the // message. If no compressor is registered for the encoding, an Unimplemented // status error will be returned. // // Deprecated: use encoding.RegisterCompressor instead. Will be supported // throughout 1.x. func WithDecompressor(dc Decompressor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.dc = dc }) } // WithConnectParams configures the ClientConn to use the provided ConnectParams // for creating and maintaining connections to servers. // // The backoff configuration specified as part of the ConnectParams overrides // all defaults specified in // https://github.com/grpc/grpc/blob/master/doc/connection-backoff.md. Consider // using the backoff.DefaultConfig as a base, in cases where you want to // override only a subset of the backoff configuration. func WithConnectParams(p ConnectParams) DialOption { return newFuncDialOption(func(o *dialOptions) { o.bs = internalbackoff.Exponential{Config: p.Backoff} o.minConnectTimeout = func() time.Duration { return p.MinConnectTimeout } }) } // WithBackoffMaxDelay configures the dialer to use the provided maximum delay // when backing off after failed connection attempts. // // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x. func WithBackoffMaxDelay(md time.Duration) DialOption { return WithBackoffConfig(BackoffConfig{MaxDelay: md}) } // WithBackoffConfig configures the dialer to use the provided backoff // parameters after connection failures. // // Deprecated: use WithConnectParams instead. Will be supported throughout 1.x. func WithBackoffConfig(b BackoffConfig) DialOption { bc := backoff.DefaultConfig bc.MaxDelay = b.MaxDelay return withBackoff(internalbackoff.Exponential{Config: bc}) } // withBackoff sets the backoff strategy used for connectRetryNum after a failed // connection attempt. // // This can be exported if arbitrary backoff strategies are allowed by gRPC. func withBackoff(bs internalbackoff.Strategy) DialOption { return newFuncDialOption(func(o *dialOptions) { o.bs = bs }) } // WithBlock returns a DialOption which makes callers of Dial block until the // underlying connection is up. Without this, Dial returns immediately and // connecting the server happens in background. // // Use of this feature is not recommended. For more information, please see: // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md // // Deprecated: this DialOption is not supported by NewClient. // Will be supported throughout 1.x. func WithBlock() DialOption { return newFuncDialOption(func(o *dialOptions) { o.block = true }) } // WithReturnConnectionError returns a DialOption which makes the client connection // return a string containing both the last connection error that occurred and // the context.DeadlineExceeded error. // Implies WithBlock() // // Use of this feature is not recommended. For more information, please see: // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md // // Deprecated: this DialOption is not supported by NewClient. // Will be supported throughout 1.x. func WithReturnConnectionError() DialOption { return newFuncDialOption(func(o *dialOptions) { o.block = true o.returnLastError = true }) } // WithInsecure returns a DialOption which disables transport security for this // ClientConn. Under the hood, it uses insecure.NewCredentials(). // // Note that using this DialOption with per-RPC credentials (through // WithCredentialsBundle or WithPerRPCCredentials) which require transport // security is incompatible and will cause grpc.Dial() to fail. // // Deprecated: use WithTransportCredentials and insecure.NewCredentials() // instead. Will be supported throughout 1.x. func WithInsecure() DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.TransportCredentials = insecure.NewCredentials() }) } // WithNoProxy returns a DialOption which disables the use of proxies for this // ClientConn. This is ignored if WithDialer or WithContextDialer are used. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithNoProxy() DialOption { return newFuncDialOption(func(o *dialOptions) { o.useProxy = false }) } // WithLocalDNSResolution forces local DNS name resolution even when a proxy is // specified in the environment. By default, the server name is provided // directly to the proxy as part of the CONNECT handshake. This is ignored if // WithNoProxy is used. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithLocalDNSResolution() DialOption { return newFuncDialOption(func(o *dialOptions) { o.enableLocalDNSResolution = true }) } // WithTransportCredentials returns a DialOption which configures a connection // level security credentials (e.g., TLS/SSL). This should not be used together // with WithCredentialsBundle. func WithTransportCredentials(creds credentials.TransportCredentials) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.TransportCredentials = creds }) } // WithPerRPCCredentials returns a DialOption which sets credentials and places // auth state on each outbound RPC. func WithPerRPCCredentials(creds credentials.PerRPCCredentials) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.PerRPCCredentials = append(o.copts.PerRPCCredentials, creds) }) } // WithCredentialsBundle returns a DialOption to set a credentials bundle for // the ClientConn.WithCreds. This should not be used together with // WithTransportCredentials. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithCredentialsBundle(b credentials.Bundle) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.CredsBundle = b }) } // WithTimeout returns a DialOption that configures a timeout for dialing a // ClientConn initially. This is valid if and only if WithBlock() is present. // // Deprecated: this DialOption is not supported by NewClient. // Will be supported throughout 1.x. func WithTimeout(d time.Duration) DialOption { return newFuncDialOption(func(o *dialOptions) { o.timeout = d }) } // WithContextDialer returns a DialOption that sets a dialer to create // connections. If FailOnNonTempDialError() is set to true, and an error is // returned by f, gRPC checks the error's Temporary() method to decide if it // should try to reconnect to the network address. // // Note that gRPC by default performs name resolution on the target passed to // NewClient. To bypass name resolution and cause the target string to be // passed directly to the dialer here instead, use the "passthrough" resolver // by specifying it in the target string, e.g. "passthrough:target". // // Note: All supported releases of Go (as of December 2023) override the OS // defaults for TCP keepalive time and interval to 15s. To enable TCP keepalive // with OS defaults for keepalive time and interval, use a net.Dialer that sets // the KeepAlive field to a negative value, and sets the SO_KEEPALIVE socket // option to true from the Control field. For a concrete example of how to do // this, see internal.NetDialerWithTCPKeepalive(). // // For more information, please see [issue 23459] in the Go GitHub repo. // // [issue 23459]: https://github.com/golang/go/issues/23459 func WithContextDialer(f func(context.Context, string) (net.Conn, error)) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.Dialer = f }) } // WithDialer returns a DialOption that specifies a function to use for dialing // network addresses. If FailOnNonTempDialError() is set to true, and an error // is returned by f, gRPC checks the error's Temporary() method to decide if it // should try to reconnect to the network address. // // Deprecated: use WithContextDialer instead. Will be supported throughout // 1.x. func WithDialer(f func(string, time.Duration) (net.Conn, error)) DialOption { return WithContextDialer( func(ctx context.Context, addr string) (net.Conn, error) { if deadline, ok := ctx.Deadline(); ok { return f(addr, time.Until(deadline)) } return f(addr, 0) }) } // WithStatsHandler returns a DialOption that specifies the stats handler for // all the RPCs and underlying network connections in this ClientConn. func WithStatsHandler(h stats.Handler) DialOption { return newFuncDialOption(func(o *dialOptions) { if h == nil { logger.Error("ignoring nil parameter in grpc.WithStatsHandler ClientOption") // Do not allow a nil stats handler, which would otherwise cause // panics. return } o.copts.StatsHandlers = append(o.copts.StatsHandlers, h) }) } // withBinaryLogger returns a DialOption that specifies the binary logger for // this ClientConn. func withBinaryLogger(bl binarylog.Logger) DialOption { return newFuncDialOption(func(o *dialOptions) { o.binaryLogger = bl }) } // FailOnNonTempDialError returns a DialOption that specifies if gRPC fails on // non-temporary dial errors. If f is true, and dialer returns a non-temporary // error, gRPC will fail the connection to the network address and won't try to // reconnect. The default value of FailOnNonTempDialError is false. // // FailOnNonTempDialError only affects the initial dial, and does not do // anything useful unless you are also using WithBlock(). // // Use of this feature is not recommended. For more information, please see: // https://github.com/grpc/grpc-go/blob/master/Documentation/anti-patterns.md // // Deprecated: this DialOption is not supported by NewClient. // This API may be changed or removed in a // later release. func FailOnNonTempDialError(f bool) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.FailOnNonTempDialError = f }) } // WithUserAgent returns a DialOption that specifies a user agent string for all // the RPCs. func WithUserAgent(s string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.UserAgent = s + " " + grpcUA }) } // WithKeepaliveParams returns a DialOption that specifies keepalive parameters // for the client transport. // // Keepalive is disabled by default. func WithKeepaliveParams(kp keepalive.ClientParameters) DialOption { if kp.Time < internal.KeepaliveMinPingTime { logger.Warningf("Adjusting keepalive ping interval to minimum period of %v", internal.KeepaliveMinPingTime) kp.Time = internal.KeepaliveMinPingTime } return newFuncDialOption(func(o *dialOptions) { o.copts.KeepaliveParams = kp }) } // WithUnaryInterceptor returns a DialOption that specifies the interceptor for // unary RPCs. func WithUnaryInterceptor(f UnaryClientInterceptor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.unaryInt = f }) } // WithChainUnaryInterceptor returns a DialOption that specifies the chained // interceptor for unary RPCs. The first interceptor will be the outer most, // while the last interceptor will be the inner most wrapper around the real call. // All interceptors added by this method will be chained, and the interceptor // defined by WithUnaryInterceptor will always be prepended to the chain. func WithChainUnaryInterceptor(interceptors ...UnaryClientInterceptor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.chainUnaryInts = append(o.chainUnaryInts, interceptors...) }) } // WithStreamInterceptor returns a DialOption that specifies the interceptor for // streaming RPCs. func WithStreamInterceptor(f StreamClientInterceptor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.streamInt = f }) } // WithChainStreamInterceptor returns a DialOption that specifies the chained // interceptor for streaming RPCs. The first interceptor will be the outer most, // while the last interceptor will be the inner most wrapper around the real call. // All interceptors added by this method will be chained, and the interceptor // defined by WithStreamInterceptor will always be prepended to the chain. func WithChainStreamInterceptor(interceptors ...StreamClientInterceptor) DialOption { return newFuncDialOption(func(o *dialOptions) { o.chainStreamInts = append(o.chainStreamInts, interceptors...) }) } // WithAuthority returns a DialOption that specifies the value to be used as the // :authority pseudo-header and as the server name in authentication handshake. func WithAuthority(a string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.authority = a }) } // WithChannelzParentID returns a DialOption that specifies the channelz ID of // current ClientConn's parent. This function is used in nested channel creation // (e.g. grpclb dial). // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithChannelzParentID(c channelz.Identifier) DialOption { return newFuncDialOption(func(o *dialOptions) { o.channelzParent = c }) } // WithDisableServiceConfig returns a DialOption that causes gRPC to ignore any // service config provided by the resolver and provides a hint to the resolver // to not fetch service configs. // // Note that this dial option only disables service config from resolver. If // default service config is provided, gRPC will use the default service config. func WithDisableServiceConfig() DialOption { return newFuncDialOption(func(o *dialOptions) { o.disableServiceConfig = true }) } // WithDefaultServiceConfig returns a DialOption that configures the default // service config, which will be used in cases where: // // 1. WithDisableServiceConfig is also used, or // // 2. The name resolver does not provide a service config or provides an // invalid service config. // // The parameter s is the JSON representation of the default service config. // For more information about service configs, see: // https://github.com/grpc/grpc/blob/master/doc/service_config.md // For a simple example of usage, see: // examples/features/load_balancing/client/main.go func WithDefaultServiceConfig(s string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.defaultServiceConfigRawJSON = &s }) } // WithDisableRetry returns a DialOption that disables retries, even if the // service config enables them. This does not impact transparent retries, which // will happen automatically if no data is written to the wire or if the RPC is // unprocessed by the remote server. func WithDisableRetry() DialOption { return newFuncDialOption(func(o *dialOptions) { o.disableRetry = true }) } // MaxHeaderListSizeDialOption is a DialOption that specifies the maximum // (uncompressed) size of header list that the client is prepared to accept. type MaxHeaderListSizeDialOption struct { MaxHeaderListSize uint32 } func (o MaxHeaderListSizeDialOption) apply(do *dialOptions) { do.copts.MaxHeaderListSize = &o.MaxHeaderListSize } // WithMaxHeaderListSize returns a DialOption that specifies the maximum // (uncompressed) size of header list that the client is prepared to accept. func WithMaxHeaderListSize(s uint32) DialOption { return MaxHeaderListSizeDialOption{ MaxHeaderListSize: s, } } // WithDisableHealthCheck disables the LB channel health checking for all // SubConns of this ClientConn. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithDisableHealthCheck() DialOption { return newFuncDialOption(func(o *dialOptions) { o.disableHealthCheck = true }) } func defaultDialOptions() dialOptions { return dialOptions{ copts: transport.ConnectOptions{ ReadBufferSize: defaultReadBufSize, WriteBufferSize: defaultWriteBufSize, UserAgent: grpcUA, BufferPool: mem.DefaultBufferPool(), }, bs: internalbackoff.DefaultExponential, idleTimeout: 30 * time.Minute, defaultScheme: "dns", maxCallAttempts: defaultMaxCallAttempts, useProxy: true, enableLocalDNSResolution: false, } } // withMinConnectDeadline specifies the function that clientconn uses to // get minConnectDeadline. This can be used to make connection attempts happen // faster/slower. // // For testing purpose only. func withMinConnectDeadline(f func() time.Duration) DialOption { return newFuncDialOption(func(o *dialOptions) { o.minConnectTimeout = f }) } // withDefaultScheme is used to allow Dial to use "passthrough" as the default // name resolver, while NewClient uses "dns" otherwise. func withDefaultScheme(s string) DialOption { return newFuncDialOption(func(o *dialOptions) { o.defaultScheme = s }) } // WithResolvers allows a list of resolver implementations to be registered // locally with the ClientConn without needing to be globally registered via // resolver.Register. They will be matched against the scheme used for the // current Dial only, and will take precedence over the global registry. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithResolvers(rs ...resolver.Builder) DialOption { return newFuncDialOption(func(o *dialOptions) { o.resolvers = append(o.resolvers, rs...) }) } // WithIdleTimeout returns a DialOption that configures an idle timeout for the // channel. If the channel is idle for the configured timeout, i.e there are no // ongoing RPCs and no new RPCs are initiated, the channel will enter idle mode // and as a result the name resolver and load balancer will be shut down. The // channel will exit idle mode when the Connect() method is called or when an // RPC is initiated. // // A default timeout of 30 minutes will be used if this dial option is not set // at dial time and idleness can be disabled by passing a timeout of zero. // // # Experimental // // Notice: This API is EXPERIMENTAL and may be changed or removed in a // later release. func WithIdleTimeout(d time.Duration) DialOption { return newFuncDialOption(func(o *dialOptions) { o.idleTimeout = d }) } // WithMaxCallAttempts returns a DialOption that configures the maximum number // of attempts per call (including retries and hedging) using the channel. // Service owners may specify a higher value for these parameters, but higher // values will be treated as equal to the maximum value by the client // implementation. This mitigates security concerns related to the service // config being transferred to the client via DNS. // // A value of 5 will be used if this dial option is not set or n < 2. func WithMaxCallAttempts(n int) DialOption { return newFuncDialOption(func(o *dialOptions) { if n < 2 { n = defaultMaxCallAttempts } o.maxCallAttempts = n }) } func withBufferPool(bufferPool mem.BufferPool) DialOption { return newFuncDialOption(func(o *dialOptions) { o.copts.BufferPool = bufferPool }) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codec.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/codec.go
/* * * Copyright 2014 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package grpc import ( "google.golang.org/grpc/encoding" _ "google.golang.org/grpc/encoding/proto" // to register the Codec for "proto" "google.golang.org/grpc/mem" ) // baseCodec captures the new encoding.CodecV2 interface without the Name // function, allowing it to be implemented by older Codec and encoding.Codec // implementations. The omitted Name function is only needed for the register in // the encoding package and is not part of the core functionality. type baseCodec interface { Marshal(v any) (mem.BufferSlice, error) Unmarshal(data mem.BufferSlice, v any) error } // getCodec returns an encoding.CodecV2 for the codec of the given name (if // registered). Initially checks the V2 registry with encoding.GetCodecV2 and // returns the V2 codec if it is registered. Otherwise, it checks the V1 registry // with encoding.GetCodec and if it is registered wraps it with newCodecV1Bridge // to turn it into an encoding.CodecV2. Returns nil otherwise. func getCodec(name string) encoding.CodecV2 { if codecV1 := encoding.GetCodec(name); codecV1 != nil { return newCodecV1Bridge(codecV1) } return encoding.GetCodecV2(name) } func newCodecV0Bridge(c Codec) baseCodec { return codecV0Bridge{codec: c} } func newCodecV1Bridge(c encoding.Codec) encoding.CodecV2 { return codecV1Bridge{ codecV0Bridge: codecV0Bridge{codec: c}, name: c.Name(), } } var _ baseCodec = codecV0Bridge{} type codecV0Bridge struct { codec interface { Marshal(v any) ([]byte, error) Unmarshal(data []byte, v any) error } } func (c codecV0Bridge) Marshal(v any) (mem.BufferSlice, error) { data, err := c.codec.Marshal(v) if err != nil { return nil, err } return mem.BufferSlice{mem.SliceBuffer(data)}, nil } func (c codecV0Bridge) Unmarshal(data mem.BufferSlice, v any) (err error) { return c.codec.Unmarshal(data.Materialize(), v) } var _ encoding.CodecV2 = codecV1Bridge{} type codecV1Bridge struct { codecV0Bridge name string } func (c codecV1Bridge) Name() string { return c.name } // Codec defines the interface gRPC uses to encode and decode messages. // Note that implementations of this interface must be thread safe; // a Codec's methods can be called from concurrent goroutines. // // Deprecated: use encoding.Codec instead. type Codec interface { // Marshal returns the wire format of v. Marshal(v any) ([]byte, error) // Unmarshal parses the wire format into v. Unmarshal(data []byte, v any) error // String returns the name of the Codec implementation. This is unused by // gRPC. String() string }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/serviceconfig/serviceconfig.go
/* * * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package serviceconfig defines types and methods for operating on gRPC // service configs. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. package serviceconfig // Config represents an opaque data structure holding a service config. type Config interface { isServiceConfig() } // LoadBalancingConfig represents an opaque data structure holding a load // balancing config. type LoadBalancingConfig interface { isLoadBalancingConfig() } // ParseResult contains a service config or an error. Exactly one must be // non-nil. type ParseResult struct { Config Config Err error }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false
kubev2v/forklift
https://github.com/kubev2v/forklift/blob/b3b4703e958c25d54c4d48138d9e80ae32fadac3/cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/encoding.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/grpc/encoding/encoding.go
/* * * Copyright 2017 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ // Package encoding defines the interface for the compressor and codec, and // functions to register and retrieve compressors and codecs. // // # Experimental // // Notice: This package is EXPERIMENTAL and may be changed or removed in a // later release. package encoding import ( "io" "strings" "google.golang.org/grpc/internal/grpcutil" ) // Identity specifies the optional encoding for uncompressed streams. // It is intended for grpc internal use only. const Identity = "identity" // Compressor is used for compressing and decompressing when sending or // receiving messages. // // If a Compressor implements `DecompressedSize(compressedBytes []byte) int`, // gRPC will invoke it to determine the size of the buffer allocated for the // result of decompression. A return value of -1 indicates unknown size. type Compressor interface { // Compress writes the data written to wc to w after compressing it. If an // error occurs while initializing the compressor, that error is returned // instead. Compress(w io.Writer) (io.WriteCloser, error) // Decompress reads data from r, decompresses it, and provides the // uncompressed data via the returned io.Reader. If an error occurs while // initializing the decompressor, that error is returned instead. Decompress(r io.Reader) (io.Reader, error) // Name is the name of the compression codec and is used to set the content // coding header. The result must be static; the result cannot change // between calls. Name() string } var registeredCompressor = make(map[string]Compressor) // RegisterCompressor registers the compressor with gRPC by its name. It can // be activated when sending an RPC via grpc.UseCompressor(). It will be // automatically accessed when receiving a message based on the content coding // header. Servers also use it to send a response with the same encoding as // the request. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Compressors are // registered with the same name, the one registered last will take effect. func RegisterCompressor(c Compressor) { registeredCompressor[c.Name()] = c if !grpcutil.IsCompressorNameRegistered(c.Name()) { grpcutil.RegisteredCompressorNames = append(grpcutil.RegisteredCompressorNames, c.Name()) } } // GetCompressor returns Compressor for the given compressor name. func GetCompressor(name string) Compressor { return registeredCompressor[name] } // Codec defines the interface gRPC uses to encode and decode messages. Note // that implementations of this interface must be thread safe; a Codec's // methods can be called from concurrent goroutines. type Codec interface { // Marshal returns the wire format of v. Marshal(v any) ([]byte, error) // Unmarshal parses the wire format into v. Unmarshal(data []byte, v any) error // Name returns the name of the Codec implementation. The returned string // will be used as part of content type in transmission. The result must be // static; the result cannot change between calls. Name() string } var registeredCodecs = make(map[string]any) // RegisterCodec registers the provided Codec for use with all gRPC clients and // servers. // // The Codec will be stored and looked up by result of its Name() method, which // should match the content-subtype of the encoding handled by the Codec. This // is case-insensitive, and is stored and looked up as lowercase. If the // result of calling Name() is an empty string, RegisterCodec will panic. See // Content-Type on // https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests for // more details. // // NOTE: this function must only be called during initialization time (i.e. in // an init() function), and is not thread-safe. If multiple Codecs are // registered with the same name, the one registered last will take effect. func RegisterCodec(codec Codec) { if codec == nil { panic("cannot register a nil Codec") } if codec.Name() == "" { panic("cannot register Codec with empty string result for Name()") } contentSubtype := strings.ToLower(codec.Name()) registeredCodecs[contentSubtype] = codec } // GetCodec gets a registered Codec by content-subtype, or nil if no Codec is // registered for the content-subtype. // // The content-subtype is expected to be lowercase. func GetCodec(contentSubtype string) Codec { c, _ := registeredCodecs[contentSubtype].(Codec) return c }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false