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/go.uber.org/zap/zapcore/marshaler.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/marshaler.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore // ObjectMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). // // Note: ObjectMarshaler is only used when zap.Object is used or when // passed directly to zap.Any. It is not used when reflection-based // encoding is used. type ObjectMarshaler interface { MarshalLogObject(ObjectEncoder) error } // ObjectMarshalerFunc is a type adapter that turns a function into an // ObjectMarshaler. type ObjectMarshalerFunc func(ObjectEncoder) error // MarshalLogObject calls the underlying function. func (f ObjectMarshalerFunc) MarshalLogObject(enc ObjectEncoder) error { return f(enc) } // ArrayMarshaler allows user-defined types to efficiently add themselves to the // logging context, and to selectively omit information which shouldn't be // included in logs (e.g., passwords). // // Note: ArrayMarshaler is only used when zap.Array is used or when // passed directly to zap.Any. It is not used when reflection-based // encoding is used. type ArrayMarshaler interface { MarshalLogArray(ArrayEncoder) error } // ArrayMarshalerFunc is a type adapter that turns a function into an // ArrayMarshaler. type ArrayMarshalerFunc func(ArrayEncoder) error // MarshalLogArray calls the underlying function. func (f ArrayMarshalerFunc) MarshalLogArray(enc ArrayEncoder) error { return f(enc) }
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/go.uber.org/zap/zapcore/reflected_encoder.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/reflected_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "encoding/json" "io" ) // ReflectedEncoder serializes log fields that can't be serialized with Zap's // JSON encoder. These have the ReflectType field type. // Use EncoderConfig.NewReflectedEncoder to set this. type ReflectedEncoder interface { // Encode encodes and writes to the underlying data stream. Encode(interface{}) error } func defaultReflectedEncoder(w io.Writer) ReflectedEncoder { enc := json.NewEncoder(w) // For consistency with our custom JSON encoder. enc.SetEscapeHTML(false) return enc }
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/go.uber.org/zap/zapcore/json_encoder.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/json_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "encoding/base64" "math" "time" "unicode/utf8" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) // For JSON-escaping; see jsonEncoder.safeAddString below. const _hex = "0123456789abcdef" var _jsonPool = pool.New(func() *jsonEncoder { return &jsonEncoder{} }) func putJSONEncoder(enc *jsonEncoder) { if enc.reflectBuf != nil { enc.reflectBuf.Free() } enc.EncoderConfig = nil enc.buf = nil enc.spaced = false enc.openNamespaces = 0 enc.reflectBuf = nil enc.reflectEnc = nil _jsonPool.Put(enc) } type jsonEncoder struct { *EncoderConfig buf *buffer.Buffer spaced bool // include spaces after colons and commas openNamespaces int // for encoding generic values by reflection reflectBuf *buffer.Buffer reflectEnc ReflectedEncoder } // NewJSONEncoder creates a fast, low-allocation JSON encoder. The encoder // appropriately escapes all field keys and values. // // Note that the encoder doesn't deduplicate keys, so it's possible to produce // a message like // // {"foo":"bar","foo":"baz"} // // This is permitted by the JSON specification, but not encouraged. Many // libraries will ignore duplicate key-value pairs (typically keeping the last // pair) when unmarshaling, but users should attempt to avoid adding duplicate // keys. func NewJSONEncoder(cfg EncoderConfig) Encoder { return newJSONEncoder(cfg, false) } func newJSONEncoder(cfg EncoderConfig, spaced bool) *jsonEncoder { if cfg.SkipLineEnding { cfg.LineEnding = "" } else if cfg.LineEnding == "" { cfg.LineEnding = DefaultLineEnding } // If no EncoderConfig.NewReflectedEncoder is provided by the user, then use default if cfg.NewReflectedEncoder == nil { cfg.NewReflectedEncoder = defaultReflectedEncoder } return &jsonEncoder{ EncoderConfig: &cfg, buf: bufferpool.Get(), spaced: spaced, } } func (enc *jsonEncoder) AddArray(key string, arr ArrayMarshaler) error { enc.addKey(key) return enc.AppendArray(arr) } func (enc *jsonEncoder) AddObject(key string, obj ObjectMarshaler) error { enc.addKey(key) return enc.AppendObject(obj) } func (enc *jsonEncoder) AddBinary(key string, val []byte) { enc.AddString(key, base64.StdEncoding.EncodeToString(val)) } func (enc *jsonEncoder) AddByteString(key string, val []byte) { enc.addKey(key) enc.AppendByteString(val) } func (enc *jsonEncoder) AddBool(key string, val bool) { enc.addKey(key) enc.AppendBool(val) } func (enc *jsonEncoder) AddComplex128(key string, val complex128) { enc.addKey(key) enc.AppendComplex128(val) } func (enc *jsonEncoder) AddComplex64(key string, val complex64) { enc.addKey(key) enc.AppendComplex64(val) } func (enc *jsonEncoder) AddDuration(key string, val time.Duration) { enc.addKey(key) enc.AppendDuration(val) } func (enc *jsonEncoder) AddFloat64(key string, val float64) { enc.addKey(key) enc.AppendFloat64(val) } func (enc *jsonEncoder) AddFloat32(key string, val float32) { enc.addKey(key) enc.AppendFloat32(val) } func (enc *jsonEncoder) AddInt64(key string, val int64) { enc.addKey(key) enc.AppendInt64(val) } func (enc *jsonEncoder) resetReflectBuf() { if enc.reflectBuf == nil { enc.reflectBuf = bufferpool.Get() enc.reflectEnc = enc.NewReflectedEncoder(enc.reflectBuf) } else { enc.reflectBuf.Reset() } } var nullLiteralBytes = []byte("null") // Only invoke the standard JSON encoder if there is actually something to // encode; otherwise write JSON null literal directly. func (enc *jsonEncoder) encodeReflected(obj interface{}) ([]byte, error) { if obj == nil { return nullLiteralBytes, nil } enc.resetReflectBuf() if err := enc.reflectEnc.Encode(obj); err != nil { return nil, err } enc.reflectBuf.TrimNewline() return enc.reflectBuf.Bytes(), nil } func (enc *jsonEncoder) AddReflected(key string, obj interface{}) error { valueBytes, err := enc.encodeReflected(obj) if err != nil { return err } enc.addKey(key) _, err = enc.buf.Write(valueBytes) return err } func (enc *jsonEncoder) OpenNamespace(key string) { enc.addKey(key) enc.buf.AppendByte('{') enc.openNamespaces++ } func (enc *jsonEncoder) AddString(key, val string) { enc.addKey(key) enc.AppendString(val) } func (enc *jsonEncoder) AddTime(key string, val time.Time) { enc.addKey(key) enc.AppendTime(val) } func (enc *jsonEncoder) AddUint64(key string, val uint64) { enc.addKey(key) enc.AppendUint64(val) } func (enc *jsonEncoder) AppendArray(arr ArrayMarshaler) error { enc.addElementSeparator() enc.buf.AppendByte('[') err := arr.MarshalLogArray(enc) enc.buf.AppendByte(']') return err } func (enc *jsonEncoder) AppendObject(obj ObjectMarshaler) error { // Close ONLY new openNamespaces that are created during // AppendObject(). old := enc.openNamespaces enc.openNamespaces = 0 enc.addElementSeparator() enc.buf.AppendByte('{') err := obj.MarshalLogObject(enc) enc.buf.AppendByte('}') enc.closeOpenNamespaces() enc.openNamespaces = old return err } func (enc *jsonEncoder) AppendBool(val bool) { enc.addElementSeparator() enc.buf.AppendBool(val) } func (enc *jsonEncoder) AppendByteString(val []byte) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddByteString(val) enc.buf.AppendByte('"') } // appendComplex appends the encoded form of the provided complex128 value. // precision specifies the encoding precision for the real and imaginary // components of the complex number. func (enc *jsonEncoder) appendComplex(val complex128, precision int) { enc.addElementSeparator() // Cast to a platform-independent, fixed-size type. r, i := float64(real(val)), float64(imag(val)) enc.buf.AppendByte('"') // Because we're always in a quoted string, we can use strconv without // special-casing NaN and +/-Inf. enc.buf.AppendFloat(r, precision) // If imaginary part is less than 0, minus (-) sign is added by default // by AppendFloat. if i >= 0 { enc.buf.AppendByte('+') } enc.buf.AppendFloat(i, precision) enc.buf.AppendByte('i') enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendDuration(val time.Duration) { cur := enc.buf.Len() if e := enc.EncodeDuration; e != nil { e(val, enc) } if cur == enc.buf.Len() { // User-supplied EncodeDuration is a no-op. Fall back to nanoseconds to keep // JSON valid. enc.AppendInt64(int64(val)) } } func (enc *jsonEncoder) AppendInt64(val int64) { enc.addElementSeparator() enc.buf.AppendInt(val) } func (enc *jsonEncoder) AppendReflected(val interface{}) error { valueBytes, err := enc.encodeReflected(val) if err != nil { return err } enc.addElementSeparator() _, err = enc.buf.Write(valueBytes) return err } func (enc *jsonEncoder) AppendString(val string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddString(val) enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendTimeLayout(time time.Time, layout string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.buf.AppendTime(time, layout) enc.buf.AppendByte('"') } func (enc *jsonEncoder) AppendTime(val time.Time) { cur := enc.buf.Len() if e := enc.EncodeTime; e != nil { e(val, enc) } if cur == enc.buf.Len() { // User-supplied EncodeTime is a no-op. Fall back to nanos since epoch to keep // output JSON valid. enc.AppendInt64(val.UnixNano()) } } func (enc *jsonEncoder) AppendUint64(val uint64) { enc.addElementSeparator() enc.buf.AppendUint(val) } func (enc *jsonEncoder) AddInt(k string, v int) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt32(k string, v int32) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt16(k string, v int16) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddInt8(k string, v int8) { enc.AddInt64(k, int64(v)) } func (enc *jsonEncoder) AddUint(k string, v uint) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint32(k string, v uint32) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint16(k string, v uint16) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUint8(k string, v uint8) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AddUintptr(k string, v uintptr) { enc.AddUint64(k, uint64(v)) } func (enc *jsonEncoder) AppendComplex64(v complex64) { enc.appendComplex(complex128(v), 32) } func (enc *jsonEncoder) AppendComplex128(v complex128) { enc.appendComplex(complex128(v), 64) } func (enc *jsonEncoder) AppendFloat64(v float64) { enc.appendFloat(v, 64) } func (enc *jsonEncoder) AppendFloat32(v float32) { enc.appendFloat(float64(v), 32) } func (enc *jsonEncoder) AppendInt(v int) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt32(v int32) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt16(v int16) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendInt8(v int8) { enc.AppendInt64(int64(v)) } func (enc *jsonEncoder) AppendUint(v uint) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint32(v uint32) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint16(v uint16) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUint8(v uint8) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) AppendUintptr(v uintptr) { enc.AppendUint64(uint64(v)) } func (enc *jsonEncoder) Clone() Encoder { clone := enc.clone() clone.buf.Write(enc.buf.Bytes()) return clone } func (enc *jsonEncoder) clone() *jsonEncoder { clone := _jsonPool.Get() clone.EncoderConfig = enc.EncoderConfig clone.spaced = enc.spaced clone.openNamespaces = enc.openNamespaces clone.buf = bufferpool.Get() return clone } func (enc *jsonEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { final := enc.clone() final.buf.AppendByte('{') if final.LevelKey != "" && final.EncodeLevel != nil { final.addKey(final.LevelKey) cur := final.buf.Len() final.EncodeLevel(ent.Level, final) if cur == final.buf.Len() { // User-supplied EncodeLevel was a no-op. Fall back to strings to keep // output JSON valid. final.AppendString(ent.Level.String()) } } if final.TimeKey != "" && !ent.Time.IsZero() { final.AddTime(final.TimeKey, ent.Time) } if ent.LoggerName != "" && final.NameKey != "" { final.addKey(final.NameKey) cur := final.buf.Len() nameEncoder := final.EncodeName // if no name encoder provided, fall back to FullNameEncoder for backwards // compatibility if nameEncoder == nil { nameEncoder = FullNameEncoder } nameEncoder(ent.LoggerName, final) if cur == final.buf.Len() { // User-supplied EncodeName was a no-op. Fall back to strings to // keep output JSON valid. final.AppendString(ent.LoggerName) } } if ent.Caller.Defined { if final.CallerKey != "" { final.addKey(final.CallerKey) cur := final.buf.Len() final.EncodeCaller(ent.Caller, final) if cur == final.buf.Len() { // User-supplied EncodeCaller was a no-op. Fall back to strings to // keep output JSON valid. final.AppendString(ent.Caller.String()) } } if final.FunctionKey != "" { final.addKey(final.FunctionKey) final.AppendString(ent.Caller.Function) } } if final.MessageKey != "" { final.addKey(enc.MessageKey) final.AppendString(ent.Message) } if enc.buf.Len() > 0 { final.addElementSeparator() final.buf.Write(enc.buf.Bytes()) } addFields(final, fields) final.closeOpenNamespaces() if ent.Stack != "" && final.StacktraceKey != "" { final.AddString(final.StacktraceKey, ent.Stack) } final.buf.AppendByte('}') final.buf.AppendString(final.LineEnding) ret := final.buf putJSONEncoder(final) return ret, nil } func (enc *jsonEncoder) truncate() { enc.buf.Reset() } func (enc *jsonEncoder) closeOpenNamespaces() { for i := 0; i < enc.openNamespaces; i++ { enc.buf.AppendByte('}') } enc.openNamespaces = 0 } func (enc *jsonEncoder) addKey(key string) { enc.addElementSeparator() enc.buf.AppendByte('"') enc.safeAddString(key) enc.buf.AppendByte('"') enc.buf.AppendByte(':') if enc.spaced { enc.buf.AppendByte(' ') } } func (enc *jsonEncoder) addElementSeparator() { last := enc.buf.Len() - 1 if last < 0 { return } switch enc.buf.Bytes()[last] { case '{', '[', ':', ',', ' ': return default: enc.buf.AppendByte(',') if enc.spaced { enc.buf.AppendByte(' ') } } } func (enc *jsonEncoder) appendFloat(val float64, bitSize int) { enc.addElementSeparator() switch { case math.IsNaN(val): enc.buf.AppendString(`"NaN"`) case math.IsInf(val, 1): enc.buf.AppendString(`"+Inf"`) case math.IsInf(val, -1): enc.buf.AppendString(`"-Inf"`) default: enc.buf.AppendFloat(val, bitSize) } } // safeAddString JSON-escapes a string and appends it to the internal buffer. // Unlike the standard library's encoder, it doesn't attempt to protect the // user from browser vulnerabilities or JSONP-related problems. func (enc *jsonEncoder) safeAddString(s string) { safeAppendStringLike( (*buffer.Buffer).AppendString, utf8.DecodeRuneInString, enc.buf, s, ) } // safeAddByteString is no-alloc equivalent of safeAddString(string(s)) for s []byte. func (enc *jsonEncoder) safeAddByteString(s []byte) { safeAppendStringLike( (*buffer.Buffer).AppendBytes, utf8.DecodeRune, enc.buf, s, ) } // safeAppendStringLike is a generic implementation of safeAddString and safeAddByteString. // It appends a string or byte slice to the buffer, escaping all special characters. func safeAppendStringLike[S []byte | string]( // appendTo appends this string-like object to the buffer. appendTo func(*buffer.Buffer, S), // decodeRune decodes the next rune from the string-like object // and returns its value and width in bytes. decodeRune func(S) (rune, int), buf *buffer.Buffer, s S, ) { // The encoding logic below works by skipping over characters // that can be safely copied as-is, // until a character is found that needs special handling. // At that point, we copy everything we've seen so far, // and then handle that special character. // // last is the index of the last byte that was copied to the buffer. last := 0 for i := 0; i < len(s); { if s[i] >= utf8.RuneSelf { // Character >= RuneSelf may be part of a multi-byte rune. // They need to be decoded before we can decide how to handle them. r, size := decodeRune(s[i:]) if r != utf8.RuneError || size != 1 { // No special handling required. // Skip over this rune and continue. i += size continue } // Invalid UTF-8 sequence. // Replace it with the Unicode replacement character. appendTo(buf, s[last:i]) buf.AppendString(`\ufffd`) i++ last = i } else { // Character < RuneSelf is a single-byte UTF-8 rune. if s[i] >= 0x20 && s[i] != '\\' && s[i] != '"' { // No escaping necessary. // Skip over this character and continue. i++ continue } // This character needs to be escaped. appendTo(buf, s[last:i]) switch s[i] { case '\\', '"': buf.AppendByte('\\') buf.AppendByte(s[i]) case '\n': buf.AppendByte('\\') buf.AppendByte('n') case '\r': buf.AppendByte('\\') buf.AppendByte('r') case '\t': buf.AppendByte('\\') buf.AppendByte('t') default: // Encode bytes < 0x20, except for the escape sequences above. buf.AppendString(`\u00`) buf.AppendByte(_hex[s[i]>>4]) buf.AppendByte(_hex[s[i]&0xF]) } i++ last = i } } // add remaining appendTo(buf, s[last:]) }
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/go.uber.org/zap/zapcore/field.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/field.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "bytes" "fmt" "math" "reflect" "time" ) // A FieldType indicates which member of the Field union struct should be used // and how it should be serialized. type FieldType uint8 const ( // UnknownType is the default field type. Attempting to add it to an encoder will panic. UnknownType FieldType = iota // ArrayMarshalerType indicates that the field carries an ArrayMarshaler. ArrayMarshalerType // ObjectMarshalerType indicates that the field carries an ObjectMarshaler. ObjectMarshalerType // BinaryType indicates that the field carries an opaque binary blob. BinaryType // BoolType indicates that the field carries a bool. BoolType // ByteStringType indicates that the field carries UTF-8 encoded bytes. ByteStringType // Complex128Type indicates that the field carries a complex128. Complex128Type // Complex64Type indicates that the field carries a complex64. Complex64Type // DurationType indicates that the field carries a time.Duration. DurationType // Float64Type indicates that the field carries a float64. Float64Type // Float32Type indicates that the field carries a float32. Float32Type // Int64Type indicates that the field carries an int64. Int64Type // Int32Type indicates that the field carries an int32. Int32Type // Int16Type indicates that the field carries an int16. Int16Type // Int8Type indicates that the field carries an int8. Int8Type // StringType indicates that the field carries a string. StringType // TimeType indicates that the field carries a time.Time that is // representable by a UnixNano() stored as an int64. TimeType // TimeFullType indicates that the field carries a time.Time stored as-is. TimeFullType // Uint64Type indicates that the field carries a uint64. Uint64Type // Uint32Type indicates that the field carries a uint32. Uint32Type // Uint16Type indicates that the field carries a uint16. Uint16Type // Uint8Type indicates that the field carries a uint8. Uint8Type // UintptrType indicates that the field carries a uintptr. UintptrType // ReflectType indicates that the field carries an interface{}, which should // be serialized using reflection. ReflectType // NamespaceType signals the beginning of an isolated namespace. All // subsequent fields should be added to the new namespace. NamespaceType // StringerType indicates that the field carries a fmt.Stringer. StringerType // ErrorType indicates that the field carries an error. ErrorType // SkipType indicates that the field is a no-op. SkipType // InlineMarshalerType indicates that the field carries an ObjectMarshaler // that should be inlined. InlineMarshalerType ) // A Field is a marshaling operation used to add a key-value pair to a logger's // context. Most fields are lazily marshaled, so it's inexpensive to add fields // to disabled debug-level log statements. type Field struct { Key string Type FieldType Integer int64 String string Interface interface{} } // AddTo exports a field through the ObjectEncoder interface. It's primarily // useful to library authors, and shouldn't be necessary in most applications. func (f Field) AddTo(enc ObjectEncoder) { var err error switch f.Type { case ArrayMarshalerType: err = enc.AddArray(f.Key, f.Interface.(ArrayMarshaler)) case ObjectMarshalerType: err = enc.AddObject(f.Key, f.Interface.(ObjectMarshaler)) case InlineMarshalerType: err = f.Interface.(ObjectMarshaler).MarshalLogObject(enc) case BinaryType: enc.AddBinary(f.Key, f.Interface.([]byte)) case BoolType: enc.AddBool(f.Key, f.Integer == 1) case ByteStringType: enc.AddByteString(f.Key, f.Interface.([]byte)) case Complex128Type: enc.AddComplex128(f.Key, f.Interface.(complex128)) case Complex64Type: enc.AddComplex64(f.Key, f.Interface.(complex64)) case DurationType: enc.AddDuration(f.Key, time.Duration(f.Integer)) case Float64Type: enc.AddFloat64(f.Key, math.Float64frombits(uint64(f.Integer))) case Float32Type: enc.AddFloat32(f.Key, math.Float32frombits(uint32(f.Integer))) case Int64Type: enc.AddInt64(f.Key, f.Integer) case Int32Type: enc.AddInt32(f.Key, int32(f.Integer)) case Int16Type: enc.AddInt16(f.Key, int16(f.Integer)) case Int8Type: enc.AddInt8(f.Key, int8(f.Integer)) case StringType: enc.AddString(f.Key, f.String) case TimeType: if f.Interface != nil { enc.AddTime(f.Key, time.Unix(0, f.Integer).In(f.Interface.(*time.Location))) } else { // Fall back to UTC if location is nil. enc.AddTime(f.Key, time.Unix(0, f.Integer)) } case TimeFullType: enc.AddTime(f.Key, f.Interface.(time.Time)) case Uint64Type: enc.AddUint64(f.Key, uint64(f.Integer)) case Uint32Type: enc.AddUint32(f.Key, uint32(f.Integer)) case Uint16Type: enc.AddUint16(f.Key, uint16(f.Integer)) case Uint8Type: enc.AddUint8(f.Key, uint8(f.Integer)) case UintptrType: enc.AddUintptr(f.Key, uintptr(f.Integer)) case ReflectType: err = enc.AddReflected(f.Key, f.Interface) case NamespaceType: enc.OpenNamespace(f.Key) case StringerType: err = encodeStringer(f.Key, f.Interface, enc) case ErrorType: err = encodeError(f.Key, f.Interface.(error), enc) case SkipType: break default: panic(fmt.Sprintf("unknown field type: %v", f)) } if err != nil { enc.AddString(fmt.Sprintf("%sError", f.Key), err.Error()) } } // Equals returns whether two fields are equal. For non-primitive types such as // errors, marshalers, or reflect types, it uses reflect.DeepEqual. func (f Field) Equals(other Field) bool { if f.Type != other.Type { return false } if f.Key != other.Key { return false } switch f.Type { case BinaryType, ByteStringType: return bytes.Equal(f.Interface.([]byte), other.Interface.([]byte)) case ArrayMarshalerType, ObjectMarshalerType, ErrorType, ReflectType: return reflect.DeepEqual(f.Interface, other.Interface) default: return f == other } } func addFields(enc ObjectEncoder, fields []Field) { for i := range fields { fields[i].AddTo(enc) } } func encodeStringer(key string, stringer interface{}, enc ObjectEncoder) (retErr error) { // Try to capture panics (from nil references or otherwise) when calling // the String() method, similar to https://golang.org/src/fmt/print.go#L540 defer func() { if err := recover(); err != nil { // If it's a nil pointer, just say "<nil>". The likeliest causes are a // Stringer that fails to guard against nil or a nil pointer for a // value receiver, and in either case, "<nil>" is a nice result. if v := reflect.ValueOf(stringer); v.Kind() == reflect.Ptr && v.IsNil() { enc.AddString(key, "<nil>") return } retErr = fmt.Errorf("PANIC=%v", err) } }() enc.AddString(key, stringer.(fmt.Stringer).String()) 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/go.uber.org/zap/zapcore/buffered_write_syncer.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/buffered_write_syncer.go
// Copyright (c) 2021 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "bufio" "sync" "time" "go.uber.org/multierr" ) const ( // _defaultBufferSize specifies the default size used by Buffer. _defaultBufferSize = 256 * 1024 // 256 kB // _defaultFlushInterval specifies the default flush interval for // Buffer. _defaultFlushInterval = 30 * time.Second ) // A BufferedWriteSyncer is a WriteSyncer that buffers writes in-memory before // flushing them to a wrapped WriteSyncer after reaching some limit, or at some // fixed interval--whichever comes first. // // BufferedWriteSyncer is safe for concurrent use. You don't need to use // zapcore.Lock for WriteSyncers with BufferedWriteSyncer. // // To set up a BufferedWriteSyncer, construct a WriteSyncer for your log // destination (*os.File is a valid WriteSyncer), wrap it with // BufferedWriteSyncer, and defer a Stop() call for when you no longer need the // object. // // func main() { // ws := ... // your log destination // bws := &zapcore.BufferedWriteSyncer{WS: ws} // defer bws.Stop() // // // ... // core := zapcore.NewCore(enc, bws, lvl) // logger := zap.New(core) // // // ... // } // // By default, a BufferedWriteSyncer will buffer up to 256 kilobytes of logs, // waiting at most 30 seconds between flushes. // You can customize these parameters by setting the Size or FlushInterval // fields. // For example, the following buffers up to 512 kB of logs before flushing them // to Stderr, with a maximum of one minute between each flush. // // ws := &BufferedWriteSyncer{ // WS: os.Stderr, // Size: 512 * 1024, // 512 kB // FlushInterval: time.Minute, // } // defer ws.Stop() type BufferedWriteSyncer struct { // WS is the WriteSyncer around which BufferedWriteSyncer will buffer // writes. // // This field is required. WS WriteSyncer // Size specifies the maximum amount of data the writer will buffered // before flushing. // // Defaults to 256 kB if unspecified. Size int // FlushInterval specifies how often the writer should flush data if // there have been no writes. // // Defaults to 30 seconds if unspecified. FlushInterval time.Duration // Clock, if specified, provides control of the source of time for the // writer. // // Defaults to the system clock. Clock Clock // unexported fields for state mu sync.Mutex initialized bool // whether initialize() has run stopped bool // whether Stop() has run writer *bufio.Writer ticker *time.Ticker stop chan struct{} // closed when flushLoop should stop done chan struct{} // closed when flushLoop has stopped } func (s *BufferedWriteSyncer) initialize() { size := s.Size if size == 0 { size = _defaultBufferSize } flushInterval := s.FlushInterval if flushInterval == 0 { flushInterval = _defaultFlushInterval } if s.Clock == nil { s.Clock = DefaultClock } s.ticker = s.Clock.NewTicker(flushInterval) s.writer = bufio.NewWriterSize(s.WS, size) s.stop = make(chan struct{}) s.done = make(chan struct{}) s.initialized = true go s.flushLoop() } // Write writes log data into buffer syncer directly, multiple Write calls will be batched, // and log data will be flushed to disk when the buffer is full or periodically. func (s *BufferedWriteSyncer) Write(bs []byte) (int, error) { s.mu.Lock() defer s.mu.Unlock() if !s.initialized { s.initialize() } // To avoid partial writes from being flushed, we manually flush the existing buffer if: // * The current write doesn't fit into the buffer fully, and // * The buffer is not empty (since bufio will not split large writes when the buffer is empty) if len(bs) > s.writer.Available() && s.writer.Buffered() > 0 { if err := s.writer.Flush(); err != nil { return 0, err } } return s.writer.Write(bs) } // Sync flushes buffered log data into disk directly. func (s *BufferedWriteSyncer) Sync() error { s.mu.Lock() defer s.mu.Unlock() var err error if s.initialized { err = s.writer.Flush() } return multierr.Append(err, s.WS.Sync()) } // flushLoop flushes the buffer at the configured interval until Stop is // called. func (s *BufferedWriteSyncer) flushLoop() { defer close(s.done) for { select { case <-s.ticker.C: // we just simply ignore error here // because the underlying bufio writer stores any errors // and we return any error from Sync() as part of the close _ = s.Sync() case <-s.stop: return } } } // Stop closes the buffer, cleans up background goroutines, and flushes // remaining unwritten data. func (s *BufferedWriteSyncer) Stop() (err error) { var stopped bool // Critical section. func() { s.mu.Lock() defer s.mu.Unlock() if !s.initialized { return } stopped = s.stopped if stopped { return } s.stopped = true s.ticker.Stop() close(s.stop) // tell flushLoop to stop <-s.done // and wait until it has }() // Don't call Sync on consecutive Stops. if !stopped { err = s.Sync() } return 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/go.uber.org/zap/zapcore/write_syncer.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/write_syncer.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "io" "sync" "go.uber.org/multierr" ) // A WriteSyncer is an io.Writer that can also flush any buffered data. Note // that *os.File (and thus, os.Stderr and os.Stdout) implement WriteSyncer. type WriteSyncer interface { io.Writer Sync() error } // AddSync converts an io.Writer to a WriteSyncer. It attempts to be // intelligent: if the concrete type of the io.Writer implements WriteSyncer, // we'll use the existing Sync method. If it doesn't, we'll add a no-op Sync. func AddSync(w io.Writer) WriteSyncer { switch w := w.(type) { case WriteSyncer: return w default: return writerWrapper{w} } } type lockedWriteSyncer struct { sync.Mutex ws WriteSyncer } // Lock wraps a WriteSyncer in a mutex to make it safe for concurrent use. In // particular, *os.Files must be locked before use. func Lock(ws WriteSyncer) WriteSyncer { if _, ok := ws.(*lockedWriteSyncer); ok { // no need to layer on another lock return ws } return &lockedWriteSyncer{ws: ws} } func (s *lockedWriteSyncer) Write(bs []byte) (int, error) { s.Lock() n, err := s.ws.Write(bs) s.Unlock() return n, err } func (s *lockedWriteSyncer) Sync() error { s.Lock() err := s.ws.Sync() s.Unlock() return err } type writerWrapper struct { io.Writer } func (w writerWrapper) Sync() error { return nil } type multiWriteSyncer []WriteSyncer // NewMultiWriteSyncer creates a WriteSyncer that duplicates its writes // and sync calls, much like io.MultiWriter. func NewMultiWriteSyncer(ws ...WriteSyncer) WriteSyncer { if len(ws) == 1 { return ws[0] } return multiWriteSyncer(ws) } // See https://golang.org/src/io/multi.go // When not all underlying syncers write the same number of bytes, // the smallest number is returned even though Write() is called on // all of them. func (ws multiWriteSyncer) Write(p []byte) (int, error) { var writeErr error nWritten := 0 for _, w := range ws { n, err := w.Write(p) writeErr = multierr.Append(writeErr, err) if nWritten == 0 && n != 0 { nWritten = n } else if n < nWritten { nWritten = n } } return nWritten, writeErr } func (ws multiWriteSyncer) Sync() error { var err error for _, w := range ws { err = multierr.Append(err, w.Sync()) } return 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/go.uber.org/zap/zapcore/memory_encoder.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/memory_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import "time" // MapObjectEncoder is an ObjectEncoder backed by a simple // map[string]interface{}. It's not fast enough for production use, but it's // helpful in tests. type MapObjectEncoder struct { // Fields contains the entire encoded log context. Fields map[string]interface{} // cur is a pointer to the namespace we're currently writing to. cur map[string]interface{} } // NewMapObjectEncoder creates a new map-backed ObjectEncoder. func NewMapObjectEncoder() *MapObjectEncoder { m := make(map[string]interface{}) return &MapObjectEncoder{ Fields: m, cur: m, } } // AddArray implements ObjectEncoder. func (m *MapObjectEncoder) AddArray(key string, v ArrayMarshaler) error { arr := &sliceArrayEncoder{elems: make([]interface{}, 0)} err := v.MarshalLogArray(arr) m.cur[key] = arr.elems return err } // AddObject implements ObjectEncoder. func (m *MapObjectEncoder) AddObject(k string, v ObjectMarshaler) error { newMap := NewMapObjectEncoder() m.cur[k] = newMap.Fields return v.MarshalLogObject(newMap) } // AddBinary implements ObjectEncoder. func (m *MapObjectEncoder) AddBinary(k string, v []byte) { m.cur[k] = v } // AddByteString implements ObjectEncoder. func (m *MapObjectEncoder) AddByteString(k string, v []byte) { m.cur[k] = string(v) } // AddBool implements ObjectEncoder. func (m *MapObjectEncoder) AddBool(k string, v bool) { m.cur[k] = v } // AddDuration implements ObjectEncoder. func (m MapObjectEncoder) AddDuration(k string, v time.Duration) { m.cur[k] = v } // AddComplex128 implements ObjectEncoder. func (m *MapObjectEncoder) AddComplex128(k string, v complex128) { m.cur[k] = v } // AddComplex64 implements ObjectEncoder. func (m *MapObjectEncoder) AddComplex64(k string, v complex64) { m.cur[k] = v } // AddFloat64 implements ObjectEncoder. func (m *MapObjectEncoder) AddFloat64(k string, v float64) { m.cur[k] = v } // AddFloat32 implements ObjectEncoder. func (m *MapObjectEncoder) AddFloat32(k string, v float32) { m.cur[k] = v } // AddInt implements ObjectEncoder. func (m *MapObjectEncoder) AddInt(k string, v int) { m.cur[k] = v } // AddInt64 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt64(k string, v int64) { m.cur[k] = v } // AddInt32 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt32(k string, v int32) { m.cur[k] = v } // AddInt16 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt16(k string, v int16) { m.cur[k] = v } // AddInt8 implements ObjectEncoder. func (m *MapObjectEncoder) AddInt8(k string, v int8) { m.cur[k] = v } // AddString implements ObjectEncoder. func (m *MapObjectEncoder) AddString(k string, v string) { m.cur[k] = v } // AddTime implements ObjectEncoder. func (m MapObjectEncoder) AddTime(k string, v time.Time) { m.cur[k] = v } // AddUint implements ObjectEncoder. func (m *MapObjectEncoder) AddUint(k string, v uint) { m.cur[k] = v } // AddUint64 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint64(k string, v uint64) { m.cur[k] = v } // AddUint32 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint32(k string, v uint32) { m.cur[k] = v } // AddUint16 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint16(k string, v uint16) { m.cur[k] = v } // AddUint8 implements ObjectEncoder. func (m *MapObjectEncoder) AddUint8(k string, v uint8) { m.cur[k] = v } // AddUintptr implements ObjectEncoder. func (m *MapObjectEncoder) AddUintptr(k string, v uintptr) { m.cur[k] = v } // AddReflected implements ObjectEncoder. func (m *MapObjectEncoder) AddReflected(k string, v interface{}) error { m.cur[k] = v return nil } // OpenNamespace implements ObjectEncoder. func (m *MapObjectEncoder) OpenNamespace(k string) { ns := make(map[string]interface{}) m.cur[k] = ns m.cur = ns } // sliceArrayEncoder is an ArrayEncoder backed by a simple []interface{}. Like // the MapObjectEncoder, it's not designed for production use. type sliceArrayEncoder struct { elems []interface{} } func (s *sliceArrayEncoder) AppendArray(v ArrayMarshaler) error { enc := &sliceArrayEncoder{} err := v.MarshalLogArray(enc) s.elems = append(s.elems, enc.elems) return err } func (s *sliceArrayEncoder) AppendObject(v ObjectMarshaler) error { m := NewMapObjectEncoder() err := v.MarshalLogObject(m) s.elems = append(s.elems, m.Fields) return err } func (s *sliceArrayEncoder) AppendReflected(v interface{}) error { s.elems = append(s.elems, v) return nil } func (s *sliceArrayEncoder) AppendBool(v bool) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendByteString(v []byte) { s.elems = append(s.elems, string(v)) } func (s *sliceArrayEncoder) AppendComplex128(v complex128) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendComplex64(v complex64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendDuration(v time.Duration) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendFloat64(v float64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendFloat32(v float32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt(v int) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt64(v int64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt32(v int32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt16(v int16) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendInt8(v int8) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendString(v string) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendTime(v time.Time) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint(v uint) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint64(v uint64) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint32(v uint32) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint16(v uint16) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUint8(v uint8) { s.elems = append(s.elems, v) } func (s *sliceArrayEncoder) AppendUintptr(v uintptr) { s.elems = append(s.elems, 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/go.uber.org/zap/zapcore/console_encoder.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/console_encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "fmt" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) var _sliceEncoderPool = pool.New(func() *sliceArrayEncoder { return &sliceArrayEncoder{ elems: make([]interface{}, 0, 2), } }) func getSliceEncoder() *sliceArrayEncoder { return _sliceEncoderPool.Get() } func putSliceEncoder(e *sliceArrayEncoder) { e.elems = e.elems[:0] _sliceEncoderPool.Put(e) } type consoleEncoder struct { *jsonEncoder } // NewConsoleEncoder creates an encoder whose output is designed for human - // rather than machine - consumption. It serializes the core log entry data // (message, level, timestamp, etc.) in a plain-text format and leaves the // structured context as JSON. // // Note that although the console encoder doesn't use the keys specified in the // encoder configuration, it will omit any element whose key is set to the empty // string. func NewConsoleEncoder(cfg EncoderConfig) Encoder { if cfg.ConsoleSeparator == "" { // Use a default delimiter of '\t' for backwards compatibility cfg.ConsoleSeparator = "\t" } return consoleEncoder{newJSONEncoder(cfg, true)} } func (c consoleEncoder) Clone() Encoder { return consoleEncoder{c.jsonEncoder.Clone().(*jsonEncoder)} } func (c consoleEncoder) EncodeEntry(ent Entry, fields []Field) (*buffer.Buffer, error) { line := bufferpool.Get() // We don't want the entry's metadata to be quoted and escaped (if it's // encoded as strings), which means that we can't use the JSON encoder. The // simplest option is to use the memory encoder and fmt.Fprint. // // If this ever becomes a performance bottleneck, we can implement // ArrayEncoder for our plain-text format. arr := getSliceEncoder() if c.TimeKey != "" && c.EncodeTime != nil && !ent.Time.IsZero() { c.EncodeTime(ent.Time, arr) } if c.LevelKey != "" && c.EncodeLevel != nil { c.EncodeLevel(ent.Level, arr) } if ent.LoggerName != "" && c.NameKey != "" { nameEncoder := c.EncodeName if nameEncoder == nil { // Fall back to FullNameEncoder for backward compatibility. nameEncoder = FullNameEncoder } nameEncoder(ent.LoggerName, arr) } if ent.Caller.Defined { if c.CallerKey != "" && c.EncodeCaller != nil { c.EncodeCaller(ent.Caller, arr) } if c.FunctionKey != "" { arr.AppendString(ent.Caller.Function) } } for i := range arr.elems { if i > 0 { line.AppendString(c.ConsoleSeparator) } fmt.Fprint(line, arr.elems[i]) } putSliceEncoder(arr) // Add the message itself. if c.MessageKey != "" { c.addSeparatorIfNecessary(line) line.AppendString(ent.Message) } // Add any structured context. c.writeContext(line, fields) // If there's no stacktrace key, honor that; this allows users to force // single-line output. if ent.Stack != "" && c.StacktraceKey != "" { line.AppendByte('\n') line.AppendString(ent.Stack) } line.AppendString(c.LineEnding) return line, nil } func (c consoleEncoder) writeContext(line *buffer.Buffer, extra []Field) { context := c.jsonEncoder.Clone().(*jsonEncoder) defer func() { // putJSONEncoder assumes the buffer is still used, but we write out the buffer so // we can free it. context.buf.Free() putJSONEncoder(context) }() addFields(context, extra) context.closeOpenNamespaces() if context.buf.Len() == 0 { return } c.addSeparatorIfNecessary(line) line.AppendByte('{') line.Write(context.buf.Bytes()) line.AppendByte('}') } func (c consoleEncoder) addSeparatorIfNecessary(line *buffer.Buffer) { if line.Len() > 0 { line.AppendString(c.ConsoleSeparator) } }
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/go.uber.org/zap/zapcore/core.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/core.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore // Core is a minimal, fast logger interface. It's designed for library authors // to wrap in a more user-friendly API. type Core interface { LevelEnabler // With adds structured context to the Core. With([]Field) Core // Check determines whether the supplied Entry should be logged (using the // embedded LevelEnabler and possibly some extra logic). If the entry // should be logged, the Core adds itself to the CheckedEntry and returns // the result. // // Callers must use Check before calling Write. Check(Entry, *CheckedEntry) *CheckedEntry // Write serializes the Entry and any Fields supplied at the log site and // writes them to their destination. // // If called, Write should always log the Entry and Fields; it should not // replicate the logic of Check. Write(Entry, []Field) error // Sync flushes buffered logs (if any). Sync() error } type nopCore struct{} // NewNopCore returns a no-op Core. func NewNopCore() Core { return nopCore{} } func (nopCore) Enabled(Level) bool { return false } func (n nopCore) With([]Field) Core { return n } func (nopCore) Check(_ Entry, ce *CheckedEntry) *CheckedEntry { return ce } func (nopCore) Write(Entry, []Field) error { return nil } func (nopCore) Sync() error { return nil } // NewCore creates a Core that writes logs to a WriteSyncer. func NewCore(enc Encoder, ws WriteSyncer, enab LevelEnabler) Core { return &ioCore{ LevelEnabler: enab, enc: enc, out: ws, } } type ioCore struct { LevelEnabler enc Encoder out WriteSyncer } var ( _ Core = (*ioCore)(nil) _ leveledEnabler = (*ioCore)(nil) ) func (c *ioCore) Level() Level { return LevelOf(c.LevelEnabler) } func (c *ioCore) With(fields []Field) Core { clone := c.clone() addFields(clone.enc, fields) return clone } func (c *ioCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { if c.Enabled(ent.Level) { return ce.AddCore(ent, c) } return ce } func (c *ioCore) Write(ent Entry, fields []Field) error { buf, err := c.enc.EncodeEntry(ent, fields) if err != nil { return err } _, err = c.out.Write(buf.Bytes()) buf.Free() if err != nil { return err } if ent.Level > ErrorLevel { // Since we may be crashing the program, sync the output. // Ignore Sync errors, pending a clean solution to issue #370. _ = c.Sync() } return nil } func (c *ioCore) Sync() error { return c.out.Sync() } func (c *ioCore) clone() *ioCore { return &ioCore{ LevelEnabler: c.LevelEnabler, enc: c.enc.Clone(), out: c.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/go.uber.org/zap/zapcore/clock.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/clock.go
// Copyright (c) 2021 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import "time" // DefaultClock is the default clock used by Zap in operations that require // time. This clock uses the system clock for all operations. var DefaultClock = systemClock{} // Clock is a source of time for logged entries. type Clock interface { // Now returns the current local time. Now() time.Time // NewTicker returns *time.Ticker that holds a channel // that delivers "ticks" of a clock. NewTicker(time.Duration) *time.Ticker } // systemClock implements default Clock that uses system time. type systemClock struct{} func (systemClock) Now() time.Time { return time.Now() } func (systemClock) NewTicker(duration time.Duration) *time.Ticker { return time.NewTicker(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/go.uber.org/zap/zapcore/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/doc.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package zapcore defines and implements the low-level interfaces upon which // zap is built. By providing alternate implementations of these interfaces, // external packages can extend zap's capabilities. package zapcore // import "go.uber.org/zap/zapcore"
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/go.uber.org/zap/zapcore/increase_level.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/increase_level.go
// Copyright (c) 2020 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import "fmt" type levelFilterCore struct { core Core level LevelEnabler } var ( _ Core = (*levelFilterCore)(nil) _ leveledEnabler = (*levelFilterCore)(nil) ) // NewIncreaseLevelCore creates a core that can be used to increase the level of // an existing Core. It cannot be used to decrease the logging level, as it acts // as a filter before calling the underlying core. If level decreases the log level, // an error is returned. func NewIncreaseLevelCore(core Core, level LevelEnabler) (Core, error) { for l := _maxLevel; l >= _minLevel; l-- { if !core.Enabled(l) && level.Enabled(l) { return nil, fmt.Errorf("invalid increase level, as level %q is allowed by increased level, but not by existing core", l) } } return &levelFilterCore{core, level}, nil } func (c *levelFilterCore) Enabled(lvl Level) bool { return c.level.Enabled(lvl) } func (c *levelFilterCore) Level() Level { return LevelOf(c.level) } func (c *levelFilterCore) With(fields []Field) Core { return &levelFilterCore{c.core.With(fields), c.level} } func (c *levelFilterCore) Check(ent Entry, ce *CheckedEntry) *CheckedEntry { if !c.Enabled(ent.Level) { return ce } return c.core.Check(ent, ce) } func (c *levelFilterCore) Write(ent Entry, fields []Field) error { return c.core.Write(ent, fields) } func (c *levelFilterCore) Sync() error { return c.core.Sync() }
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/go.uber.org/zap/zapcore/encoder.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/encoder.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import ( "encoding/json" "io" "time" "go.uber.org/zap/buffer" ) // DefaultLineEnding defines the default line ending when writing logs. // Alternate line endings specified in EncoderConfig can override this // behavior. const DefaultLineEnding = "\n" // OmitKey defines the key to use when callers want to remove a key from log output. const OmitKey = "" // A LevelEncoder serializes a Level to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type LevelEncoder func(Level, PrimitiveArrayEncoder) // LowercaseLevelEncoder serializes a Level to a lowercase string. For example, // InfoLevel is serialized to "info". func LowercaseLevelEncoder(l Level, enc PrimitiveArrayEncoder) { enc.AppendString(l.String()) } // LowercaseColorLevelEncoder serializes a Level to a lowercase string and adds coloring. // For example, InfoLevel is serialized to "info" and colored blue. func LowercaseColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { s, ok := _levelToLowercaseColorString[l] if !ok { s = _unknownLevelColor.Add(l.String()) } enc.AppendString(s) } // CapitalLevelEncoder serializes a Level to an all-caps string. For example, // InfoLevel is serialized to "INFO". func CapitalLevelEncoder(l Level, enc PrimitiveArrayEncoder) { enc.AppendString(l.CapitalString()) } // CapitalColorLevelEncoder serializes a Level to an all-caps string and adds color. // For example, InfoLevel is serialized to "INFO" and colored blue. func CapitalColorLevelEncoder(l Level, enc PrimitiveArrayEncoder) { s, ok := _levelToCapitalColorString[l] if !ok { s = _unknownLevelColor.Add(l.CapitalString()) } enc.AppendString(s) } // UnmarshalText unmarshals text to a LevelEncoder. "capital" is unmarshaled to // CapitalLevelEncoder, "coloredCapital" is unmarshaled to CapitalColorLevelEncoder, // "colored" is unmarshaled to LowercaseColorLevelEncoder, and anything else // is unmarshaled to LowercaseLevelEncoder. func (e *LevelEncoder) UnmarshalText(text []byte) error { switch string(text) { case "capital": *e = CapitalLevelEncoder case "capitalColor": *e = CapitalColorLevelEncoder case "color": *e = LowercaseColorLevelEncoder default: *e = LowercaseLevelEncoder } return nil } // A TimeEncoder serializes a time.Time to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type TimeEncoder func(time.Time, PrimitiveArrayEncoder) // EpochTimeEncoder serializes a time.Time to a floating-point number of seconds // since the Unix epoch. func EpochTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { nanos := t.UnixNano() sec := float64(nanos) / float64(time.Second) enc.AppendFloat64(sec) } // EpochMillisTimeEncoder serializes a time.Time to a floating-point number of // milliseconds since the Unix epoch. func EpochMillisTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { nanos := t.UnixNano() millis := float64(nanos) / float64(time.Millisecond) enc.AppendFloat64(millis) } // EpochNanosTimeEncoder serializes a time.Time to an integer number of // nanoseconds since the Unix epoch. func EpochNanosTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { enc.AppendInt64(t.UnixNano()) } func encodeTimeLayout(t time.Time, layout string, enc PrimitiveArrayEncoder) { type appendTimeEncoder interface { AppendTimeLayout(time.Time, string) } if enc, ok := enc.(appendTimeEncoder); ok { enc.AppendTimeLayout(t, layout) return } enc.AppendString(t.Format(layout)) } // ISO8601TimeEncoder serializes a time.Time to an ISO8601-formatted string // with millisecond precision. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func ISO8601TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, "2006-01-02T15:04:05.000Z0700", enc) } // RFC3339TimeEncoder serializes a time.Time to an RFC3339-formatted string. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func RFC3339TimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, time.RFC3339, enc) } // RFC3339NanoTimeEncoder serializes a time.Time to an RFC3339-formatted string // with nanosecond precision. // // If enc supports AppendTimeLayout(t time.Time,layout string), it's used // instead of appending a pre-formatted string value. func RFC3339NanoTimeEncoder(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, time.RFC3339Nano, enc) } // TimeEncoderOfLayout returns TimeEncoder which serializes a time.Time using // given layout. func TimeEncoderOfLayout(layout string) TimeEncoder { return func(t time.Time, enc PrimitiveArrayEncoder) { encodeTimeLayout(t, layout, enc) } } // UnmarshalText unmarshals text to a TimeEncoder. // "rfc3339nano" and "RFC3339Nano" are unmarshaled to RFC3339NanoTimeEncoder. // "rfc3339" and "RFC3339" are unmarshaled to RFC3339TimeEncoder. // "iso8601" and "ISO8601" are unmarshaled to ISO8601TimeEncoder. // "millis" is unmarshaled to EpochMillisTimeEncoder. // "nanos" is unmarshaled to EpochNanosEncoder. // Anything else is unmarshaled to EpochTimeEncoder. func (e *TimeEncoder) UnmarshalText(text []byte) error { switch string(text) { case "rfc3339nano", "RFC3339Nano": *e = RFC3339NanoTimeEncoder case "rfc3339", "RFC3339": *e = RFC3339TimeEncoder case "iso8601", "ISO8601": *e = ISO8601TimeEncoder case "millis": *e = EpochMillisTimeEncoder case "nanos": *e = EpochNanosTimeEncoder default: *e = EpochTimeEncoder } return nil } // UnmarshalYAML unmarshals YAML to a TimeEncoder. // If value is an object with a "layout" field, it will be unmarshaled to TimeEncoder with given layout. // // timeEncoder: // layout: 06/01/02 03:04pm // // If value is string, it uses UnmarshalText. // // timeEncoder: iso8601 func (e *TimeEncoder) UnmarshalYAML(unmarshal func(interface{}) error) error { var o struct { Layout string `json:"layout" yaml:"layout"` } if err := unmarshal(&o); err == nil { *e = TimeEncoderOfLayout(o.Layout) return nil } var s string if err := unmarshal(&s); err != nil { return err } return e.UnmarshalText([]byte(s)) } // UnmarshalJSON unmarshals JSON to a TimeEncoder as same way UnmarshalYAML does. func (e *TimeEncoder) UnmarshalJSON(data []byte) error { return e.UnmarshalYAML(func(v interface{}) error { return json.Unmarshal(data, v) }) } // A DurationEncoder serializes a time.Duration to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type DurationEncoder func(time.Duration, PrimitiveArrayEncoder) // SecondsDurationEncoder serializes a time.Duration to a floating-point number of seconds elapsed. func SecondsDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendFloat64(float64(d) / float64(time.Second)) } // NanosDurationEncoder serializes a time.Duration to an integer number of // nanoseconds elapsed. func NanosDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendInt64(int64(d)) } // MillisDurationEncoder serializes a time.Duration to an integer number of // milliseconds elapsed. func MillisDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendInt64(d.Nanoseconds() / 1e6) } // StringDurationEncoder serializes a time.Duration using its built-in String // method. func StringDurationEncoder(d time.Duration, enc PrimitiveArrayEncoder) { enc.AppendString(d.String()) } // UnmarshalText unmarshals text to a DurationEncoder. "string" is unmarshaled // to StringDurationEncoder, and anything else is unmarshaled to // NanosDurationEncoder. func (e *DurationEncoder) UnmarshalText(text []byte) error { switch string(text) { case "string": *e = StringDurationEncoder case "nanos": *e = NanosDurationEncoder case "ms": *e = MillisDurationEncoder default: *e = SecondsDurationEncoder } return nil } // A CallerEncoder serializes an EntryCaller to a primitive type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type CallerEncoder func(EntryCaller, PrimitiveArrayEncoder) // FullCallerEncoder serializes a caller in /full/path/to/package/file:line // format. func FullCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { // TODO: consider using a byte-oriented API to save an allocation. enc.AppendString(caller.String()) } // ShortCallerEncoder serializes a caller in package/file:line format, trimming // all but the final directory from the full path. func ShortCallerEncoder(caller EntryCaller, enc PrimitiveArrayEncoder) { // TODO: consider using a byte-oriented API to save an allocation. enc.AppendString(caller.TrimmedPath()) } // UnmarshalText unmarshals text to a CallerEncoder. "full" is unmarshaled to // FullCallerEncoder and anything else is unmarshaled to ShortCallerEncoder. func (e *CallerEncoder) UnmarshalText(text []byte) error { switch string(text) { case "full": *e = FullCallerEncoder default: *e = ShortCallerEncoder } return nil } // A NameEncoder serializes a period-separated logger name to a primitive // type. // // This function must make exactly one call // to a PrimitiveArrayEncoder's Append* method. type NameEncoder func(string, PrimitiveArrayEncoder) // FullNameEncoder serializes the logger name as-is. func FullNameEncoder(loggerName string, enc PrimitiveArrayEncoder) { enc.AppendString(loggerName) } // UnmarshalText unmarshals text to a NameEncoder. Currently, everything is // unmarshaled to FullNameEncoder. func (e *NameEncoder) UnmarshalText(text []byte) error { switch string(text) { case "full": *e = FullNameEncoder default: *e = FullNameEncoder } return nil } // An EncoderConfig allows users to configure the concrete encoders supplied by // zapcore. type EncoderConfig struct { // Set the keys used for each log entry. If any key is empty, that portion // of the entry is omitted. MessageKey string `json:"messageKey" yaml:"messageKey"` LevelKey string `json:"levelKey" yaml:"levelKey"` TimeKey string `json:"timeKey" yaml:"timeKey"` NameKey string `json:"nameKey" yaml:"nameKey"` CallerKey string `json:"callerKey" yaml:"callerKey"` FunctionKey string `json:"functionKey" yaml:"functionKey"` StacktraceKey string `json:"stacktraceKey" yaml:"stacktraceKey"` SkipLineEnding bool `json:"skipLineEnding" yaml:"skipLineEnding"` LineEnding string `json:"lineEnding" yaml:"lineEnding"` // Configure the primitive representations of common complex types. For // example, some users may want all time.Times serialized as floating-point // seconds since epoch, while others may prefer ISO8601 strings. EncodeLevel LevelEncoder `json:"levelEncoder" yaml:"levelEncoder"` EncodeTime TimeEncoder `json:"timeEncoder" yaml:"timeEncoder"` EncodeDuration DurationEncoder `json:"durationEncoder" yaml:"durationEncoder"` EncodeCaller CallerEncoder `json:"callerEncoder" yaml:"callerEncoder"` // Unlike the other primitive type encoders, EncodeName is optional. The // zero value falls back to FullNameEncoder. EncodeName NameEncoder `json:"nameEncoder" yaml:"nameEncoder"` // Configure the encoder for interface{} type objects. // If not provided, objects are encoded using json.Encoder NewReflectedEncoder func(io.Writer) ReflectedEncoder `json:"-" yaml:"-"` // Configures the field separator used by the console encoder. Defaults // to tab. ConsoleSeparator string `json:"consoleSeparator" yaml:"consoleSeparator"` } // ObjectEncoder is a strongly-typed, encoding-agnostic interface for adding a // map- or struct-like object to the logging context. Like maps, ObjectEncoders // aren't safe for concurrent use (though typical use shouldn't require locks). type ObjectEncoder interface { // Logging-specific marshalers. AddArray(key string, marshaler ArrayMarshaler) error AddObject(key string, marshaler ObjectMarshaler) error // Built-in types. AddBinary(key string, value []byte) // for arbitrary bytes AddByteString(key string, value []byte) // for UTF-8 encoded bytes AddBool(key string, value bool) AddComplex128(key string, value complex128) AddComplex64(key string, value complex64) AddDuration(key string, value time.Duration) AddFloat64(key string, value float64) AddFloat32(key string, value float32) AddInt(key string, value int) AddInt64(key string, value int64) AddInt32(key string, value int32) AddInt16(key string, value int16) AddInt8(key string, value int8) AddString(key, value string) AddTime(key string, value time.Time) AddUint(key string, value uint) AddUint64(key string, value uint64) AddUint32(key string, value uint32) AddUint16(key string, value uint16) AddUint8(key string, value uint8) AddUintptr(key string, value uintptr) // AddReflected uses reflection to serialize arbitrary objects, so it can be // slow and allocation-heavy. AddReflected(key string, value interface{}) error // OpenNamespace opens an isolated namespace where all subsequent fields will // be added. Applications can use namespaces to prevent key collisions when // injecting loggers into sub-components or third-party libraries. OpenNamespace(key string) } // ArrayEncoder is a strongly-typed, encoding-agnostic interface for adding // array-like objects to the logging context. Of note, it supports mixed-type // arrays even though they aren't typical in Go. Like slices, ArrayEncoders // aren't safe for concurrent use (though typical use shouldn't require locks). type ArrayEncoder interface { // Built-in types. PrimitiveArrayEncoder // Time-related types. AppendDuration(time.Duration) AppendTime(time.Time) // Logging-specific marshalers. AppendArray(ArrayMarshaler) error AppendObject(ObjectMarshaler) error // AppendReflected uses reflection to serialize arbitrary objects, so it's // slow and allocation-heavy. AppendReflected(value interface{}) error } // PrimitiveArrayEncoder is the subset of the ArrayEncoder interface that deals // only in Go's built-in types. It's included only so that Duration- and // TimeEncoders cannot trigger infinite recursion. type PrimitiveArrayEncoder interface { // Built-in types. AppendBool(bool) AppendByteString([]byte) // for UTF-8 encoded bytes AppendComplex128(complex128) AppendComplex64(complex64) AppendFloat64(float64) AppendFloat32(float32) AppendInt(int) AppendInt64(int64) AppendInt32(int32) AppendInt16(int16) AppendInt8(int8) AppendString(string) AppendUint(uint) AppendUint64(uint64) AppendUint32(uint32) AppendUint16(uint16) AppendUint8(uint8) AppendUintptr(uintptr) } // Encoder is a format-agnostic interface for all log entry marshalers. Since // log encoders don't need to support the same wide range of use cases as // general-purpose marshalers, it's possible to make them faster and // lower-allocation. // // Implementations of the ObjectEncoder interface's methods can, of course, // freely modify the receiver. However, the Clone and EncodeEntry methods will // be called concurrently and shouldn't modify the receiver. type Encoder interface { ObjectEncoder // Clone copies the encoder, ensuring that adding fields to the copy doesn't // affect the original. Clone() Encoder // EncodeEntry encodes an entry and fields, along with any accumulated // context, into a byte buffer and returns it. Any fields that are empty, // including fields on the `Entry` type, should be omitted. EncodeEntry(Entry, []Field) (*buffer.Buffer, 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/go.uber.org/zap/zapcore/level_strings.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/zapcore/level_strings.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package zapcore import "go.uber.org/zap/internal/color" var ( _levelToColor = map[Level]color.Color{ DebugLevel: color.Magenta, InfoLevel: color.Blue, WarnLevel: color.Yellow, ErrorLevel: color.Red, DPanicLevel: color.Red, PanicLevel: color.Red, FatalLevel: color.Red, } _unknownLevelColor = color.Red _levelToLowercaseColorString = make(map[Level]string, len(_levelToColor)) _levelToCapitalColorString = make(map[Level]string, len(_levelToColor)) ) func init() { for level, color := range _levelToColor { _levelToLowercaseColorString[level] = color.Add(level.String()) _levelToCapitalColorString[level] = color.Add(level.CapitalString()) } }
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/go.uber.org/zap/internal/level_enabler.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/level_enabler.go
// Copyright (c) 2022 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package internal and its subpackages hold types and functionality // that are not part of Zap's public API. package internal import "go.uber.org/zap/zapcore" // LeveledEnabler is an interface satisfied by LevelEnablers that are able to // report their own level. // // This interface is defined to use more conveniently in tests and non-zapcore // packages. // This cannot be imported from zapcore because of the cyclic dependency. type LeveledEnabler interface { zapcore.LevelEnabler Level() zapcore.Level }
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/go.uber.org/zap/internal/bufferpool/bufferpool.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/bufferpool/bufferpool.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package bufferpool houses zap's shared internal buffer pool. Third-party // packages can recreate the same functionality with buffers.NewPool. package bufferpool import "go.uber.org/zap/buffer" var ( _pool = buffer.NewPool() // Get retrieves a buffer from the pool, creating one if necessary. Get = _pool.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/go.uber.org/zap/internal/exit/exit.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/exit/exit.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package exit provides stubs so that unit tests can exercise code that calls // os.Exit(1). package exit import "os" var _exit = os.Exit // With terminates the process by calling os.Exit(code). If the package is // stubbed, it instead records a call in the testing spy. func With(code int) { _exit(code) } // A StubbedExit is a testing fake for os.Exit. type StubbedExit struct { Exited bool Code int prev func(code int) } // Stub substitutes a fake for the call to os.Exit(1). func Stub() *StubbedExit { s := &StubbedExit{prev: _exit} _exit = s.exit return s } // WithStub runs the supplied function with Exit stubbed. It returns the stub // used, so that users can test whether the process would have crashed. func WithStub(f func()) *StubbedExit { s := Stub() defer s.Unstub() f() return s } // Unstub restores the previous exit function. func (se *StubbedExit) Unstub() { _exit = se.prev } func (se *StubbedExit) exit(code int) { se.Exited = true se.Code = code }
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/go.uber.org/zap/internal/pool/pool.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/pool/pool.go
// Copyright (c) 2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package pool provides internal pool utilities. package pool import ( "sync" ) // A Pool is a generic wrapper around [sync.Pool] to provide strongly-typed // object pooling. // // Note that SA6002 (ref: https://staticcheck.io/docs/checks/#SA6002) will // not be detected, so all internal pool use must take care to only store // pointer types. type Pool[T any] struct { pool sync.Pool } // New returns a new [Pool] for T, and will use fn to construct new Ts when // the pool is empty. func New[T any](fn func() T) *Pool[T] { return &Pool[T]{ pool: sync.Pool{ New: func() any { return fn() }, }, } } // Get gets a T from the pool, or creates a new one if the pool is empty. func (p *Pool[T]) Get() T { return p.pool.Get().(T) } // Put returns x into the pool. func (p *Pool[T]) Put(x T) { p.pool.Put(x) }
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/go.uber.org/zap/internal/stacktrace/stack.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/stacktrace/stack.go
// Copyright (c) 2023 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package stacktrace provides support for gathering stack traces // efficiently. package stacktrace import ( "runtime" "go.uber.org/zap/buffer" "go.uber.org/zap/internal/bufferpool" "go.uber.org/zap/internal/pool" ) var _stackPool = pool.New(func() *Stack { return &Stack{ storage: make([]uintptr, 64), } }) // Stack is a captured stack trace. type Stack struct { pcs []uintptr // program counters; always a subslice of storage frames *runtime.Frames // The size of pcs varies depending on requirements: // it will be one if the only the first frame was requested, // and otherwise it will reflect the depth of the call stack. // // storage decouples the slice we need (pcs) from the slice we pool. // We will always allocate a reasonably large storage, but we'll use // only as much of it as we need. storage []uintptr } // Depth specifies how deep of a stack trace should be captured. type Depth int const ( // First captures only the first frame. First Depth = iota // Full captures the entire call stack, allocating more // storage for it if needed. Full ) // Capture captures a stack trace of the specified depth, skipping // the provided number of frames. skip=0 identifies the caller of // Capture. // // The caller must call Free on the returned stacktrace after using it. func Capture(skip int, depth Depth) *Stack { stack := _stackPool.Get() switch depth { case First: stack.pcs = stack.storage[:1] case Full: stack.pcs = stack.storage } // Unlike other "skip"-based APIs, skip=0 identifies runtime.Callers // itself. +2 to skip captureStacktrace and runtime.Callers. numFrames := runtime.Callers( skip+2, stack.pcs, ) // runtime.Callers truncates the recorded stacktrace if there is no // room in the provided slice. For the full stack trace, keep expanding // storage until there are fewer frames than there is room. if depth == Full { pcs := stack.pcs for numFrames == len(pcs) { pcs = make([]uintptr, len(pcs)*2) numFrames = runtime.Callers(skip+2, pcs) } // Discard old storage instead of returning it to the pool. // This will adjust the pool size over time if stack traces are // consistently very deep. stack.storage = pcs stack.pcs = pcs[:numFrames] } else { stack.pcs = stack.pcs[:numFrames] } stack.frames = runtime.CallersFrames(stack.pcs) return stack } // Free releases resources associated with this stacktrace // and returns it back to the pool. func (st *Stack) Free() { st.frames = nil st.pcs = nil _stackPool.Put(st) } // Count reports the total number of frames in this stacktrace. // Count DOES NOT change as Next is called. func (st *Stack) Count() int { return len(st.pcs) } // Next returns the next frame in the stack trace, // and a boolean indicating whether there are more after it. func (st *Stack) Next() (_ runtime.Frame, more bool) { return st.frames.Next() } // Take returns a string representation of the current stacktrace. // // skip is the number of frames to skip before recording the stack trace. // skip=0 identifies the caller of Take. func Take(skip int) string { stack := Capture(skip+1, Full) defer stack.Free() buffer := bufferpool.Get() defer buffer.Free() stackfmt := NewFormatter(buffer) stackfmt.FormatStack(stack) return buffer.String() } // Formatter formats a stack trace into a readable string representation. type Formatter struct { b *buffer.Buffer nonEmpty bool // whehther we've written at least one frame already } // NewFormatter builds a new Formatter. func NewFormatter(b *buffer.Buffer) Formatter { return Formatter{b: b} } // FormatStack formats all remaining frames in the provided stacktrace -- minus // the final runtime.main/runtime.goexit frame. func (sf *Formatter) FormatStack(stack *Stack) { // Note: On the last iteration, frames.Next() returns false, with a valid // frame, but we ignore this frame. The last frame is a runtime frame which // adds noise, since it's only either runtime.main or runtime.goexit. for frame, more := stack.Next(); more; frame, more = stack.Next() { sf.FormatFrame(frame) } } // FormatFrame formats the given frame. func (sf *Formatter) FormatFrame(frame runtime.Frame) { if sf.nonEmpty { sf.b.AppendByte('\n') } sf.nonEmpty = true sf.b.AppendString(frame.Function) sf.b.AppendByte('\n') sf.b.AppendByte('\t') sf.b.AppendString(frame.File) sf.b.AppendByte(':') sf.b.AppendInt(int64(frame.Line)) }
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/go.uber.org/zap/internal/color/color.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/internal/color/color.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package color adds coloring functionality for TTY output. package color import "fmt" // Foreground colors. const ( Black Color = iota + 30 Red Green Yellow Blue Magenta Cyan White ) // Color represents a text color. type Color uint8 // Add adds the coloring to the given string. func (c Color) Add(s string) string { return fmt.Sprintf("\x1b[%dm%s\x1b[0m", uint8(c), 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/go.uber.org/zap/buffer/buffer.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/buffer/buffer.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // Package buffer provides a thin wrapper around a byte slice. Unlike the // standard library's bytes.Buffer, it supports a portion of the strconv // package's zero-allocation formatters. package buffer // import "go.uber.org/zap/buffer" import ( "strconv" "time" ) const _size = 1024 // by default, create 1 KiB buffers // Buffer is a thin wrapper around a byte slice. It's intended to be pooled, so // the only way to construct one is via a Pool. type Buffer struct { bs []byte pool Pool } // AppendByte writes a single byte to the Buffer. func (b *Buffer) AppendByte(v byte) { b.bs = append(b.bs, v) } // AppendBytes writes the given slice of bytes to the Buffer. func (b *Buffer) AppendBytes(v []byte) { b.bs = append(b.bs, v...) } // AppendString writes a string to the Buffer. func (b *Buffer) AppendString(s string) { b.bs = append(b.bs, s...) } // AppendInt appends an integer to the underlying buffer (assuming base 10). func (b *Buffer) AppendInt(i int64) { b.bs = strconv.AppendInt(b.bs, i, 10) } // AppendTime appends the time formatted using the specified layout. func (b *Buffer) AppendTime(t time.Time, layout string) { b.bs = t.AppendFormat(b.bs, layout) } // AppendUint appends an unsigned integer to the underlying buffer (assuming // base 10). func (b *Buffer) AppendUint(i uint64) { b.bs = strconv.AppendUint(b.bs, i, 10) } // AppendBool appends a bool to the underlying buffer. func (b *Buffer) AppendBool(v bool) { b.bs = strconv.AppendBool(b.bs, v) } // AppendFloat appends a float to the underlying buffer. It doesn't quote NaN // or +/- Inf. func (b *Buffer) AppendFloat(f float64, bitSize int) { b.bs = strconv.AppendFloat(b.bs, f, 'f', -1, bitSize) } // Len returns the length of the underlying byte slice. func (b *Buffer) Len() int { return len(b.bs) } // Cap returns the capacity of the underlying byte slice. func (b *Buffer) Cap() int { return cap(b.bs) } // Bytes returns a mutable reference to the underlying byte slice. func (b *Buffer) Bytes() []byte { return b.bs } // String returns a string copy of the underlying byte slice. func (b *Buffer) String() string { return string(b.bs) } // Reset resets the underlying byte slice. Subsequent writes re-use the slice's // backing array. func (b *Buffer) Reset() { b.bs = b.bs[:0] } // Write implements io.Writer. func (b *Buffer) Write(bs []byte) (int, error) { b.bs = append(b.bs, bs...) return len(bs), nil } // WriteByte writes a single byte to the Buffer. // // Error returned is always nil, function signature is compatible // with bytes.Buffer and bufio.Writer func (b *Buffer) WriteByte(v byte) error { b.AppendByte(v) return nil } // WriteString writes a string to the Buffer. // // Error returned is always nil, function signature is compatible // with bytes.Buffer and bufio.Writer func (b *Buffer) WriteString(s string) (int, error) { b.AppendString(s) return len(s), nil } // TrimNewline trims any final "\n" byte from the end of the buffer. func (b *Buffer) TrimNewline() { if i := len(b.bs) - 1; i >= 0 { if b.bs[i] == '\n' { b.bs = b.bs[:i] } } } // Free returns the Buffer to its Pool. // // Callers must not retain references to the Buffer after calling Free. func (b *Buffer) Free() { b.pool.put(b) }
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/go.uber.org/zap/buffer/pool.go
cmd/vsphere-xcopy-volume-populator/vendor/go.uber.org/zap/buffer/pool.go
// Copyright (c) 2016 Uber Technologies, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. package buffer import ( "go.uber.org/zap/internal/pool" ) // A Pool is a type-safe wrapper around a sync.Pool. type Pool struct { p *pool.Pool[*Buffer] } // NewPool constructs a new Pool. func NewPool() Pool { return Pool{ p: pool.New(func() *Buffer { return &Buffer{ bs: make([]byte, 0, _size), } }), } } // Get retrieves a Buffer from the pool, creating one if necessary. func (p Pool) Get() *Buffer { buf := p.p.Get() buf.Reset() buf.pool = p return buf } func (p Pool) put(buf *Buffer) { p.p.Put(buf) }
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/genproto/googleapis/rpc/status/status.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/genproto/googleapis/rpc/status/status.pb.go
// Copyright 2024 Google LLC // // 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. // Code generated by protoc-gen-go. DO NOT EDIT. // versions: // protoc-gen-go v1.26.0 // protoc v4.24.4 // source: google/rpc/status.proto package status import ( reflect "reflect" sync "sync" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" anypb "google.golang.org/protobuf/types/known/anypb" ) const ( // Verify that this generated code is sufficiently up-to-date. _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) // Verify that runtime/protoimpl is sufficiently up-to-date. _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) // The `Status` type defines a logical error model that is suitable for // different programming environments, including REST APIs and RPC APIs. It is // used by [gRPC](https://github.com/grpc). Each `Status` message contains // three pieces of data: error code, error message, and error details. // // You can find out more about this error model and how to work with it in the // [API Design Guide](https://cloud.google.com/apis/design/errors). type Status struct { state protoimpl.MessageState sizeCache protoimpl.SizeCache unknownFields protoimpl.UnknownFields // The status code, which should be an enum value of // [google.rpc.Code][google.rpc.Code]. Code int32 `protobuf:"varint,1,opt,name=code,proto3" json:"code,omitempty"` // A developer-facing error message, which should be in English. Any // user-facing error message should be localized and sent in the // [google.rpc.Status.details][google.rpc.Status.details] field, or localized // by the client. Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"` // A list of messages that carry the error details. There is a common set of // message types for APIs to use. Details []*anypb.Any `protobuf:"bytes,3,rep,name=details,proto3" json:"details,omitempty"` } func (x *Status) Reset() { *x = Status{} if protoimpl.UnsafeEnabled { mi := &file_google_rpc_status_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } } func (x *Status) String() string { return protoimpl.X.MessageStringOf(x) } func (*Status) ProtoMessage() {} func (x *Status) ProtoReflect() protoreflect.Message { mi := &file_google_rpc_status_proto_msgTypes[0] if protoimpl.UnsafeEnabled && x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Status.ProtoReflect.Descriptor instead. func (*Status) Descriptor() ([]byte, []int) { return file_google_rpc_status_proto_rawDescGZIP(), []int{0} } func (x *Status) GetCode() int32 { if x != nil { return x.Code } return 0 } func (x *Status) GetMessage() string { if x != nil { return x.Message } return "" } func (x *Status) GetDetails() []*anypb.Any { if x != nil { return x.Details } return nil } var File_google_rpc_status_proto protoreflect.FileDescriptor var file_google_rpc_status_proto_rawDesc = []byte{ 0x0a, 0x17, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0a, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x1a, 0x19, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x61, 0x6e, 0x79, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x22, 0x66, 0x0a, 0x06, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x12, 0x12, 0x0a, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x05, 0x52, 0x04, 0x63, 0x6f, 0x64, 0x65, 0x12, 0x18, 0x0a, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x07, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x12, 0x2e, 0x0a, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x14, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x41, 0x6e, 0x79, 0x52, 0x07, 0x64, 0x65, 0x74, 0x61, 0x69, 0x6c, 0x73, 0x42, 0x61, 0x0a, 0x0e, 0x63, 0x6f, 0x6d, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x72, 0x70, 0x63, 0x42, 0x0b, 0x53, 0x74, 0x61, 0x74, 0x75, 0x73, 0x50, 0x72, 0x6f, 0x74, 0x6f, 0x50, 0x01, 0x5a, 0x37, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x67, 0x65, 0x6e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x61, 0x70, 0x69, 0x73, 0x2f, 0x72, 0x70, 0x63, 0x2f, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0x3b, 0x73, 0x74, 0x61, 0x74, 0x75, 0x73, 0xf8, 0x01, 0x01, 0xa2, 0x02, 0x03, 0x52, 0x50, 0x43, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, } var ( file_google_rpc_status_proto_rawDescOnce sync.Once file_google_rpc_status_proto_rawDescData = file_google_rpc_status_proto_rawDesc ) func file_google_rpc_status_proto_rawDescGZIP() []byte { file_google_rpc_status_proto_rawDescOnce.Do(func() { file_google_rpc_status_proto_rawDescData = protoimpl.X.CompressGZIP(file_google_rpc_status_proto_rawDescData) }) return file_google_rpc_status_proto_rawDescData } var file_google_rpc_status_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_rpc_status_proto_goTypes = []interface{}{ (*Status)(nil), // 0: google.rpc.Status (*anypb.Any)(nil), // 1: google.protobuf.Any } var file_google_rpc_status_proto_depIdxs = []int32{ 1, // 0: google.rpc.Status.details:type_name -> google.protobuf.Any 1, // [1:1] is the sub-list for method output_type 1, // [1:1] is the sub-list for method input_type 1, // [1:1] is the sub-list for extension type_name 1, // [1:1] is the sub-list for extension extendee 0, // [0:1] is the sub-list for field type_name } func init() { file_google_rpc_status_proto_init() } func file_google_rpc_status_proto_init() { if File_google_rpc_status_proto != nil { return } if !protoimpl.UnsafeEnabled { file_google_rpc_status_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { switch v := v.(*Status); i { case 0: return &v.state case 1: return &v.sizeCache case 2: return &v.unknownFields default: return nil } } } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: file_google_rpc_status_proto_rawDesc, NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_rpc_status_proto_goTypes, DependencyIndexes: file_google_rpc_status_proto_depIdxs, MessageInfos: file_google_rpc_status_proto_msgTypes, }.Build() File_google_rpc_status_proto = out.File file_google_rpc_status_proto_rawDesc = nil file_google_rpc_status_proto_goTypes = nil file_google_rpc_status_proto_depIdxs = 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/encoding/protojson/well_known_types.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protojson/well_known_types.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 protojson import ( "bytes" "fmt" "math" "strconv" "strings" "time" "google.golang.org/protobuf/internal/encoding/json" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) type marshalFunc func(encoder, protoreflect.Message) error // wellKnownTypeMarshaler returns a marshal function if the message type // has specialized serialization behavior. It returns nil otherwise. func wellKnownTypeMarshaler(name protoreflect.FullName) marshalFunc { if name.Parent() == genid.GoogleProtobuf_package { switch name.Name() { case genid.Any_message_name: return encoder.marshalAny case genid.Timestamp_message_name: return encoder.marshalTimestamp case genid.Duration_message_name: return encoder.marshalDuration case genid.BoolValue_message_name, genid.Int32Value_message_name, genid.Int64Value_message_name, genid.UInt32Value_message_name, genid.UInt64Value_message_name, genid.FloatValue_message_name, genid.DoubleValue_message_name, genid.StringValue_message_name, genid.BytesValue_message_name: return encoder.marshalWrapperType case genid.Struct_message_name: return encoder.marshalStruct case genid.ListValue_message_name: return encoder.marshalListValue case genid.Value_message_name: return encoder.marshalKnownValue case genid.FieldMask_message_name: return encoder.marshalFieldMask case genid.Empty_message_name: return encoder.marshalEmpty } } return nil } type unmarshalFunc func(decoder, protoreflect.Message) error // wellKnownTypeUnmarshaler returns a unmarshal function if the message type // has specialized serialization behavior. It returns nil otherwise. func wellKnownTypeUnmarshaler(name protoreflect.FullName) unmarshalFunc { if name.Parent() == genid.GoogleProtobuf_package { switch name.Name() { case genid.Any_message_name: return decoder.unmarshalAny case genid.Timestamp_message_name: return decoder.unmarshalTimestamp case genid.Duration_message_name: return decoder.unmarshalDuration case genid.BoolValue_message_name, genid.Int32Value_message_name, genid.Int64Value_message_name, genid.UInt32Value_message_name, genid.UInt64Value_message_name, genid.FloatValue_message_name, genid.DoubleValue_message_name, genid.StringValue_message_name, genid.BytesValue_message_name: return decoder.unmarshalWrapperType case genid.Struct_message_name: return decoder.unmarshalStruct case genid.ListValue_message_name: return decoder.unmarshalListValue case genid.Value_message_name: return decoder.unmarshalKnownValue case genid.FieldMask_message_name: return decoder.unmarshalFieldMask case genid.Empty_message_name: return decoder.unmarshalEmpty } } return nil } // The JSON representation of an Any message uses the regular representation of // the deserialized, embedded message, with an additional field `@type` which // contains the type URL. If the embedded message type is well-known and has a // custom JSON representation, that representation will be embedded adding a // field `value` which holds the custom JSON in addition to the `@type` field. func (e encoder) marshalAny(m protoreflect.Message) error { fds := m.Descriptor().Fields() fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) fdValue := fds.ByNumber(genid.Any_Value_field_number) if !m.Has(fdType) { if !m.Has(fdValue) { // If message is empty, marshal out empty JSON object. e.StartObject() e.EndObject() return nil } else { // Return error if type_url field is not set, but value is set. return errors.New("%s: %v is not set", genid.Any_message_fullname, genid.Any_TypeUrl_field_name) } } typeVal := m.Get(fdType) valueVal := m.Get(fdValue) // Resolve the type in order to unmarshal value field. typeURL := typeVal.String() emt, err := e.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return errors.New("%s: unable to resolve %q: %v", genid.Any_message_fullname, typeURL, err) } em := emt.New() err = proto.UnmarshalOptions{ AllowPartial: true, // never check required fields inside an Any Resolver: e.opts.Resolver, }.Unmarshal(valueVal.Bytes(), em.Interface()) if err != nil { return errors.New("%s: unable to unmarshal %q: %v", genid.Any_message_fullname, typeURL, err) } // If type of value has custom JSON encoding, marshal out a field "value" // with corresponding custom JSON encoding of the embedded message as a // field. if marshal := wellKnownTypeMarshaler(emt.Descriptor().FullName()); marshal != nil { e.StartObject() defer e.EndObject() // Marshal out @type field. e.WriteName("@type") if err := e.WriteString(typeURL); err != nil { return err } e.WriteName("value") return marshal(e, em) } // Else, marshal out the embedded message's fields in this Any object. if err := e.marshalMessage(em, typeURL); err != nil { return err } return nil } func (d decoder) unmarshalAny(m protoreflect.Message) error { // Peek to check for json.ObjectOpen to avoid advancing a read. start, err := d.Peek() if err != nil { return err } if start.Kind() != json.ObjectOpen { return d.unexpectedTokenError(start) } // Use another decoder to parse the unread bytes for @type field. This // avoids advancing a read from current decoder because the current JSON // object may contain the fields of the embedded type. dec := decoder{d.Clone(), UnmarshalOptions{RecursionLimit: d.opts.RecursionLimit}} tok, err := findTypeURL(dec) switch err { case errEmptyObject: // An empty JSON object translates to an empty Any message. d.Read() // Read json.ObjectOpen. d.Read() // Read json.ObjectClose. return nil case errMissingType: if d.opts.DiscardUnknown { // Treat all fields as unknowns, similar to an empty object. return d.skipJSONValue() } // Use start.Pos() for line position. return d.newError(start.Pos(), err.Error()) default: if err != nil { return err } } typeURL := tok.ParsedString() emt, err := d.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return d.newError(tok.Pos(), "unable to resolve %v: %q", tok.RawString(), err) } // Create new message for the embedded message type and unmarshal into it. em := emt.New() if unmarshal := wellKnownTypeUnmarshaler(emt.Descriptor().FullName()); unmarshal != nil { // If embedded message is a custom type, // unmarshal the JSON "value" field into it. if err := d.unmarshalAnyValue(unmarshal, em); err != nil { return err } } else { // Else unmarshal the current JSON object into it. if err := d.unmarshalMessage(em, true); err != nil { return err } } // Serialize the embedded message and assign the resulting bytes to the // proto value field. b, err := proto.MarshalOptions{ AllowPartial: true, // No need to check required fields inside an Any. Deterministic: true, }.Marshal(em.Interface()) if err != nil { return d.newError(start.Pos(), "error in marshaling Any.value field: %v", err) } fds := m.Descriptor().Fields() fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) fdValue := fds.ByNumber(genid.Any_Value_field_number) m.Set(fdType, protoreflect.ValueOfString(typeURL)) m.Set(fdValue, protoreflect.ValueOfBytes(b)) return nil } var errEmptyObject = fmt.Errorf(`empty object`) var errMissingType = fmt.Errorf(`missing "@type" field`) // findTypeURL returns the token for the "@type" field value from the given // JSON bytes. It is expected that the given bytes start with json.ObjectOpen. // It returns errEmptyObject if the JSON object is empty or errMissingType if // @type field does not exist. It returns other error if the @type field is not // valid or other decoding issues. func findTypeURL(d decoder) (json.Token, error) { var typeURL string var typeTok json.Token numFields := 0 // Skip start object. d.Read() Loop: for { tok, err := d.Read() if err != nil { return json.Token{}, err } switch tok.Kind() { case json.ObjectClose: if typeURL == "" { // Did not find @type field. if numFields > 0 { return json.Token{}, errMissingType } return json.Token{}, errEmptyObject } break Loop case json.Name: numFields++ if tok.Name() != "@type" { // Skip value. if err := d.skipJSONValue(); err != nil { return json.Token{}, err } continue } // Return error if this was previously set already. if typeURL != "" { return json.Token{}, d.newError(tok.Pos(), `duplicate "@type" field`) } // Read field value. tok, err := d.Read() if err != nil { return json.Token{}, err } if tok.Kind() != json.String { return json.Token{}, d.newError(tok.Pos(), `@type field value is not a string: %v`, tok.RawString()) } typeURL = tok.ParsedString() if typeURL == "" { return json.Token{}, d.newError(tok.Pos(), `@type field contains empty value`) } typeTok = tok } } return typeTok, nil } // skipJSONValue parses a JSON value (null, boolean, string, number, object and // array) in order to advance the read to the next JSON value. It relies on // the decoder returning an error if the types are not in valid sequence. func (d decoder) skipJSONValue() error { var open int for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case json.ObjectClose, json.ArrayClose: open-- case json.ObjectOpen, json.ArrayOpen: open++ if open > d.opts.RecursionLimit { return errors.New("exceeded max recursion depth") } case json.EOF: // This can only happen if there's a bug in Decoder.Read. // Avoid an infinite loop if this does happen. return errors.New("unexpected EOF") } if open == 0 { return nil } } } // unmarshalAnyValue unmarshals the given custom-type message from the JSON // object's "value" field. func (d decoder) unmarshalAnyValue(unmarshal unmarshalFunc, m protoreflect.Message) error { // Skip ObjectOpen, and start reading the fields. d.Read() var found bool // Used for detecting duplicate "value". for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case json.ObjectClose: if !found { // We tolerate an omitted `value` field with the google.protobuf.Empty Well-Known-Type, // for compatibility with other proto runtimes that have interpreted the spec differently. if m.Descriptor().FullName() != genid.Empty_message_fullname { return d.newError(tok.Pos(), `missing "value" field`) } } return nil case json.Name: switch tok.Name() { case "@type": // Skip the value as this was previously parsed already. d.Read() case "value": if found { return d.newError(tok.Pos(), `duplicate "value" field`) } // Unmarshal the field value into the given message. if err := unmarshal(d, m); err != nil { return err } found = true default: if d.opts.DiscardUnknown { if err := d.skipJSONValue(); err != nil { return err } continue } return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) } } } } // Wrapper types are encoded as JSON primitives like string, number or boolean. func (e encoder) marshalWrapperType(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) val := m.Get(fd) return e.marshalSingular(val, fd) } func (d decoder) unmarshalWrapperType(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.WrapperValue_Value_field_number) val, err := d.unmarshalScalar(fd) if err != nil { return err } m.Set(fd, val) return nil } // The JSON representation for Empty is an empty JSON object. func (e encoder) marshalEmpty(protoreflect.Message) error { e.StartObject() e.EndObject() return nil } func (d decoder) unmarshalEmpty(protoreflect.Message) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.ObjectOpen { return d.unexpectedTokenError(tok) } for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case json.ObjectClose: return nil case json.Name: if d.opts.DiscardUnknown { if err := d.skipJSONValue(); err != nil { return err } continue } return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) default: return d.unexpectedTokenError(tok) } } } // The JSON representation for Struct is a JSON object that contains the encoded // Struct.fields map and follows the serialization rules for a map. func (e encoder) marshalStruct(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) return e.marshalMap(m.Get(fd).Map(), fd) } func (d decoder) unmarshalStruct(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.Struct_Fields_field_number) return d.unmarshalMap(m.Mutable(fd).Map(), fd) } // The JSON representation for ListValue is JSON array that contains the encoded // ListValue.values repeated field and follows the serialization rules for a // repeated field. func (e encoder) marshalListValue(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) return e.marshalList(m.Get(fd).List(), fd) } func (d decoder) unmarshalListValue(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.ListValue_Values_field_number) return d.unmarshalList(m.Mutable(fd).List(), fd) } // The JSON representation for a Value is dependent on the oneof field that is // set. Each of the field in the oneof has its own custom serialization rule. A // Value message needs to be a oneof field set, else it is an error. func (e encoder) marshalKnownValue(m protoreflect.Message) error { od := m.Descriptor().Oneofs().ByName(genid.Value_Kind_oneof_name) fd := m.WhichOneof(od) if fd == nil { return errors.New("%s: none of the oneof fields is set", genid.Value_message_fullname) } if fd.Number() == genid.Value_NumberValue_field_number { if v := m.Get(fd).Float(); math.IsNaN(v) || math.IsInf(v, 0) { return errors.New("%s: invalid %v value", genid.Value_NumberValue_field_fullname, v) } } return e.marshalSingular(m.Get(fd), fd) } func (d decoder) unmarshalKnownValue(m protoreflect.Message) error { tok, err := d.Peek() if err != nil { return err } var fd protoreflect.FieldDescriptor var val protoreflect.Value switch tok.Kind() { case json.Null: d.Read() fd = m.Descriptor().Fields().ByNumber(genid.Value_NullValue_field_number) val = protoreflect.ValueOfEnum(0) case json.Bool: tok, err := d.Read() if err != nil { return err } fd = m.Descriptor().Fields().ByNumber(genid.Value_BoolValue_field_number) val = protoreflect.ValueOfBool(tok.Bool()) case json.Number: tok, err := d.Read() if err != nil { return err } fd = m.Descriptor().Fields().ByNumber(genid.Value_NumberValue_field_number) var ok bool val, ok = unmarshalFloat(tok, 64) if !ok { return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) } case json.String: // A JSON string may have been encoded from the number_value field, // e.g. "NaN", "Infinity", etc. Parsing a proto double type also allows // for it to be in JSON string form. Given this custom encoding spec, // however, there is no way to identify that and hence a JSON string is // always assigned to the string_value field, which means that certain // encoding cannot be parsed back to the same field. tok, err := d.Read() if err != nil { return err } fd = m.Descriptor().Fields().ByNumber(genid.Value_StringValue_field_number) val = protoreflect.ValueOfString(tok.ParsedString()) case json.ObjectOpen: fd = m.Descriptor().Fields().ByNumber(genid.Value_StructValue_field_number) val = m.NewField(fd) if err := d.unmarshalStruct(val.Message()); err != nil { return err } case json.ArrayOpen: fd = m.Descriptor().Fields().ByNumber(genid.Value_ListValue_field_number) val = m.NewField(fd) if err := d.unmarshalListValue(val.Message()); err != nil { return err } default: return d.newError(tok.Pos(), "invalid %v: %v", genid.Value_message_fullname, tok.RawString()) } m.Set(fd, val) return nil } // The JSON representation for a Duration is a JSON string that ends in the // suffix "s" (indicating seconds) and is preceded by the number of seconds, // with nanoseconds expressed as fractional seconds. // // Durations less than one second are represented with a 0 seconds field and a // positive or negative nanos field. For durations of one second or more, a // non-zero value for the nanos field must be of the same sign as the seconds // field. // // Duration.seconds must be from -315,576,000,000 to +315,576,000,000 inclusive. // Duration.nanos must be from -999,999,999 to +999,999,999 inclusive. const ( secondsInNanos = 999999999 maxSecondsInDuration = 315576000000 ) func (e encoder) marshalDuration(m protoreflect.Message) error { fds := m.Descriptor().Fields() fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) secsVal := m.Get(fdSeconds) nanosVal := m.Get(fdNanos) secs := secsVal.Int() nanos := nanosVal.Int() if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { return errors.New("%s: seconds out of range %v", genid.Duration_message_fullname, secs) } if nanos < -secondsInNanos || nanos > secondsInNanos { return errors.New("%s: nanos out of range %v", genid.Duration_message_fullname, nanos) } if (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0) { return errors.New("%s: signs of seconds and nanos do not match", genid.Duration_message_fullname) } // Generated output always contains 0, 3, 6, or 9 fractional digits, // depending on required precision, followed by the suffix "s". var sign string if secs < 0 || nanos < 0 { sign, secs, nanos = "-", -1*secs, -1*nanos } x := fmt.Sprintf("%s%d.%09d", sign, secs, nanos) x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, ".000") e.WriteString(x + "s") return nil } func (d decoder) unmarshalDuration(m protoreflect.Message) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.String { return d.unexpectedTokenError(tok) } secs, nanos, ok := parseDuration(tok.ParsedString()) if !ok { return d.newError(tok.Pos(), "invalid %v value %v", genid.Duration_message_fullname, tok.RawString()) } // Validate seconds. No need to validate nanos because parseDuration would // have covered that already. if secs < -maxSecondsInDuration || secs > maxSecondsInDuration { return d.newError(tok.Pos(), "%v value out of range: %v", genid.Duration_message_fullname, tok.RawString()) } fds := m.Descriptor().Fields() fdSeconds := fds.ByNumber(genid.Duration_Seconds_field_number) fdNanos := fds.ByNumber(genid.Duration_Nanos_field_number) m.Set(fdSeconds, protoreflect.ValueOfInt64(secs)) m.Set(fdNanos, protoreflect.ValueOfInt32(nanos)) return nil } // parseDuration parses the given input string for seconds and nanoseconds value // for the Duration JSON format. The format is a decimal number with a suffix // 's'. It can have optional plus/minus sign. There needs to be at least an // integer or fractional part. Fractional part is limited to 9 digits only for // nanoseconds precision, regardless of whether there are trailing zero digits. // Example values are 1s, 0.1s, 1.s, .1s, +1s, -1s, -.1s. func parseDuration(input string) (int64, int32, bool) { b := []byte(input) size := len(b) if size < 2 { return 0, 0, false } if b[size-1] != 's' { return 0, 0, false } b = b[:size-1] // Read optional plus/minus symbol. var neg bool switch b[0] { case '-': neg = true b = b[1:] case '+': b = b[1:] } if len(b) == 0 { return 0, 0, false } // Read the integer part. var intp []byte switch { case b[0] == '0': b = b[1:] case '1' <= b[0] && b[0] <= '9': intp = b[0:] b = b[1:] n := 1 for len(b) > 0 && '0' <= b[0] && b[0] <= '9' { n++ b = b[1:] } intp = intp[:n] case b[0] == '.': // Continue below. default: return 0, 0, false } hasFrac := false var frac [9]byte if len(b) > 0 { if b[0] != '.' { return 0, 0, false } // Read the fractional part. b = b[1:] n := 0 for len(b) > 0 && n < 9 && '0' <= b[0] && b[0] <= '9' { frac[n] = b[0] n++ b = b[1:] } // It is not valid if there are more bytes left. if len(b) > 0 { return 0, 0, false } // Pad fractional part with 0s. for i := n; i < 9; i++ { frac[i] = '0' } hasFrac = true } var secs int64 if len(intp) > 0 { var err error secs, err = strconv.ParseInt(string(intp), 10, 64) if err != nil { return 0, 0, false } } var nanos int64 if hasFrac { nanob := bytes.TrimLeft(frac[:], "0") if len(nanob) > 0 { var err error nanos, err = strconv.ParseInt(string(nanob), 10, 32) if err != nil { return 0, 0, false } } } if neg { if secs > 0 { secs = -secs } if nanos > 0 { nanos = -nanos } } return secs, int32(nanos), true } // The JSON representation for a Timestamp is a JSON string in the RFC 3339 // format, i.e. "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" where // {year} is always expressed using four digits while {month}, {day}, {hour}, // {min}, and {sec} are zero-padded to two digits each. The fractional seconds, // which can go up to 9 digits, up to 1 nanosecond resolution, is optional. The // "Z" suffix indicates the timezone ("UTC"); the timezone is required. Encoding // should always use UTC (as indicated by "Z") and a decoder should be able to // accept both UTC and other timezones (as indicated by an offset). // // Timestamp.seconds must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z // inclusive. // Timestamp.nanos must be from 0 to 999,999,999 inclusive. const ( maxTimestampSeconds = 253402300799 minTimestampSeconds = -62135596800 ) func (e encoder) marshalTimestamp(m protoreflect.Message) error { fds := m.Descriptor().Fields() fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) secsVal := m.Get(fdSeconds) nanosVal := m.Get(fdNanos) secs := secsVal.Int() nanos := nanosVal.Int() if secs < minTimestampSeconds || secs > maxTimestampSeconds { return errors.New("%s: seconds out of range %v", genid.Timestamp_message_fullname, secs) } if nanos < 0 || nanos > secondsInNanos { return errors.New("%s: nanos out of range %v", genid.Timestamp_message_fullname, nanos) } // Uses RFC 3339, where generated output will be Z-normalized and uses 0, 3, // 6 or 9 fractional digits. t := time.Unix(secs, nanos).UTC() x := t.Format("2006-01-02T15:04:05.000000000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, "000") x = strings.TrimSuffix(x, ".000") e.WriteString(x + "Z") return nil } func (d decoder) unmarshalTimestamp(m protoreflect.Message) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.String { return d.unexpectedTokenError(tok) } s := tok.ParsedString() t, err := time.Parse(time.RFC3339Nano, s) if err != nil { return d.newError(tok.Pos(), "invalid %v value %v", genid.Timestamp_message_fullname, tok.RawString()) } // Validate seconds. secs := t.Unix() if secs < minTimestampSeconds || secs > maxTimestampSeconds { return d.newError(tok.Pos(), "%v value out of range: %v", genid.Timestamp_message_fullname, tok.RawString()) } // Validate subseconds. i := strings.LastIndexByte(s, '.') // start of subsecond field j := strings.LastIndexAny(s, "Z-+") // start of timezone field if i >= 0 && j >= i && j-i > len(".999999999") { return d.newError(tok.Pos(), "invalid %v value %v", genid.Timestamp_message_fullname, tok.RawString()) } fds := m.Descriptor().Fields() fdSeconds := fds.ByNumber(genid.Timestamp_Seconds_field_number) fdNanos := fds.ByNumber(genid.Timestamp_Nanos_field_number) m.Set(fdSeconds, protoreflect.ValueOfInt64(secs)) m.Set(fdNanos, protoreflect.ValueOfInt32(int32(t.Nanosecond()))) return nil } // The JSON representation for a FieldMask is a JSON string where paths are // separated by a comma. Fields name in each path are converted to/from // lower-camel naming conventions. Encoding should fail if the path name would // end up differently after a round-trip. func (e encoder) marshalFieldMask(m protoreflect.Message) error { fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) list := m.Get(fd).List() paths := make([]string, 0, list.Len()) for i := 0; i < list.Len(); i++ { s := list.Get(i).String() if !protoreflect.FullName(s).IsValid() { return errors.New("%s contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s) } // Return error if conversion to camelCase is not reversible. cc := strs.JSONCamelCase(s) if s != strs.JSONSnakeCase(cc) { return errors.New("%s contains irreversible value %q", genid.FieldMask_Paths_field_fullname, s) } paths = append(paths, cc) } e.WriteString(strings.Join(paths, ",")) return nil } func (d decoder) unmarshalFieldMask(m protoreflect.Message) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.String { return d.unexpectedTokenError(tok) } str := strings.TrimSpace(tok.ParsedString()) if str == "" { return nil } paths := strings.Split(str, ",") fd := m.Descriptor().Fields().ByNumber(genid.FieldMask_Paths_field_number) list := m.Mutable(fd).List() for _, s0 := range paths { s := strs.JSONSnakeCase(s0) if strings.Contains(s0, "_") || !protoreflect.FullName(s).IsValid() { return d.newError(tok.Pos(), "%v contains invalid path: %q", genid.FieldMask_Paths_field_fullname, s0) } list.Append(protoreflect.ValueOfString(s)) } 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/encoding/protojson/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protojson/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 protojson import ( "encoding/base64" "fmt" "google.golang.org/protobuf/internal/encoding/json" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) const defaultIndent = " " // Format formats the message as a multiline string. // This function is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func Format(m proto.Message) string { return MarshalOptions{Multiline: true}.Format(m) } // Marshal writes the given [proto.Message] in JSON format using default options. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func Marshal(m proto.Message) ([]byte, error) { return MarshalOptions{}.Marshal(m) } // MarshalOptions is a configurable JSON format marshaler. type MarshalOptions struct { pragma.NoUnkeyedLiterals // Multiline specifies whether the marshaler should format the output in // indented-form with every textual element on a new line. // If Indent is an empty string, then an arbitrary indent is chosen. Multiline bool // Indent specifies the set of indentation characters to use in a multiline // formatted output such that every entry is preceded by Indent and // terminated by a newline. If non-empty, then Multiline is treated as true. // Indent can only be composed of space or tab characters. Indent string // AllowPartial allows messages that have missing required fields to marshal // without returning an error. If AllowPartial is false (the default), // Marshal will return error if there are any missing required fields. AllowPartial bool // UseProtoNames uses proto field name instead of lowerCamelCase name in JSON // field names. UseProtoNames bool // UseEnumNumbers emits enum values as numbers. UseEnumNumbers bool // EmitUnpopulated specifies whether to emit unpopulated fields. It does not // emit unpopulated oneof fields or unpopulated extension fields. // The JSON value emitted for unpopulated fields are as follows: // ╔═══════╤════════════════════════════╗ // ║ JSON │ Protobuf field ║ // ╠═══════╪════════════════════════════╣ // ║ false │ proto3 boolean fields ║ // ║ 0 │ proto3 numeric fields ║ // ║ "" │ proto3 string/bytes fields ║ // ║ null │ proto2 scalar fields ║ // ║ null │ message fields ║ // ║ [] │ list fields ║ // ║ {} │ map fields ║ // ╚═══════╧════════════════════════════╝ EmitUnpopulated bool // EmitDefaultValues specifies whether to emit default-valued primitive fields, // empty lists, and empty maps. The fields affected are as follows: // ╔═══════╤════════════════════════════════════════╗ // ║ JSON │ Protobuf field ║ // ╠═══════╪════════════════════════════════════════╣ // ║ false │ non-optional scalar boolean fields ║ // ║ 0 │ non-optional scalar numeric fields ║ // ║ "" │ non-optional scalar string/byte fields ║ // ║ [] │ empty repeated fields ║ // ║ {} │ empty map fields ║ // ╚═══════╧════════════════════════════════════════╝ // // Behaves similarly to EmitUnpopulated, but does not emit "null"-value fields, // i.e. presence-sensing fields that are omitted will remain omitted to preserve // presence-sensing. // EmitUnpopulated takes precedence over EmitDefaultValues since the former generates // a strict superset of the latter. EmitDefaultValues bool // Resolver is used for looking up types when expanding google.protobuf.Any // messages. If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.ExtensionTypeResolver protoregistry.MessageTypeResolver } } // Format formats the message as a string. // This method is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func (o MarshalOptions) Format(m proto.Message) string { if m == nil || !m.ProtoReflect().IsValid() { return "<nil>" // invalid syntax, but okay since this is for debugging } o.AllowPartial = true b, _ := o.Marshal(m) return string(b) } // Marshal marshals the given [proto.Message] in the JSON format using options in // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { return o.marshal(nil, m) } // MarshalAppend appends the JSON format encoding of m to b, // returning the result. func (o MarshalOptions) MarshalAppend(b []byte, m proto.Message) ([]byte, error) { return o.marshal(b, m) } // marshal is a centralized function that all marshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for marshal that do not go through this. func (o MarshalOptions) marshal(b []byte, m proto.Message) ([]byte, error) { if o.Multiline && o.Indent == "" { o.Indent = defaultIndent } if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } internalEnc, err := json.NewEncoder(b, o.Indent) if err != nil { return nil, err } // Treat nil message interface as an empty message, // in which case the output in an empty JSON object. if m == nil { return append(b, '{', '}'), nil } enc := encoder{internalEnc, o} if err := enc.marshalMessage(m.ProtoReflect(), ""); err != nil { return nil, err } if o.AllowPartial { return enc.Bytes(), nil } return enc.Bytes(), proto.CheckInitialized(m) } type encoder struct { *json.Encoder opts MarshalOptions } // typeFieldDesc is a synthetic field descriptor used for the "@type" field. var typeFieldDesc = func() protoreflect.FieldDescriptor { var fd filedesc.Field fd.L0.FullName = "@type" fd.L0.Index = -1 fd.L1.Cardinality = protoreflect.Optional fd.L1.Kind = protoreflect.StringKind return &fd }() // typeURLFieldRanger wraps a protoreflect.Message and modifies its Range method // to additionally iterate over a synthetic field for the type URL. type typeURLFieldRanger struct { order.FieldRanger typeURL string } func (m typeURLFieldRanger) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { if !f(typeFieldDesc, protoreflect.ValueOfString(m.typeURL)) { return } m.FieldRanger.Range(f) } // unpopulatedFieldRanger wraps a protoreflect.Message and modifies its Range // method to additionally iterate over unpopulated fields. type unpopulatedFieldRanger struct { protoreflect.Message skipNull bool } func (m unpopulatedFieldRanger) Range(f func(protoreflect.FieldDescriptor, protoreflect.Value) bool) { fds := m.Descriptor().Fields() for i := 0; i < fds.Len(); i++ { fd := fds.Get(i) if m.Has(fd) || fd.ContainingOneof() != nil { continue // ignore populated fields and fields within a oneofs } v := m.Get(fd) if fd.HasPresence() { if m.skipNull { continue } v = protoreflect.Value{} // use invalid value to emit null } if !f(fd, v) { return } } m.Message.Range(f) } // marshalMessage marshals the fields in the given protoreflect.Message. // If the typeURL is non-empty, then a synthetic "@type" field is injected // containing the URL as the value. func (e encoder) marshalMessage(m protoreflect.Message, typeURL string) error { if !flags.ProtoLegacy && messageset.IsMessageSet(m.Descriptor()) { return errors.New("no support for proto1 MessageSets") } if marshal := wellKnownTypeMarshaler(m.Descriptor().FullName()); marshal != nil { return marshal(e, m) } e.StartObject() defer e.EndObject() var fields order.FieldRanger = m switch { case e.opts.EmitUnpopulated: fields = unpopulatedFieldRanger{Message: m, skipNull: false} case e.opts.EmitDefaultValues: fields = unpopulatedFieldRanger{Message: m, skipNull: true} } if typeURL != "" { fields = typeURLFieldRanger{fields, typeURL} } var err error order.RangeFields(fields, order.IndexNameFieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { name := fd.JSONName() if e.opts.UseProtoNames { name = fd.TextName() } if err = e.WriteName(name); err != nil { return false } if err = e.marshalValue(v, fd); err != nil { return false } return true }) return err } // marshalValue marshals the given protoreflect.Value. func (e encoder) marshalValue(val protoreflect.Value, fd protoreflect.FieldDescriptor) error { switch { case fd.IsList(): return e.marshalList(val.List(), fd) case fd.IsMap(): return e.marshalMap(val.Map(), fd) default: return e.marshalSingular(val, fd) } } // marshalSingular marshals the given non-repeated field value. This includes // all scalar types, enums, messages, and groups. func (e encoder) marshalSingular(val protoreflect.Value, fd protoreflect.FieldDescriptor) error { if !val.IsValid() { e.WriteNull() return nil } switch kind := fd.Kind(); kind { case protoreflect.BoolKind: e.WriteBool(val.Bool()) case protoreflect.StringKind: if e.WriteString(val.String()) != nil { return errors.InvalidUTF8(string(fd.FullName())) } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: e.WriteInt(val.Int()) case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: e.WriteUint(val.Uint()) case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Uint64Kind, protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind: // 64-bit integers are written out as JSON string. e.WriteString(val.String()) case protoreflect.FloatKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 32) case protoreflect.DoubleKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 64) case protoreflect.BytesKind: e.WriteString(base64.StdEncoding.EncodeToString(val.Bytes())) case protoreflect.EnumKind: if fd.Enum().FullName() == genid.NullValue_enum_fullname { e.WriteNull() } else { desc := fd.Enum().Values().ByNumber(val.Enum()) if e.opts.UseEnumNumbers || desc == nil { e.WriteInt(int64(val.Enum())) } else { e.WriteString(string(desc.Name())) } } case protoreflect.MessageKind, protoreflect.GroupKind: if err := e.marshalMessage(val.Message(), ""); err != nil { return err } default: panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) } return nil } // marshalList marshals the given protoreflect.List. func (e encoder) marshalList(list protoreflect.List, fd protoreflect.FieldDescriptor) error { e.StartArray() defer e.EndArray() for i := 0; i < list.Len(); i++ { item := list.Get(i) if err := e.marshalSingular(item, fd); err != nil { return err } } return nil } // marshalMap marshals given protoreflect.Map. func (e encoder) marshalMap(mmap protoreflect.Map, fd protoreflect.FieldDescriptor) error { e.StartObject() defer e.EndObject() var err error order.RangeEntries(mmap, order.GenericKeyOrder, func(k protoreflect.MapKey, v protoreflect.Value) bool { if err = e.WriteName(k.String()); err != nil { return false } if err = e.marshalSingular(v, fd.MapValue()); err != nil { return false } return true }) return 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/encoding/protojson/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protojson/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 protojson marshals and unmarshals protocol buffer messages as JSON // format. It follows the guide at // https://protobuf.dev/programming-guides/proto3#json. // // This package produces a different output than the standard [encoding/json] // package, which does not operate correctly on protocol buffer messages. package protojson
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/encoding/protojson/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protojson/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 protojson import ( "encoding/base64" "fmt" "math" "strconv" "strings" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/json" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/set" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Unmarshal reads the given []byte into the given [proto.Message]. // The provided message must be mutable (e.g., a non-nil pointer to a message). func Unmarshal(b []byte, m proto.Message) error { return UnmarshalOptions{}.Unmarshal(b, m) } // UnmarshalOptions is a configurable JSON format parser. type UnmarshalOptions struct { pragma.NoUnkeyedLiterals // If AllowPartial is set, input for messages that will result in missing // required fields will not return an error. AllowPartial bool // If DiscardUnknown is set, unknown fields and enum name values are ignored. DiscardUnknown bool // Resolver is used for looking up types when unmarshaling // google.protobuf.Any messages or extension fields. // If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.MessageTypeResolver protoregistry.ExtensionTypeResolver } // RecursionLimit limits how deeply messages may be nested. // If zero, a default limit is applied. RecursionLimit int } // Unmarshal reads the given []byte and populates the given [proto.Message] // using options in the UnmarshalOptions object. // It will clear the message first before setting the fields. // If it returns an error, the given message may be partially set. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { return o.unmarshal(b, m) } // unmarshal is a centralized function that all unmarshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for unmarshal that do not go through this. func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { proto.Reset(m) if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } if o.RecursionLimit == 0 { o.RecursionLimit = protowire.DefaultRecursionLimit } dec := decoder{json.NewDecoder(b), o} if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { return err } // Check for EOF. tok, err := dec.Read() if err != nil { return err } if tok.Kind() != json.EOF { return dec.unexpectedTokenError(tok) } if o.AllowPartial { return nil } return proto.CheckInitialized(m) } type decoder struct { *json.Decoder opts UnmarshalOptions } // newError returns an error object with position info. func (d decoder) newError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("(line %d:%d): ", line, column) return errors.New(head+f, x...) } // unexpectedTokenError returns a syntax error for the given unexpected token. func (d decoder) unexpectedTokenError(tok json.Token) error { return d.syntaxError(tok.Pos(), "unexpected token %s", tok.RawString()) } // syntaxError returns a syntax error for given position. func (d decoder) syntaxError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) return errors.New(head+f, x...) } // unmarshalMessage unmarshals a message into the given protoreflect.Message. func (d decoder) unmarshalMessage(m protoreflect.Message, skipTypeURL bool) error { d.opts.RecursionLimit-- if d.opts.RecursionLimit < 0 { return errors.New("exceeded max recursion depth") } if unmarshal := wellKnownTypeUnmarshaler(m.Descriptor().FullName()); unmarshal != nil { return unmarshal(d, m) } tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.ObjectOpen { return d.unexpectedTokenError(tok) } messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") } var seenNums set.Ints var seenOneofs set.Ints fieldDescs := messageDesc.Fields() for { // Read field name. tok, err := d.Read() if err != nil { return err } switch tok.Kind() { default: return d.unexpectedTokenError(tok) case json.ObjectClose: return nil case json.Name: // Continue below. } name := tok.Name() // Unmarshaling a non-custom embedded message in Any will contain the // JSON field "@type" which should be skipped because it is not a field // of the embedded message, but simply an artifact of the Any format. if skipTypeURL && name == "@type" { d.Read() continue } // Get the FieldDescriptor. var fd protoreflect.FieldDescriptor if strings.HasPrefix(name, "[") && strings.HasSuffix(name, "]") { // Only extension names are in [name] format. extName := protoreflect.FullName(name[1 : len(name)-1]) extType, err := d.opts.Resolver.FindExtensionByName(extName) if err != nil && err != protoregistry.NotFound { return d.newError(tok.Pos(), "unable to resolve %s: %v", tok.RawString(), err) } if extType != nil { fd = extType.TypeDescriptor() if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) } } } else { // The name can either be the JSON name or the proto field name. fd = fieldDescs.ByJSONName(name) if fd == nil { fd = fieldDescs.ByTextName(name) } } if fd == nil { // Field is unknown. if d.opts.DiscardUnknown { if err := d.skipJSONValue(); err != nil { return err } continue } return d.newError(tok.Pos(), "unknown field %v", tok.RawString()) } // Do not allow duplicate fields. num := uint64(fd.Number()) if seenNums.Has(num) { return d.newError(tok.Pos(), "duplicate field %v", tok.RawString()) } seenNums.Set(num) // No need to set values for JSON null unless the field type is // google.protobuf.Value or google.protobuf.NullValue. if tok, _ := d.Peek(); tok.Kind() == json.Null && !isKnownValue(fd) && !isNullValue(fd) { d.Read() continue } switch { case fd.IsList(): list := m.Mutable(fd).List() if err := d.unmarshalList(list, fd); err != nil { return err } case fd.IsMap(): mmap := m.Mutable(fd).Map() if err := d.unmarshalMap(mmap, fd); err != nil { return err } default: // If field is a oneof, check if it has already been set. if od := fd.ContainingOneof(); od != nil { idx := uint64(od.Index()) if seenOneofs.Has(idx) { return d.newError(tok.Pos(), "error parsing %s, oneof %v is already set", tok.RawString(), od.FullName()) } seenOneofs.Set(idx) } // Required or optional fields. if err := d.unmarshalSingular(m, fd); err != nil { return err } } } } func isKnownValue(fd protoreflect.FieldDescriptor) bool { md := fd.Message() return md != nil && md.FullName() == genid.Value_message_fullname } func isNullValue(fd protoreflect.FieldDescriptor) bool { ed := fd.Enum() return ed != nil && ed.FullName() == genid.NullValue_enum_fullname } // unmarshalSingular unmarshals to the non-repeated field specified // by the given FieldDescriptor. func (d decoder) unmarshalSingular(m protoreflect.Message, fd protoreflect.FieldDescriptor) error { var val protoreflect.Value var err error switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: val = m.NewField(fd) err = d.unmarshalMessage(val.Message(), false) default: val, err = d.unmarshalScalar(fd) } if err != nil { return err } if val.IsValid() { m.Set(fd, val) } return nil } // unmarshalScalar unmarshals to a scalar/enum protoreflect.Value specified by // the given FieldDescriptor. func (d decoder) unmarshalScalar(fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { const b32 int = 32 const b64 int = 64 tok, err := d.Read() if err != nil { return protoreflect.Value{}, err } kind := fd.Kind() switch kind { case protoreflect.BoolKind: if tok.Kind() == json.Bool { return protoreflect.ValueOfBool(tok.Bool()), nil } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if v, ok := unmarshalInt(tok, b32); ok { return v, nil } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if v, ok := unmarshalInt(tok, b64); ok { return v, nil } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if v, ok := unmarshalUint(tok, b32); ok { return v, nil } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if v, ok := unmarshalUint(tok, b64); ok { return v, nil } case protoreflect.FloatKind: if v, ok := unmarshalFloat(tok, b32); ok { return v, nil } case protoreflect.DoubleKind: if v, ok := unmarshalFloat(tok, b64); ok { return v, nil } case protoreflect.StringKind: if tok.Kind() == json.String { return protoreflect.ValueOfString(tok.ParsedString()), nil } case protoreflect.BytesKind: if v, ok := unmarshalBytes(tok); ok { return v, nil } case protoreflect.EnumKind: if v, ok := unmarshalEnum(tok, fd, d.opts.DiscardUnknown); ok { return v, nil } default: panic(fmt.Sprintf("unmarshalScalar: invalid scalar kind %v", kind)) } return protoreflect.Value{}, d.newError(tok.Pos(), "invalid value for %v field %v: %v", kind, fd.JSONName(), tok.RawString()) } func unmarshalInt(tok json.Token, bitSize int) (protoreflect.Value, bool) { switch tok.Kind() { case json.Number: return getInt(tok, bitSize) case json.String: // Decode number from string. s := strings.TrimSpace(tok.ParsedString()) if len(s) != len(tok.ParsedString()) { return protoreflect.Value{}, false } dec := json.NewDecoder([]byte(s)) tok, err := dec.Read() if err != nil { return protoreflect.Value{}, false } return getInt(tok, bitSize) } return protoreflect.Value{}, false } func getInt(tok json.Token, bitSize int) (protoreflect.Value, bool) { n, ok := tok.Int(bitSize) if !ok { return protoreflect.Value{}, false } if bitSize == 32 { return protoreflect.ValueOfInt32(int32(n)), true } return protoreflect.ValueOfInt64(n), true } func unmarshalUint(tok json.Token, bitSize int) (protoreflect.Value, bool) { switch tok.Kind() { case json.Number: return getUint(tok, bitSize) case json.String: // Decode number from string. s := strings.TrimSpace(tok.ParsedString()) if len(s) != len(tok.ParsedString()) { return protoreflect.Value{}, false } dec := json.NewDecoder([]byte(s)) tok, err := dec.Read() if err != nil { return protoreflect.Value{}, false } return getUint(tok, bitSize) } return protoreflect.Value{}, false } func getUint(tok json.Token, bitSize int) (protoreflect.Value, bool) { n, ok := tok.Uint(bitSize) if !ok { return protoreflect.Value{}, false } if bitSize == 32 { return protoreflect.ValueOfUint32(uint32(n)), true } return protoreflect.ValueOfUint64(n), true } func unmarshalFloat(tok json.Token, bitSize int) (protoreflect.Value, bool) { switch tok.Kind() { case json.Number: return getFloat(tok, bitSize) case json.String: s := tok.ParsedString() switch s { case "NaN": if bitSize == 32 { return protoreflect.ValueOfFloat32(float32(math.NaN())), true } return protoreflect.ValueOfFloat64(math.NaN()), true case "Infinity": if bitSize == 32 { return protoreflect.ValueOfFloat32(float32(math.Inf(+1))), true } return protoreflect.ValueOfFloat64(math.Inf(+1)), true case "-Infinity": if bitSize == 32 { return protoreflect.ValueOfFloat32(float32(math.Inf(-1))), true } return protoreflect.ValueOfFloat64(math.Inf(-1)), true } // Decode number from string. if len(s) != len(strings.TrimSpace(s)) { return protoreflect.Value{}, false } dec := json.NewDecoder([]byte(s)) tok, err := dec.Read() if err != nil { return protoreflect.Value{}, false } return getFloat(tok, bitSize) } return protoreflect.Value{}, false } func getFloat(tok json.Token, bitSize int) (protoreflect.Value, bool) { n, ok := tok.Float(bitSize) if !ok { return protoreflect.Value{}, false } if bitSize == 32 { return protoreflect.ValueOfFloat32(float32(n)), true } return protoreflect.ValueOfFloat64(n), true } func unmarshalBytes(tok json.Token) (protoreflect.Value, bool) { if tok.Kind() != json.String { return protoreflect.Value{}, false } s := tok.ParsedString() enc := base64.StdEncoding if strings.ContainsAny(s, "-_") { enc = base64.URLEncoding } if len(s)%4 != 0 { enc = enc.WithPadding(base64.NoPadding) } b, err := enc.DecodeString(s) if err != nil { return protoreflect.Value{}, false } return protoreflect.ValueOfBytes(b), true } func unmarshalEnum(tok json.Token, fd protoreflect.FieldDescriptor, discardUnknown bool) (protoreflect.Value, bool) { switch tok.Kind() { case json.String: // Lookup EnumNumber based on name. s := tok.ParsedString() if enumVal := fd.Enum().Values().ByName(protoreflect.Name(s)); enumVal != nil { return protoreflect.ValueOfEnum(enumVal.Number()), true } if discardUnknown { return protoreflect.Value{}, true } case json.Number: if n, ok := tok.Int(32); ok { return protoreflect.ValueOfEnum(protoreflect.EnumNumber(n)), true } case json.Null: // This is only valid for google.protobuf.NullValue. if isNullValue(fd) { return protoreflect.ValueOfEnum(0), true } } return protoreflect.Value{}, false } func (d decoder) unmarshalList(list protoreflect.List, fd protoreflect.FieldDescriptor) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.ArrayOpen { return d.unexpectedTokenError(tok) } switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: for { tok, err := d.Peek() if err != nil { return err } if tok.Kind() == json.ArrayClose { d.Read() return nil } val := list.NewElement() if err := d.unmarshalMessage(val.Message(), false); err != nil { return err } list.Append(val) } default: for { tok, err := d.Peek() if err != nil { return err } if tok.Kind() == json.ArrayClose { d.Read() return nil } val, err := d.unmarshalScalar(fd) if err != nil { return err } if val.IsValid() { list.Append(val) } } } return nil } func (d decoder) unmarshalMap(mmap protoreflect.Map, fd protoreflect.FieldDescriptor) error { tok, err := d.Read() if err != nil { return err } if tok.Kind() != json.ObjectOpen { return d.unexpectedTokenError(tok) } // Determine ahead whether map entry is a scalar type or a message type in // order to call the appropriate unmarshalMapValue func inside the for loop // below. var unmarshalMapValue func() (protoreflect.Value, error) switch fd.MapValue().Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: unmarshalMapValue = func() (protoreflect.Value, error) { val := mmap.NewValue() if err := d.unmarshalMessage(val.Message(), false); err != nil { return protoreflect.Value{}, err } return val, nil } default: unmarshalMapValue = func() (protoreflect.Value, error) { return d.unmarshalScalar(fd.MapValue()) } } Loop: for { // Read field name. tok, err := d.Read() if err != nil { return err } switch tok.Kind() { default: return d.unexpectedTokenError(tok) case json.ObjectClose: break Loop case json.Name: // Continue. } // Unmarshal field name. pkey, err := d.unmarshalMapKey(tok, fd.MapKey()) if err != nil { return err } // Check for duplicate field name. if mmap.Has(pkey) { return d.newError(tok.Pos(), "duplicate map key %v", tok.RawString()) } // Read and unmarshal field value. pval, err := unmarshalMapValue() if err != nil { return err } if pval.IsValid() { mmap.Set(pkey, pval) } } return nil } // unmarshalMapKey converts given token of Name kind into a protoreflect.MapKey. // A map key type is any integral or string type. func (d decoder) unmarshalMapKey(tok json.Token, fd protoreflect.FieldDescriptor) (protoreflect.MapKey, error) { const b32 = 32 const b64 = 64 const base10 = 10 name := tok.Name() kind := fd.Kind() switch kind { case protoreflect.StringKind: return protoreflect.ValueOfString(name).MapKey(), nil case protoreflect.BoolKind: switch name { case "true": return protoreflect.ValueOfBool(true).MapKey(), nil case "false": return protoreflect.ValueOfBool(false).MapKey(), nil } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if n, err := strconv.ParseInt(name, base10, b32); err == nil { return protoreflect.ValueOfInt32(int32(n)).MapKey(), nil } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if n, err := strconv.ParseInt(name, base10, b64); err == nil { return protoreflect.ValueOfInt64(int64(n)).MapKey(), nil } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if n, err := strconv.ParseUint(name, base10, b32); err == nil { return protoreflect.ValueOfUint32(uint32(n)).MapKey(), nil } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if n, err := strconv.ParseUint(name, base10, b64); err == nil { return protoreflect.ValueOfUint64(uint64(n)).MapKey(), nil } default: panic(fmt.Sprintf("invalid kind for map key: %v", kind)) } return protoreflect.MapKey{}, d.newError(tok.Pos(), "invalid value for %v key: %s", kind, tok.RawString()) }
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/encoding/prototext/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/prototext/encode.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 prototext import ( "fmt" "strconv" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) const defaultIndent = " " // Format formats the message as a multiline string. // This function is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func Format(m proto.Message) string { return MarshalOptions{Multiline: true}.Format(m) } // Marshal writes the given [proto.Message] in textproto format using default // options. Do not depend on the output being stable. Its output will change // across different builds of your program, even when using the same version of // the protobuf module. func Marshal(m proto.Message) ([]byte, error) { return MarshalOptions{}.Marshal(m) } // MarshalOptions is a configurable text format marshaler. type MarshalOptions struct { pragma.NoUnkeyedLiterals // Multiline specifies whether the marshaler should format the output in // indented-form with every textual element on a new line. // If Indent is an empty string, then an arbitrary indent is chosen. Multiline bool // Indent specifies the set of indentation characters to use in a multiline // formatted output such that every entry is preceded by Indent and // terminated by a newline. If non-empty, then Multiline is treated as true. // Indent can only be composed of space or tab characters. Indent string // EmitASCII specifies whether to format strings and bytes as ASCII only // as opposed to using UTF-8 encoding when possible. EmitASCII bool // allowInvalidUTF8 specifies whether to permit the encoding of strings // with invalid UTF-8. This is unexported as it is intended to only // be specified by the Format method. allowInvalidUTF8 bool // AllowPartial allows messages that have missing required fields to marshal // without returning an error. If AllowPartial is false (the default), // Marshal will return error if there are any missing required fields. AllowPartial bool // EmitUnknown specifies whether to emit unknown fields in the output. // If specified, the unmarshaler may be unable to parse the output. // The default is to exclude unknown fields. EmitUnknown bool // Resolver is used for looking up types when expanding google.protobuf.Any // messages. If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.ExtensionTypeResolver protoregistry.MessageTypeResolver } } // Format formats the message as a string. // This method is only intended for human consumption and ignores errors. // Do not depend on the output being stable. Its output will change across // different builds of your program, even when using the same version of the // protobuf module. func (o MarshalOptions) Format(m proto.Message) string { if m == nil || !m.ProtoReflect().IsValid() { return "<nil>" // invalid syntax, but okay since this is for debugging } o.allowInvalidUTF8 = true o.AllowPartial = true o.EmitUnknown = true b, _ := o.Marshal(m) return string(b) } // Marshal writes the given [proto.Message] in textproto format using options in // MarshalOptions object. Do not depend on the output being stable. Its output // will change across different builds of your program, even when using the // same version of the protobuf module. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) { return o.marshal(nil, m) } // MarshalAppend appends the textproto format encoding of m to b, // returning the result. func (o MarshalOptions) MarshalAppend(b []byte, m proto.Message) ([]byte, error) { return o.marshal(b, m) } // marshal is a centralized function that all marshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for marshal that do not go through this. func (o MarshalOptions) marshal(b []byte, m proto.Message) ([]byte, error) { var delims = [2]byte{'{', '}'} if o.Multiline && o.Indent == "" { o.Indent = defaultIndent } if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } internalEnc, err := text.NewEncoder(b, o.Indent, delims, o.EmitASCII) if err != nil { return nil, err } // Treat nil message interface as an empty message, // in which case there is nothing to output. if m == nil { return b, nil } enc := encoder{internalEnc, o} err = enc.marshalMessage(m.ProtoReflect(), false) if err != nil { return nil, err } out := enc.Bytes() if len(o.Indent) > 0 && len(out) > 0 { out = append(out, '\n') } if o.AllowPartial { return out, nil } return out, proto.CheckInitialized(m) } type encoder struct { *text.Encoder opts MarshalOptions } // marshalMessage marshals the given protoreflect.Message. func (e encoder) marshalMessage(m protoreflect.Message, inclDelims bool) error { messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") } if inclDelims { e.StartMessage() defer e.EndMessage() } // Handle Any expansion. if messageDesc.FullName() == genid.Any_message_fullname { if e.marshalAny(m) { return nil } // If unable to expand, continue on to marshal Any as a regular message. } // Marshal fields. var err error order.RangeFields(m, order.IndexNameFieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { if err = e.marshalField(fd.TextName(), v, fd); err != nil { return false } return true }) if err != nil { return err } // Marshal unknown fields. if e.opts.EmitUnknown { e.marshalUnknown(m.GetUnknown()) } return nil } // marshalField marshals the given field with protoreflect.Value. func (e encoder) marshalField(name string, val protoreflect.Value, fd protoreflect.FieldDescriptor) error { switch { case fd.IsList(): return e.marshalList(name, val.List(), fd) case fd.IsMap(): return e.marshalMap(name, val.Map(), fd) default: e.WriteName(name) return e.marshalSingular(val, fd) } } // marshalSingular marshals the given non-repeated field value. This includes // all scalar types, enums, messages, and groups. func (e encoder) marshalSingular(val protoreflect.Value, fd protoreflect.FieldDescriptor) error { kind := fd.Kind() switch kind { case protoreflect.BoolKind: e.WriteBool(val.Bool()) case protoreflect.StringKind: s := val.String() if !e.opts.allowInvalidUTF8 && strs.EnforceUTF8(fd) && !utf8.ValidString(s) { return errors.InvalidUTF8(string(fd.FullName())) } e.WriteString(s) case protoreflect.Int32Kind, protoreflect.Int64Kind, protoreflect.Sint32Kind, protoreflect.Sint64Kind, protoreflect.Sfixed32Kind, protoreflect.Sfixed64Kind: e.WriteInt(val.Int()) case protoreflect.Uint32Kind, protoreflect.Uint64Kind, protoreflect.Fixed32Kind, protoreflect.Fixed64Kind: e.WriteUint(val.Uint()) case protoreflect.FloatKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 32) case protoreflect.DoubleKind: // Encoder.WriteFloat handles the special numbers NaN and infinites. e.WriteFloat(val.Float(), 64) case protoreflect.BytesKind: e.WriteString(string(val.Bytes())) case protoreflect.EnumKind: num := val.Enum() if desc := fd.Enum().Values().ByNumber(num); desc != nil { e.WriteLiteral(string(desc.Name())) } else { // Use numeric value if there is no enum description. e.WriteInt(int64(num)) } case protoreflect.MessageKind, protoreflect.GroupKind: return e.marshalMessage(val.Message(), true) default: panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind)) } return nil } // marshalList marshals the given protoreflect.List as multiple name-value fields. func (e encoder) marshalList(name string, list protoreflect.List, fd protoreflect.FieldDescriptor) error { size := list.Len() for i := 0; i < size; i++ { e.WriteName(name) if err := e.marshalSingular(list.Get(i), fd); err != nil { return err } } return nil } // marshalMap marshals the given protoreflect.Map as multiple name-value fields. func (e encoder) marshalMap(name string, mmap protoreflect.Map, fd protoreflect.FieldDescriptor) error { var err error order.RangeEntries(mmap, order.GenericKeyOrder, func(key protoreflect.MapKey, val protoreflect.Value) bool { e.WriteName(name) e.StartMessage() defer e.EndMessage() e.WriteName(string(genid.MapEntry_Key_field_name)) err = e.marshalSingular(key.Value(), fd.MapKey()) if err != nil { return false } e.WriteName(string(genid.MapEntry_Value_field_name)) err = e.marshalSingular(val, fd.MapValue()) if err != nil { return false } return true }) return err } // marshalUnknown parses the given []byte and marshals fields out. // This function assumes proper encoding in the given []byte. func (e encoder) marshalUnknown(b []byte) { const dec = 10 const hex = 16 for len(b) > 0 { num, wtype, n := protowire.ConsumeTag(b) b = b[n:] e.WriteName(strconv.FormatInt(int64(num), dec)) switch wtype { case protowire.VarintType: var v uint64 v, n = protowire.ConsumeVarint(b) e.WriteUint(v) case protowire.Fixed32Type: var v uint32 v, n = protowire.ConsumeFixed32(b) e.WriteLiteral("0x" + strconv.FormatUint(uint64(v), hex)) case protowire.Fixed64Type: var v uint64 v, n = protowire.ConsumeFixed64(b) e.WriteLiteral("0x" + strconv.FormatUint(v, hex)) case protowire.BytesType: var v []byte v, n = protowire.ConsumeBytes(b) e.WriteString(string(v)) case protowire.StartGroupType: e.StartMessage() var v []byte v, n = protowire.ConsumeGroup(num, b) e.marshalUnknown(v) e.EndMessage() default: panic(fmt.Sprintf("prototext: error parsing unknown field wire type: %v", wtype)) } b = b[n:] } } // marshalAny marshals the given google.protobuf.Any message in expanded form. // It returns true if it was able to marshal, else false. func (e encoder) marshalAny(any protoreflect.Message) bool { // Construct the embedded message. fds := any.Descriptor().Fields() fdType := fds.ByNumber(genid.Any_TypeUrl_field_number) typeURL := any.Get(fdType).String() mt, err := e.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return false } m := mt.New().Interface() // Unmarshal bytes into embedded message. fdValue := fds.ByNumber(genid.Any_Value_field_number) value := any.Get(fdValue) err = proto.UnmarshalOptions{ AllowPartial: true, Resolver: e.opts.Resolver, }.Unmarshal(value.Bytes(), m) if err != nil { return false } // Get current encoder position. If marshaling fails, reset encoder output // back to this position. pos := e.Snapshot() // Field name is the proto field name enclosed in []. e.WriteName("[" + typeURL + "]") err = e.marshalMessage(m.ProtoReflect(), true) if err != nil { e.Reset(pos) 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/encoding/prototext/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/prototext/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 prototext marshals and unmarshals protocol buffer messages as the // textproto format. package prototext
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/encoding/prototext/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/prototext/decode.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 prototext import ( "fmt" "unicode/utf8" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/set" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Unmarshal reads the given []byte into the given [proto.Message]. // The provided message must be mutable (e.g., a non-nil pointer to a message). func Unmarshal(b []byte, m proto.Message) error { return UnmarshalOptions{}.Unmarshal(b, m) } // UnmarshalOptions is a configurable textproto format unmarshaler. type UnmarshalOptions struct { pragma.NoUnkeyedLiterals // AllowPartial accepts input for messages that will result in missing // required fields. If AllowPartial is false (the default), Unmarshal will // return error if there are any missing required fields. AllowPartial bool // DiscardUnknown specifies whether to ignore unknown fields when parsing. // An unknown field is any field whose field name or field number does not // resolve to any known or extension field in the message. // By default, unmarshal rejects unknown fields as an error. DiscardUnknown bool // Resolver is used for looking up types when unmarshaling // google.protobuf.Any messages or extension fields. // If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { protoregistry.MessageTypeResolver protoregistry.ExtensionTypeResolver } } // Unmarshal reads the given []byte and populates the given [proto.Message] // using options in the UnmarshalOptions object. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m proto.Message) error { return o.unmarshal(b, m) } // unmarshal is a centralized function that all unmarshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for unmarshal that do not go through this. func (o UnmarshalOptions) unmarshal(b []byte, m proto.Message) error { proto.Reset(m) if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } dec := decoder{text.NewDecoder(b), o} if err := dec.unmarshalMessage(m.ProtoReflect(), false); err != nil { return err } if o.AllowPartial { return nil } return proto.CheckInitialized(m) } type decoder struct { *text.Decoder opts UnmarshalOptions } // newError returns an error object with position info. func (d decoder) newError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("(line %d:%d): ", line, column) return errors.New(head+f, x...) } // unexpectedTokenError returns a syntax error for the given unexpected token. func (d decoder) unexpectedTokenError(tok text.Token) error { return d.syntaxError(tok.Pos(), "unexpected token: %s", tok.RawString()) } // syntaxError returns a syntax error for given position. func (d decoder) syntaxError(pos int, f string, x ...any) error { line, column := d.Position(pos) head := fmt.Sprintf("syntax error (line %d:%d): ", line, column) return errors.New(head+f, x...) } // unmarshalMessage unmarshals into the given protoreflect.Message. func (d decoder) unmarshalMessage(m protoreflect.Message, checkDelims bool) error { messageDesc := m.Descriptor() if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) { return errors.New("no support for proto1 MessageSets") } if messageDesc.FullName() == genid.Any_message_fullname { return d.unmarshalAny(m, checkDelims) } if checkDelims { tok, err := d.Read() if err != nil { return err } if tok.Kind() != text.MessageOpen { return d.unexpectedTokenError(tok) } } var seenNums set.Ints var seenOneofs set.Ints fieldDescs := messageDesc.Fields() for { // Read field name. tok, err := d.Read() if err != nil { return err } switch typ := tok.Kind(); typ { case text.Name: // Continue below. case text.EOF: if checkDelims { return text.ErrUnexpectedEOF } return nil default: if checkDelims && typ == text.MessageClose { return nil } return d.unexpectedTokenError(tok) } // Resolve the field descriptor. var name protoreflect.Name var fd protoreflect.FieldDescriptor var xt protoreflect.ExtensionType var xtErr error var isFieldNumberName bool switch tok.NameKind() { case text.IdentName: name = protoreflect.Name(tok.IdentName()) fd = fieldDescs.ByTextName(string(name)) case text.TypeName: // Handle extensions only. This code path is not for Any. xt, xtErr = d.opts.Resolver.FindExtensionByName(protoreflect.FullName(tok.TypeName())) case text.FieldNumber: isFieldNumberName = true num := protoreflect.FieldNumber(tok.FieldNumber()) if !num.IsValid() { return d.newError(tok.Pos(), "invalid field number: %d", num) } fd = fieldDescs.ByNumber(num) if fd == nil { xt, xtErr = d.opts.Resolver.FindExtensionByNumber(messageDesc.FullName(), num) } } if xt != nil { fd = xt.TypeDescriptor() if !messageDesc.ExtensionRanges().Has(fd.Number()) || fd.ContainingMessage().FullName() != messageDesc.FullName() { return d.newError(tok.Pos(), "message %v cannot be extended by %v", messageDesc.FullName(), fd.FullName()) } } else if xtErr != nil && xtErr != protoregistry.NotFound { return d.newError(tok.Pos(), "unable to resolve [%s]: %v", tok.RawString(), xtErr) } // Handle unknown fields. if fd == nil { if d.opts.DiscardUnknown || messageDesc.ReservedNames().Has(name) { d.skipValue() continue } return d.newError(tok.Pos(), "unknown field: %v", tok.RawString()) } // Handle fields identified by field number. if isFieldNumberName { // TODO: Add an option to permit parsing field numbers. // // This requires careful thought as the MarshalOptions.EmitUnknown // option allows formatting unknown fields as the field number and the // best-effort textual representation of the field value. In that case, // it may not be possible to unmarshal the value from a parser that does // have information about the unknown field. return d.newError(tok.Pos(), "cannot specify field by number: %v", tok.RawString()) } switch { case fd.IsList(): kind := fd.Kind() if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } list := m.Mutable(fd).List() if err := d.unmarshalList(fd, list); err != nil { return err } case fd.IsMap(): mmap := m.Mutable(fd).Map() if err := d.unmarshalMap(fd, mmap); err != nil { return err } default: kind := fd.Kind() if kind != protoreflect.MessageKind && kind != protoreflect.GroupKind && !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } // If field is a oneof, check if it has already been set. if od := fd.ContainingOneof(); od != nil { idx := uint64(od.Index()) if seenOneofs.Has(idx) { return d.newError(tok.Pos(), "error parsing %q, oneof %v is already set", tok.RawString(), od.FullName()) } seenOneofs.Set(idx) } num := uint64(fd.Number()) if seenNums.Has(num) { return d.newError(tok.Pos(), "non-repeated field %q is repeated", tok.RawString()) } if err := d.unmarshalSingular(fd, m); err != nil { return err } seenNums.Set(num) } } return nil } // unmarshalSingular unmarshals a non-repeated field value specified by the // given FieldDescriptor. func (d decoder) unmarshalSingular(fd protoreflect.FieldDescriptor, m protoreflect.Message) error { var val protoreflect.Value var err error switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: val = m.NewField(fd) err = d.unmarshalMessage(val.Message(), true) default: val, err = d.unmarshalScalar(fd) } if err == nil { m.Set(fd, val) } return err } // unmarshalScalar unmarshals a scalar/enum protoreflect.Value specified by the // given FieldDescriptor. func (d decoder) unmarshalScalar(fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { tok, err := d.Read() if err != nil { return protoreflect.Value{}, err } if tok.Kind() != text.Scalar { return protoreflect.Value{}, d.unexpectedTokenError(tok) } kind := fd.Kind() switch kind { case protoreflect.BoolKind: if b, ok := tok.Bool(); ok { return protoreflect.ValueOfBool(b), nil } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if n, ok := tok.Int32(); ok { return protoreflect.ValueOfInt32(n), nil } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if n, ok := tok.Int64(); ok { return protoreflect.ValueOfInt64(n), nil } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if n, ok := tok.Uint32(); ok { return protoreflect.ValueOfUint32(n), nil } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if n, ok := tok.Uint64(); ok { return protoreflect.ValueOfUint64(n), nil } case protoreflect.FloatKind: if n, ok := tok.Float32(); ok { return protoreflect.ValueOfFloat32(n), nil } case protoreflect.DoubleKind: if n, ok := tok.Float64(); ok { return protoreflect.ValueOfFloat64(n), nil } case protoreflect.StringKind: if s, ok := tok.String(); ok { if strs.EnforceUTF8(fd) && !utf8.ValidString(s) { return protoreflect.Value{}, d.newError(tok.Pos(), "contains invalid UTF-8") } return protoreflect.ValueOfString(s), nil } case protoreflect.BytesKind: if b, ok := tok.String(); ok { return protoreflect.ValueOfBytes([]byte(b)), nil } case protoreflect.EnumKind: if lit, ok := tok.Enum(); ok { // Lookup EnumNumber based on name. if enumVal := fd.Enum().Values().ByName(protoreflect.Name(lit)); enumVal != nil { return protoreflect.ValueOfEnum(enumVal.Number()), nil } } if num, ok := tok.Int32(); ok { return protoreflect.ValueOfEnum(protoreflect.EnumNumber(num)), nil } default: panic(fmt.Sprintf("invalid scalar kind %v", kind)) } return protoreflect.Value{}, d.newError(tok.Pos(), "invalid value for %v type: %v", kind, tok.RawString()) } // unmarshalList unmarshals into given protoreflect.List. A list value can // either be in [] syntax or simply just a single scalar/message value. func (d decoder) unmarshalList(fd protoreflect.FieldDescriptor, list protoreflect.List) error { tok, err := d.Peek() if err != nil { return err } switch fd.Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: switch tok.Kind() { case text.ListOpen: d.Read() for { tok, err := d.Peek() if err != nil { return err } switch tok.Kind() { case text.ListClose: d.Read() return nil case text.MessageOpen: pval := list.NewElement() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return err } list.Append(pval) default: return d.unexpectedTokenError(tok) } } case text.MessageOpen: pval := list.NewElement() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return err } list.Append(pval) return nil } default: switch tok.Kind() { case text.ListOpen: d.Read() for { tok, err := d.Peek() if err != nil { return err } switch tok.Kind() { case text.ListClose: d.Read() return nil case text.Scalar: pval, err := d.unmarshalScalar(fd) if err != nil { return err } list.Append(pval) default: return d.unexpectedTokenError(tok) } } case text.Scalar: pval, err := d.unmarshalScalar(fd) if err != nil { return err } list.Append(pval) return nil } } return d.unexpectedTokenError(tok) } // unmarshalMap unmarshals into given protoreflect.Map. A map value is a // textproto message containing {key: <kvalue>, value: <mvalue>}. func (d decoder) unmarshalMap(fd protoreflect.FieldDescriptor, mmap protoreflect.Map) error { // Determine ahead whether map entry is a scalar type or a message type in // order to call the appropriate unmarshalMapValue func inside // unmarshalMapEntry. var unmarshalMapValue func() (protoreflect.Value, error) switch fd.MapValue().Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: unmarshalMapValue = func() (protoreflect.Value, error) { pval := mmap.NewValue() if err := d.unmarshalMessage(pval.Message(), true); err != nil { return protoreflect.Value{}, err } return pval, nil } default: unmarshalMapValue = func() (protoreflect.Value, error) { return d.unmarshalScalar(fd.MapValue()) } } tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.MessageOpen: return d.unmarshalMapEntry(fd, mmap, unmarshalMapValue) case text.ListOpen: for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.ListClose: return nil case text.MessageOpen: if err := d.unmarshalMapEntry(fd, mmap, unmarshalMapValue); err != nil { return err } default: return d.unexpectedTokenError(tok) } } default: return d.unexpectedTokenError(tok) } } // unmarshalMap unmarshals into given protoreflect.Map. A map value is a // textproto message containing {key: <kvalue>, value: <mvalue>}. func (d decoder) unmarshalMapEntry(fd protoreflect.FieldDescriptor, mmap protoreflect.Map, unmarshalMapValue func() (protoreflect.Value, error)) error { var key protoreflect.MapKey var pval protoreflect.Value Loop: for { // Read field name. tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.Name: if tok.NameKind() != text.IdentName { if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "unknown map entry field %q", tok.RawString()) } d.skipValue() continue Loop } // Continue below. case text.MessageClose: break Loop default: return d.unexpectedTokenError(tok) } switch name := protoreflect.Name(tok.IdentName()); name { case genid.MapEntry_Key_field_name: if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } if key.IsValid() { return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) } val, err := d.unmarshalScalar(fd.MapKey()) if err != nil { return err } key = val.MapKey() case genid.MapEntry_Value_field_name: if kind := fd.MapValue().Kind(); (kind != protoreflect.MessageKind) && (kind != protoreflect.GroupKind) { if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } } if pval.IsValid() { return d.newError(tok.Pos(), "map entry %q cannot be repeated", name) } pval, err = unmarshalMapValue() if err != nil { return err } default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "unknown map entry field %q", name) } d.skipValue() } } if !key.IsValid() { key = fd.MapKey().Default().MapKey() } if !pval.IsValid() { switch fd.MapValue().Kind() { case protoreflect.MessageKind, protoreflect.GroupKind: // If value field is not set for message/group types, construct an // empty one as default. pval = mmap.NewValue() default: pval = fd.MapValue().Default() } } mmap.Set(key, pval) return nil } // unmarshalAny unmarshals an Any textproto. It can either be in expanded form // or non-expanded form. func (d decoder) unmarshalAny(m protoreflect.Message, checkDelims bool) error { var typeURL string var bValue []byte var seenTypeUrl bool var seenValue bool var isExpanded bool if checkDelims { tok, err := d.Read() if err != nil { return err } if tok.Kind() != text.MessageOpen { return d.unexpectedTokenError(tok) } } Loop: for { // Read field name. Can only have 3 possible field names, i.e. type_url, // value and type URL name inside []. tok, err := d.Read() if err != nil { return err } if typ := tok.Kind(); typ != text.Name { if checkDelims { if typ == text.MessageClose { break Loop } } else if typ == text.EOF { break Loop } return d.unexpectedTokenError(tok) } switch tok.NameKind() { case text.IdentName: // Both type_url and value fields require field separator :. if !tok.HasSeparator() { return d.syntaxError(tok.Pos(), "missing field separator :") } switch name := protoreflect.Name(tok.IdentName()); name { case genid.Any_TypeUrl_field_name: if seenTypeUrl { return d.newError(tok.Pos(), "duplicate %v field", genid.Any_TypeUrl_field_fullname) } if isExpanded { return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) } tok, err := d.Read() if err != nil { return err } var ok bool typeURL, ok = tok.String() if !ok { return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_TypeUrl_field_fullname, tok.RawString()) } seenTypeUrl = true case genid.Any_Value_field_name: if seenValue { return d.newError(tok.Pos(), "duplicate %v field", genid.Any_Value_field_fullname) } if isExpanded { return d.newError(tok.Pos(), "conflict with [%s] field", typeURL) } tok, err := d.Read() if err != nil { return err } s, ok := tok.String() if !ok { return d.newError(tok.Pos(), "invalid %v field value: %v", genid.Any_Value_field_fullname, tok.RawString()) } bValue = []byte(s) seenValue = true default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) } } case text.TypeName: if isExpanded { return d.newError(tok.Pos(), "cannot have more than one type") } if seenTypeUrl { return d.newError(tok.Pos(), "conflict with type_url field") } typeURL = tok.TypeName() var err error bValue, err = d.unmarshalExpandedAny(typeURL, tok.Pos()) if err != nil { return err } isExpanded = true default: if !d.opts.DiscardUnknown { return d.newError(tok.Pos(), "invalid field name %q in %v message", tok.RawString(), genid.Any_message_fullname) } } } fds := m.Descriptor().Fields() if len(typeURL) > 0 { m.Set(fds.ByNumber(genid.Any_TypeUrl_field_number), protoreflect.ValueOfString(typeURL)) } if len(bValue) > 0 { m.Set(fds.ByNumber(genid.Any_Value_field_number), protoreflect.ValueOfBytes(bValue)) } return nil } func (d decoder) unmarshalExpandedAny(typeURL string, pos int) ([]byte, error) { mt, err := d.opts.Resolver.FindMessageByURL(typeURL) if err != nil { return nil, d.newError(pos, "unable to resolve message [%v]: %v", typeURL, err) } // Create new message for the embedded message type and unmarshal the value // field into it. m := mt.New() if err := d.unmarshalMessage(m, true); err != nil { return nil, err } // Serialize the embedded message and return the resulting bytes. b, err := proto.MarshalOptions{ AllowPartial: true, // Never check required fields inside an Any. Deterministic: true, }.Marshal(m.Interface()) if err != nil { return nil, d.newError(pos, "error in marshaling message into Any.value: %v", err) } return b, nil } // skipValue makes the decoder parse a field value in order to advance the read // to the next field. It relies on Read returning an error if the types are not // in valid sequence. func (d decoder) skipValue() error { tok, err := d.Read() if err != nil { return err } // Only need to continue reading for messages and lists. switch tok.Kind() { case text.MessageOpen: return d.skipMessageValue() case text.ListOpen: for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.ListClose: return nil case text.MessageOpen: if err := d.skipMessageValue(); err != nil { return err } default: // Skip items. This will not validate whether skipped values are // of the same type or not, same behavior as C++ // TextFormat::Parser::AllowUnknownField(true) version 3.8.0. } } } return nil } // skipMessageValue makes the decoder parse and skip over all fields in a // message. It assumes that the previous read type is MessageOpen. func (d decoder) skipMessageValue() error { for { tok, err := d.Read() if err != nil { return err } switch tok.Kind() { case text.MessageClose: return nil case text.Name: if err := d.skipValue(); err != nil { return 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/encoding/protodelim/protodelim.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protodelim/protodelim.go
// Copyright 2022 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 protodelim marshals and unmarshals varint size-delimited messages. package protodelim import ( "bufio" "encoding/binary" "fmt" "io" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/proto" ) // MarshalOptions is a configurable varint size-delimited marshaler. type MarshalOptions struct{ proto.MarshalOptions } // MarshalTo writes a varint size-delimited wire-format message to w. // If w returns an error, MarshalTo returns it unchanged. func (o MarshalOptions) MarshalTo(w io.Writer, m proto.Message) (int, error) { msgBytes, err := o.MarshalOptions.Marshal(m) if err != nil { return 0, err } sizeBytes := protowire.AppendVarint(nil, uint64(len(msgBytes))) sizeWritten, err := w.Write(sizeBytes) if err != nil { return sizeWritten, err } msgWritten, err := w.Write(msgBytes) if err != nil { return sizeWritten + msgWritten, err } return sizeWritten + msgWritten, nil } // MarshalTo writes a varint size-delimited wire-format message to w // with the default options. // // See the documentation for [MarshalOptions.MarshalTo]. func MarshalTo(w io.Writer, m proto.Message) (int, error) { return MarshalOptions{}.MarshalTo(w, m) } // UnmarshalOptions is a configurable varint size-delimited unmarshaler. type UnmarshalOptions struct { proto.UnmarshalOptions // MaxSize is the maximum size in wire-format bytes of a single message. // Unmarshaling a message larger than MaxSize will return an error. // A zero MaxSize will default to 4 MiB. // Setting MaxSize to -1 disables the limit. MaxSize int64 } const defaultMaxSize = 4 << 20 // 4 MiB, corresponds to the default gRPC max request/response size // SizeTooLargeError is an error that is returned when the unmarshaler encounters a message size // that is larger than its configured [UnmarshalOptions.MaxSize]. type SizeTooLargeError struct { // Size is the varint size of the message encountered // that was larger than the provided MaxSize. Size uint64 // MaxSize is the MaxSize limit configured in UnmarshalOptions, which Size exceeded. MaxSize uint64 } func (e *SizeTooLargeError) Error() string { return fmt.Sprintf("message size %d exceeded unmarshaler's maximum configured size %d", e.Size, e.MaxSize) } // Reader is the interface expected by [UnmarshalFrom]. // It is implemented by *[bufio.Reader]. type Reader interface { io.Reader io.ByteReader } // UnmarshalFrom parses and consumes a varint size-delimited wire-format message // from r. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // The error is [io.EOF] error only if no bytes are read. // If an EOF happens after reading some but not all the bytes, // UnmarshalFrom returns a non-io.EOF error. // In particular if r returns a non-io.EOF error, UnmarshalFrom returns it unchanged, // and if only a size is read with no subsequent message, [io.ErrUnexpectedEOF] is returned. func (o UnmarshalOptions) UnmarshalFrom(r Reader, m proto.Message) error { var sizeArr [binary.MaxVarintLen64]byte sizeBuf := sizeArr[:0] for i := range sizeArr { b, err := r.ReadByte() if err != nil { // Immediate EOF is unexpected. if err == io.EOF && i != 0 { break } return err } sizeBuf = append(sizeBuf, b) if b < 0x80 { break } } size, n := protowire.ConsumeVarint(sizeBuf) if n < 0 { return protowire.ParseError(n) } maxSize := o.MaxSize if maxSize == 0 { maxSize = defaultMaxSize } if maxSize != -1 && size > uint64(maxSize) { return errors.Wrap(&SizeTooLargeError{Size: size, MaxSize: uint64(maxSize)}, "") } var b []byte var err error if br, ok := r.(*bufio.Reader); ok { // Use the []byte from the bufio.Reader instead of having to allocate one. // This reduces CPU usage and allocated bytes. b, err = br.Peek(int(size)) if err == nil { defer br.Discard(int(size)) } else { b = nil } } if b == nil { b = make([]byte, size) _, err = io.ReadFull(r, b) } if err == io.EOF { return io.ErrUnexpectedEOF } if err != nil { return err } if err := o.Unmarshal(b, m); err != nil { return err } return nil } // UnmarshalFrom parses and consumes a varint size-delimited wire-format message // from r with the default options. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // See the documentation for [UnmarshalOptions.UnmarshalFrom]. func UnmarshalFrom(r Reader, m proto.Message) error { return UnmarshalOptions{}.UnmarshalFrom(r, 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/encoding/protowire/wire.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/encoding/protowire/wire.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 protowire parses and formats the raw wire encoding. // See https://protobuf.dev/programming-guides/encoding. // // For marshaling and unmarshaling entire protobuf messages, // use the [google.golang.org/protobuf/proto] package instead. package protowire import ( "io" "math" "math/bits" "google.golang.org/protobuf/internal/errors" ) // Number represents the field number. type Number int32 const ( MinValidNumber Number = 1 FirstReservedNumber Number = 19000 LastReservedNumber Number = 19999 MaxValidNumber Number = 1<<29 - 1 DefaultRecursionLimit = 10000 ) // IsValid reports whether the field number is semantically valid. func (n Number) IsValid() bool { return MinValidNumber <= n && n <= MaxValidNumber } // Type represents the wire type. type Type int8 const ( VarintType Type = 0 Fixed32Type Type = 5 Fixed64Type Type = 1 BytesType Type = 2 StartGroupType Type = 3 EndGroupType Type = 4 ) const ( _ = -iota errCodeTruncated errCodeFieldNumber errCodeOverflow errCodeReserved errCodeEndGroup errCodeRecursionDepth ) var ( errFieldNumber = errors.New("invalid field number") errOverflow = errors.New("variable length integer overflow") errReserved = errors.New("cannot parse reserved wire type") errEndGroup = errors.New("mismatching end group marker") errParse = errors.New("parse error") ) // ParseError converts an error code into an error value. // This returns nil if n is a non-negative number. func ParseError(n int) error { if n >= 0 { return nil } switch n { case errCodeTruncated: return io.ErrUnexpectedEOF case errCodeFieldNumber: return errFieldNumber case errCodeOverflow: return errOverflow case errCodeReserved: return errReserved case errCodeEndGroup: return errEndGroup default: return errParse } } // ConsumeField parses an entire field record (both tag and value) and returns // the field number, the wire type, and the total length. // This returns a negative length upon an error (see [ParseError]). // // The total length includes the tag header and the end group marker (if the // field is a group). func ConsumeField(b []byte) (Number, Type, int) { num, typ, n := ConsumeTag(b) if n < 0 { return 0, 0, n // forward error code } m := ConsumeFieldValue(num, typ, b[n:]) if m < 0 { return 0, 0, m // forward error code } return num, typ, n + m } // ConsumeFieldValue parses a field value and returns its length. // This assumes that the field [Number] and wire [Type] have already been parsed. // This returns a negative length upon an error (see [ParseError]). // // When parsing a group, the length includes the end group marker and // the end group is verified to match the starting field number. func ConsumeFieldValue(num Number, typ Type, b []byte) (n int) { return consumeFieldValueD(num, typ, b, DefaultRecursionLimit) } func consumeFieldValueD(num Number, typ Type, b []byte, depth int) (n int) { switch typ { case VarintType: _, n = ConsumeVarint(b) return n case Fixed32Type: _, n = ConsumeFixed32(b) return n case Fixed64Type: _, n = ConsumeFixed64(b) return n case BytesType: _, n = ConsumeBytes(b) return n case StartGroupType: if depth < 0 { return errCodeRecursionDepth } n0 := len(b) for { num2, typ2, n := ConsumeTag(b) if n < 0 { return n // forward error code } b = b[n:] if typ2 == EndGroupType { if num != num2 { return errCodeEndGroup } return n0 - len(b) } n = consumeFieldValueD(num2, typ2, b, depth-1) if n < 0 { return n // forward error code } b = b[n:] } case EndGroupType: return errCodeEndGroup default: return errCodeReserved } } // AppendTag encodes num and typ as a varint-encoded tag and appends it to b. func AppendTag(b []byte, num Number, typ Type) []byte { return AppendVarint(b, EncodeTag(num, typ)) } // ConsumeTag parses b as a varint-encoded tag, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeTag(b []byte) (Number, Type, int) { v, n := ConsumeVarint(b) if n < 0 { return 0, 0, n // forward error code } num, typ := DecodeTag(v) if num < MinValidNumber { return 0, 0, errCodeFieldNumber } return num, typ, n } func SizeTag(num Number) int { return SizeVarint(EncodeTag(num, 0)) // wire type has no effect on size } // AppendVarint appends v to b as a varint-encoded uint64. func AppendVarint(b []byte, v uint64) []byte { switch { case v < 1<<7: b = append(b, byte(v)) case v < 1<<14: b = append(b, byte((v>>0)&0x7f|0x80), byte(v>>7)) case v < 1<<21: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte(v>>14)) case v < 1<<28: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte(v>>21)) case v < 1<<35: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte(v>>28)) case v < 1<<42: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte(v>>35)) case v < 1<<49: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte(v>>42)) case v < 1<<56: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte(v>>49)) case v < 1<<63: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte((v>>49)&0x7f|0x80), byte(v>>56)) default: b = append(b, byte((v>>0)&0x7f|0x80), byte((v>>7)&0x7f|0x80), byte((v>>14)&0x7f|0x80), byte((v>>21)&0x7f|0x80), byte((v>>28)&0x7f|0x80), byte((v>>35)&0x7f|0x80), byte((v>>42)&0x7f|0x80), byte((v>>49)&0x7f|0x80), byte((v>>56)&0x7f|0x80), 1) } return b } // ConsumeVarint parses b as a varint-encoded uint64, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeVarint(b []byte) (v uint64, n int) { var y uint64 if len(b) <= 0 { return 0, errCodeTruncated } v = uint64(b[0]) if v < 0x80 { return v, 1 } v -= 0x80 if len(b) <= 1 { return 0, errCodeTruncated } y = uint64(b[1]) v += y << 7 if y < 0x80 { return v, 2 } v -= 0x80 << 7 if len(b) <= 2 { return 0, errCodeTruncated } y = uint64(b[2]) v += y << 14 if y < 0x80 { return v, 3 } v -= 0x80 << 14 if len(b) <= 3 { return 0, errCodeTruncated } y = uint64(b[3]) v += y << 21 if y < 0x80 { return v, 4 } v -= 0x80 << 21 if len(b) <= 4 { return 0, errCodeTruncated } y = uint64(b[4]) v += y << 28 if y < 0x80 { return v, 5 } v -= 0x80 << 28 if len(b) <= 5 { return 0, errCodeTruncated } y = uint64(b[5]) v += y << 35 if y < 0x80 { return v, 6 } v -= 0x80 << 35 if len(b) <= 6 { return 0, errCodeTruncated } y = uint64(b[6]) v += y << 42 if y < 0x80 { return v, 7 } v -= 0x80 << 42 if len(b) <= 7 { return 0, errCodeTruncated } y = uint64(b[7]) v += y << 49 if y < 0x80 { return v, 8 } v -= 0x80 << 49 if len(b) <= 8 { return 0, errCodeTruncated } y = uint64(b[8]) v += y << 56 if y < 0x80 { return v, 9 } v -= 0x80 << 56 if len(b) <= 9 { return 0, errCodeTruncated } y = uint64(b[9]) v += y << 63 if y < 2 { return v, 10 } return 0, errCodeOverflow } // SizeVarint returns the encoded size of a varint. // The size is guaranteed to be within 1 and 10, inclusive. func SizeVarint(v uint64) int { // This computes 1 + (bits.Len64(v)-1)/7. // 9/64 is a good enough approximation of 1/7 // // The Go compiler can translate the bits.LeadingZeros64 call into the LZCNT // instruction, which is very fast on CPUs from the last few years. The // specific way of expressing the calculation matches C++ Protobuf, see // https://godbolt.org/z/4P3h53oM4 for the C++ code and how gcc/clang // optimize that function for GOAMD64=v1 and GOAMD64=v3 (-march=haswell). // By OR'ing v with 1, we guarantee that v is never 0, without changing the // result of SizeVarint. LZCNT is not defined for 0, meaning the compiler // needs to add extra instructions to handle that case. // // The Go compiler currently (go1.24.4) does not make use of this knowledge. // This opportunity (removing the XOR instruction, which handles the 0 case) // results in a small (1%) performance win across CPU architectures. // // Independently of avoiding the 0 case, we need the v |= 1 line because // it allows the Go compiler to eliminate an extra XCHGL barrier. v |= 1 // It would be clearer to write log2value := 63 - uint32(...), but // writing uint32(...) ^ 63 is much more efficient (-14% ARM, -20% Intel). // Proof of identity for our value range [0..63]: // https://go.dev/play/p/Pdn9hEWYakX log2value := uint32(bits.LeadingZeros64(v)) ^ 63 return int((log2value*9 + (64 + 9)) / 64) } // AppendFixed32 appends v to b as a little-endian uint32. func AppendFixed32(b []byte, v uint32) []byte { return append(b, byte(v>>0), byte(v>>8), byte(v>>16), byte(v>>24)) } // ConsumeFixed32 parses b as a little-endian uint32, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeFixed32(b []byte) (v uint32, n int) { if len(b) < 4 { return 0, errCodeTruncated } v = uint32(b[0])<<0 | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 return v, 4 } // SizeFixed32 returns the encoded size of a fixed32; which is always 4. func SizeFixed32() int { return 4 } // AppendFixed64 appends v to b as a little-endian uint64. func AppendFixed64(b []byte, v uint64) []byte { return append(b, byte(v>>0), byte(v>>8), byte(v>>16), byte(v>>24), byte(v>>32), byte(v>>40), byte(v>>48), byte(v>>56)) } // ConsumeFixed64 parses b as a little-endian uint64, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeFixed64(b []byte) (v uint64, n int) { if len(b) < 8 { return 0, errCodeTruncated } v = uint64(b[0])<<0 | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 return v, 8 } // SizeFixed64 returns the encoded size of a fixed64; which is always 8. func SizeFixed64() int { return 8 } // AppendBytes appends v to b as a length-prefixed bytes value. func AppendBytes(b []byte, v []byte) []byte { return append(AppendVarint(b, uint64(len(v))), v...) } // ConsumeBytes parses b as a length-prefixed bytes value, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeBytes(b []byte) (v []byte, n int) { m, n := ConsumeVarint(b) if n < 0 { return nil, n // forward error code } if m > uint64(len(b[n:])) { return nil, errCodeTruncated } return b[n:][:m], n + int(m) } // SizeBytes returns the encoded size of a length-prefixed bytes value, // given only the length. func SizeBytes(n int) int { return SizeVarint(uint64(n)) + n } // AppendString appends v to b as a length-prefixed bytes value. func AppendString(b []byte, v string) []byte { return append(AppendVarint(b, uint64(len(v))), v...) } // ConsumeString parses b as a length-prefixed bytes value, reporting its length. // This returns a negative length upon an error (see [ParseError]). func ConsumeString(b []byte) (v string, n int) { bb, n := ConsumeBytes(b) return string(bb), n } // AppendGroup appends v to b as group value, with a trailing end group marker. // The value v must not contain the end marker. func AppendGroup(b []byte, num Number, v []byte) []byte { return AppendVarint(append(b, v...), EncodeTag(num, EndGroupType)) } // ConsumeGroup parses b as a group value until the trailing end group marker, // and verifies that the end marker matches the provided num. The value v // does not contain the end marker, while the length does contain the end marker. // This returns a negative length upon an error (see [ParseError]). func ConsumeGroup(num Number, b []byte) (v []byte, n int) { n = ConsumeFieldValue(num, StartGroupType, b) if n < 0 { return nil, n // forward error code } b = b[:n] // Truncate off end group marker, but need to handle denormalized varints. // Assuming end marker is never 0 (which is always the case since // EndGroupType is non-zero), we can truncate all trailing bytes where the // lower 7 bits are all zero (implying that the varint is denormalized). for len(b) > 0 && b[len(b)-1]&0x7f == 0 { b = b[:len(b)-1] } b = b[:len(b)-SizeTag(num)] return b, n } // SizeGroup returns the encoded size of a group, given only the length. func SizeGroup(num Number, n int) int { return n + SizeTag(num) } // DecodeTag decodes the field [Number] and wire [Type] from its unified form. // The [Number] is -1 if the decoded field number overflows int32. // Other than overflow, this does not check for field number validity. func DecodeTag(x uint64) (Number, Type) { // NOTE: MessageSet allows for larger field numbers than normal. if x>>3 > uint64(math.MaxInt32) { return -1, 0 } return Number(x >> 3), Type(x & 7) } // EncodeTag encodes the field [Number] and wire [Type] into its unified form. func EncodeTag(num Number, typ Type) uint64 { return uint64(num)<<3 | uint64(typ&7) } // DecodeZigZag decodes a zig-zag-encoded uint64 as an int64. // // Input: {…, 5, 3, 1, 0, 2, 4, 6, …} // Output: {…, -3, -2, -1, 0, +1, +2, +3, …} func DecodeZigZag(x uint64) int64 { return int64(x>>1) ^ int64(x)<<63>>63 } // EncodeZigZag encodes an int64 as a zig-zag-encoded uint64. // // Input: {…, -3, -2, -1, 0, +1, +2, +3, …} // Output: {…, 5, 3, 1, 0, 2, 4, 6, …} func EncodeZigZag(x int64) uint64 { return uint64(x<<1) ^ uint64(x>>63) } // DecodeBool decodes a uint64 as a bool. // // Input: { 0, 1, 2, …} // Output: {false, true, true, …} func DecodeBool(x uint64) bool { return x != 0 } // EncodeBool encodes a bool as a uint64. // // Input: {false, true} // Output: { 0, 1} func EncodeBool(x bool) uint64 { if x { return 1 } return 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/proto/merge.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/merge.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 proto import ( "fmt" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Merge merges src into dst, which must be a message with the same descriptor. // // Populated scalar fields in src are copied to dst, while populated // singular messages in src are merged into dst by recursively calling Merge. // The elements of every list field in src is appended to the corresponded // list fields in dst. The entries of every map field in src is copied into // the corresponding map field in dst, possibly replacing existing entries. // The unknown fields of src are appended to the unknown fields of dst. // // It is semantically equivalent to unmarshaling the encoded form of src // into dst with the [UnmarshalOptions.Merge] option specified. func Merge(dst, src Message) { // TODO: Should nil src be treated as semantically equivalent to a // untyped, read-only, empty message? What about a nil dst? dstMsg, srcMsg := dst.ProtoReflect(), src.ProtoReflect() if dstMsg.Descriptor() != srcMsg.Descriptor() { if got, want := dstMsg.Descriptor().FullName(), srcMsg.Descriptor().FullName(); got != want { panic(fmt.Sprintf("descriptor mismatch: %v != %v", got, want)) } panic("descriptor mismatch") } mergeOptions{}.mergeMessage(dstMsg, srcMsg) } // Clone returns a deep copy of m. // If the top-level message is invalid, it returns an invalid message as well. func Clone(m Message) Message { // NOTE: Most usages of Clone assume the following properties: // t := reflect.TypeOf(m) // t == reflect.TypeOf(m.ProtoReflect().New().Interface()) // t == reflect.TypeOf(m.ProtoReflect().Type().Zero().Interface()) // // Embedding protobuf messages breaks this since the parent type will have // a forwarded ProtoReflect method, but the Interface method will return // the underlying embedded message type. if m == nil { return nil } src := m.ProtoReflect() if !src.IsValid() { return src.Type().Zero().Interface() } dst := src.New() mergeOptions{}.mergeMessage(dst, src) return dst.Interface() } // CloneOf returns a deep copy of m. If the top-level message is invalid, // it returns an invalid message as well. func CloneOf[M Message](m M) M { return Clone(m).(M) } // mergeOptions provides a namespace for merge functions, and can be // exported in the future if we add user-visible merge options. type mergeOptions struct{} func (o mergeOptions) mergeMessage(dst, src protoreflect.Message) { methods := protoMethods(dst) if methods != nil && methods.Merge != nil { in := protoiface.MergeInput{ Destination: dst, Source: src, } out := methods.Merge(in) if out.Flags&protoiface.MergeComplete != 0 { return } } if !dst.IsValid() { panic(fmt.Sprintf("cannot merge into invalid %v message", dst.Descriptor().FullName())) } src.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { switch { case fd.IsList(): o.mergeList(dst.Mutable(fd).List(), v.List(), fd) case fd.IsMap(): o.mergeMap(dst.Mutable(fd).Map(), v.Map(), fd.MapValue()) case fd.Message() != nil: o.mergeMessage(dst.Mutable(fd).Message(), v.Message()) case fd.Kind() == protoreflect.BytesKind: dst.Set(fd, o.cloneBytes(v)) default: dst.Set(fd, v) } return true }) if len(src.GetUnknown()) > 0 { dst.SetUnknown(append(dst.GetUnknown(), src.GetUnknown()...)) } } func (o mergeOptions) mergeList(dst, src protoreflect.List, fd protoreflect.FieldDescriptor) { // Merge semantics appends to the end of the existing list. for i, n := 0, src.Len(); i < n; i++ { switch v := src.Get(i); { case fd.Message() != nil: dstv := dst.NewElement() o.mergeMessage(dstv.Message(), v.Message()) dst.Append(dstv) case fd.Kind() == protoreflect.BytesKind: dst.Append(o.cloneBytes(v)) default: dst.Append(v) } } } func (o mergeOptions) mergeMap(dst, src protoreflect.Map, fd protoreflect.FieldDescriptor) { // Merge semantics replaces, rather than merges into existing entries. src.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { switch { case fd.Message() != nil: dstv := dst.NewValue() o.mergeMessage(dstv.Message(), v.Message()) dst.Set(k, dstv) case fd.Kind() == protoreflect.BytesKind: dst.Set(k, o.cloneBytes(v)) default: dst.Set(k, v) } return true }) } func (o mergeOptions) cloneBytes(v protoreflect.Value) protoreflect.Value { return protoreflect.ValueOfBytes(append([]byte{}, v.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/proto/size.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/size.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 proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Size returns the size in bytes of the wire-format encoding of m. // // Note that Size might return more bytes than Marshal will write in the case of // lazily decoded messages that arrive in non-minimal wire format: see // https://protobuf.dev/reference/go/size/ for more details. func Size(m Message) int { return MarshalOptions{}.Size(m) } // Size returns the size in bytes of the wire-format encoding of m. // // Note that Size might return more bytes than Marshal will write in the case of // lazily decoded messages that arrive in non-minimal wire format: see // https://protobuf.dev/reference/go/size/ for more details. func (o MarshalOptions) Size(m Message) int { // Treat a nil message interface as an empty message; nothing to output. if m == nil { return 0 } return o.size(m.ProtoReflect()) } // size is a centralized function that all size operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for size that do not go through this. func (o MarshalOptions) size(m protoreflect.Message) (size int) { methods := protoMethods(m) if methods != nil && methods.Size != nil { out := methods.Size(protoiface.SizeInput{ Message: m, Flags: o.flags(), }) return out.Size } if methods != nil && methods.Marshal != nil { // This is not efficient, but we don't have any choice. // This case is mainly used for legacy types with a Marshal method. out, _ := methods.Marshal(protoiface.MarshalInput{ Message: m, Flags: o.flags(), }) return len(out.Buf) } return o.sizeMessageSlow(m) } func (o MarshalOptions) sizeMessageSlow(m protoreflect.Message) (size int) { if messageset.IsMessageSet(m.Descriptor()) { return o.sizeMessageSet(m) } m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { size += o.sizeField(fd, v) return true }) size += len(m.GetUnknown()) return size } func (o MarshalOptions) sizeField(fd protoreflect.FieldDescriptor, value protoreflect.Value) (size int) { num := fd.Number() switch { case fd.IsList(): return o.sizeList(num, fd, value.List()) case fd.IsMap(): return o.sizeMap(num, fd, value.Map()) default: return protowire.SizeTag(num) + o.sizeSingular(num, fd.Kind(), value) } } func (o MarshalOptions) sizeList(num protowire.Number, fd protoreflect.FieldDescriptor, list protoreflect.List) (size int) { sizeTag := protowire.SizeTag(num) if fd.IsPacked() && list.Len() > 0 { content := 0 for i, llen := 0, list.Len(); i < llen; i++ { content += o.sizeSingular(num, fd.Kind(), list.Get(i)) } return sizeTag + protowire.SizeBytes(content) } for i, llen := 0, list.Len(); i < llen; i++ { size += sizeTag + o.sizeSingular(num, fd.Kind(), list.Get(i)) } return size } func (o MarshalOptions) sizeMap(num protowire.Number, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) (size int) { sizeTag := protowire.SizeTag(num) mapv.Range(func(key protoreflect.MapKey, value protoreflect.Value) bool { size += sizeTag size += protowire.SizeBytes(o.sizeField(fd.MapKey(), key.Value()) + o.sizeField(fd.MapValue(), value)) return true }) return size }
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/proto/checkinit.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto import ( "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // CheckInitialized returns an error if any required fields in m are not set. func CheckInitialized(m Message) error { // Treat a nil message interface as an "untyped" empty message, // which we assume to have no required fields. if m == nil { return nil } return checkInitialized(m.ProtoReflect()) } // CheckInitialized returns an error if any required fields in m are not set. func checkInitialized(m protoreflect.Message) error { if methods := protoMethods(m); methods != nil && methods.CheckInitialized != nil { _, err := methods.CheckInitialized(protoiface.CheckInitializedInput{ Message: m, }) return err } return checkInitializedSlow(m) } func checkInitializedSlow(m protoreflect.Message) error { md := m.Descriptor() fds := md.Fields() for i, nums := 0, md.RequiredNumbers(); i < nums.Len(); i++ { fd := fds.ByNumber(nums.Get(i)) if !m.Has(fd) { return errors.RequiredNotSet(string(fd.FullName())) } } var err error m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { switch { case fd.IsList(): if fd.Message() == nil { return true } for i, list := 0, v.List(); i < list.Len() && err == nil; i++ { err = checkInitialized(list.Get(i).Message()) } case fd.IsMap(): if fd.MapValue().Message() == nil { return true } v.Map().Range(func(key protoreflect.MapKey, v protoreflect.Value) bool { err = checkInitialized(v.Message()) return err == nil }) default: if fd.Message() == nil { return true } err = checkInitialized(v.Message()) } return err == nil }) return 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/proto/messageset.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto import ( "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" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) func (o MarshalOptions) sizeMessageSet(m protoreflect.Message) (size int) { m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { size += messageset.SizeField(fd.Number()) size += protowire.SizeTag(messageset.FieldMessage) size += protowire.SizeBytes(o.size(v.Message())) return true }) size += messageset.SizeUnknown(m.GetUnknown()) return size } func (o MarshalOptions) marshalMessageSet(b []byte, m protoreflect.Message) ([]byte, error) { if !flags.ProtoLegacy { return b, errors.New("no support for message_set_wire_format") } fieldOrder := order.AnyFieldOrder if o.Deterministic { fieldOrder = order.NumberFieldOrder } var err error order.RangeFields(m, fieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { b, err = o.marshalMessageSetField(b, fd, v) return err == nil }) if err != nil { return b, err } return messageset.AppendUnknown(b, m.GetUnknown()) } func (o MarshalOptions) marshalMessageSetField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { b = messageset.AppendFieldStart(b, fd.Number()) b = protowire.AppendTag(b, messageset.FieldMessage, protowire.BytesType) calculatedSize := o.Size(value.Message().Interface()) b = protowire.AppendVarint(b, uint64(calculatedSize)) before := len(b) b, err := o.marshalMessage(b, value.Message()) if err != nil { return b, err } if measuredSize := len(b) - before; calculatedSize != measuredSize { return nil, errors.MismatchedSizeCalculation(calculatedSize, measuredSize) } b = messageset.AppendFieldEnd(b) return b, nil } func (o UnmarshalOptions) unmarshalMessageSet(b []byte, m protoreflect.Message) error { if !flags.ProtoLegacy { return errors.New("no support for message_set_wire_format") } return messageset.Unmarshal(b, false, func(num protowire.Number, v []byte) error { err := o.unmarshalMessageSetField(m, num, v) if err == errUnknown { unknown := m.GetUnknown() unknown = protowire.AppendTag(unknown, num, protowire.BytesType) unknown = protowire.AppendBytes(unknown, v) m.SetUnknown(unknown) return nil } return err }) } func (o UnmarshalOptions) unmarshalMessageSetField(m protoreflect.Message, num protowire.Number, v []byte) error { md := m.Descriptor() if !md.ExtensionRanges().Has(num) { return errUnknown } xt, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) if err == protoregistry.NotFound { return errUnknown } if err != nil { return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) } xd := xt.TypeDescriptor() if err := o.unmarshalMessage(v, m.Mutable(xd).Message()); err != nil { return err } 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/proto/reset.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/reset.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 proto import ( "fmt" "google.golang.org/protobuf/reflect/protoreflect" ) // Reset clears every field in the message. // The resulting message shares no observable memory with its previous state // other than the memory for the message itself. func Reset(m Message) { if mr, ok := m.(interface{ Reset() }); ok && hasProtoMethods { mr.Reset() return } resetMessage(m.ProtoReflect()) } func resetMessage(m protoreflect.Message) { if !m.IsValid() { panic(fmt.Sprintf("cannot reset invalid %v message", m.Descriptor().FullName())) } // Clear all known fields. fds := m.Descriptor().Fields() for i := 0; i < fds.Len(); i++ { m.Clear(fds.Get(i)) } // Clear extension fields. m.Range(func(fd protoreflect.FieldDescriptor, _ protoreflect.Value) bool { m.Clear(fd) return true }) // Clear unknown fields. m.SetUnknown(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/proto/size_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/size_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 proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/reflect/protoreflect" ) func (o MarshalOptions) sizeSingular(num protowire.Number, kind protoreflect.Kind, v protoreflect.Value) int { switch kind { case protoreflect.BoolKind: return protowire.SizeVarint(protowire.EncodeBool(v.Bool())) case protoreflect.EnumKind: return protowire.SizeVarint(uint64(v.Enum())) case protoreflect.Int32Kind: return protowire.SizeVarint(uint64(int32(v.Int()))) case protoreflect.Sint32Kind: return protowire.SizeVarint(protowire.EncodeZigZag(int64(int32(v.Int())))) case protoreflect.Uint32Kind: return protowire.SizeVarint(uint64(uint32(v.Uint()))) case protoreflect.Int64Kind: return protowire.SizeVarint(uint64(v.Int())) case protoreflect.Sint64Kind: return protowire.SizeVarint(protowire.EncodeZigZag(v.Int())) case protoreflect.Uint64Kind: return protowire.SizeVarint(v.Uint()) case protoreflect.Sfixed32Kind: return protowire.SizeFixed32() case protoreflect.Fixed32Kind: return protowire.SizeFixed32() case protoreflect.FloatKind: return protowire.SizeFixed32() case protoreflect.Sfixed64Kind: return protowire.SizeFixed64() case protoreflect.Fixed64Kind: return protowire.SizeFixed64() case protoreflect.DoubleKind: return protowire.SizeFixed64() case protoreflect.StringKind: return protowire.SizeBytes(len(v.String())) case protoreflect.BytesKind: return protowire.SizeBytes(len(v.Bytes())) case protoreflect.MessageKind: return protowire.SizeBytes(o.size(v.Message())) case protoreflect.GroupKind: return protowire.SizeGroup(num, o.size(v.Message())) default: return 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/proto/proto_reflect.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/proto_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. // The protoreflect build tag disables use of fast-path methods. //go:build protoreflect // +build protoreflect package proto import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) const hasProtoMethods = false func protoMethods(m protoreflect.Message) *protoiface.Methods { 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/proto/encode_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/encode_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 proto import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) var wireTypes = map[protoreflect.Kind]protowire.Type{ protoreflect.BoolKind: protowire.VarintType, protoreflect.EnumKind: protowire.VarintType, protoreflect.Int32Kind: protowire.VarintType, protoreflect.Sint32Kind: protowire.VarintType, protoreflect.Uint32Kind: protowire.VarintType, protoreflect.Int64Kind: protowire.VarintType, protoreflect.Sint64Kind: protowire.VarintType, protoreflect.Uint64Kind: protowire.VarintType, protoreflect.Sfixed32Kind: protowire.Fixed32Type, protoreflect.Fixed32Kind: protowire.Fixed32Type, protoreflect.FloatKind: protowire.Fixed32Type, protoreflect.Sfixed64Kind: protowire.Fixed64Type, protoreflect.Fixed64Kind: protowire.Fixed64Type, protoreflect.DoubleKind: protowire.Fixed64Type, protoreflect.StringKind: protowire.BytesType, protoreflect.BytesKind: protowire.BytesType, protoreflect.MessageKind: protowire.BytesType, protoreflect.GroupKind: protowire.StartGroupType, } func (o MarshalOptions) marshalSingular(b []byte, fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]byte, error) { switch fd.Kind() { case protoreflect.BoolKind: b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) case protoreflect.EnumKind: b = protowire.AppendVarint(b, uint64(v.Enum())) case protoreflect.Int32Kind: b = protowire.AppendVarint(b, uint64(int32(v.Int()))) case protoreflect.Sint32Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) case protoreflect.Uint32Kind: b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) case protoreflect.Int64Kind: b = protowire.AppendVarint(b, uint64(v.Int())) case protoreflect.Sint64Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) case protoreflect.Uint64Kind: b = protowire.AppendVarint(b, v.Uint()) case protoreflect.Sfixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Int())) case protoreflect.Fixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Uint())) case protoreflect.FloatKind: b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) case protoreflect.Sfixed64Kind: b = protowire.AppendFixed64(b, uint64(v.Int())) case protoreflect.Fixed64Kind: b = protowire.AppendFixed64(b, v.Uint()) case protoreflect.DoubleKind: b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) case protoreflect.StringKind: if strs.EnforceUTF8(fd) && !utf8.ValidString(v.String()) { return b, errors.InvalidUTF8(string(fd.FullName())) } b = protowire.AppendString(b, v.String()) case protoreflect.BytesKind: b = protowire.AppendBytes(b, v.Bytes()) case protoreflect.MessageKind: var pos int var err error b, pos = appendSpeculativeLength(b) b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = finishSpeculativeLength(b, pos) case protoreflect.GroupKind: var err error b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = protowire.AppendVarint(b, protowire.EncodeTag(fd.Number(), protowire.EndGroupType)) default: return b, errors.New("invalid kind %v", fd.Kind()) } 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/proto/proto.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/proto.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 proto import ( "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) // Message is the top-level interface that all messages must implement. // It provides access to a reflective view of a message. // Any implementation of this interface may be used with all functions in the // protobuf module that accept a Message, except where otherwise specified. // // This is the v2 interface definition for protobuf messages. // The v1 interface definition is [github.com/golang/protobuf/proto.Message]. // // - To convert a v1 message to a v2 message, // use [google.golang.org/protobuf/protoadapt.MessageV2Of]. // - To convert a v2 message to a v1 message, // use [google.golang.org/protobuf/protoadapt.MessageV1Of]. type Message = protoreflect.ProtoMessage // Error matches all errors produced by packages in the protobuf module // according to [errors.Is]. // // Example usage: // // if errors.Is(err, proto.Error) { ... } var Error error func init() { Error = errors.Error } // MessageName returns the full name of m. // If m is nil, it returns an empty string. func MessageName(m Message) protoreflect.FullName { if m == nil { return "" } return m.ProtoReflect().Descriptor().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/proto/equal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/equal.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 proto import ( "reflect" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) // Equal reports whether two messages are equal, // by recursively comparing the fields of the message. // // - Bytes fields are equal if they contain identical bytes. // Empty bytes (regardless of nil-ness) are considered equal. // // - Floating-point fields are equal if they contain the same value. // Unlike the == operator, a NaN is equal to another NaN. // // - Other scalar fields are equal if they contain the same value. // // - Message fields are equal if they have // the same set of populated known and extension field values, and // the same set of unknown fields values. // // - Lists are equal if they are the same length and // each corresponding element is equal. // // - Maps are equal if they have the same set of keys and // the corresponding value for each key is equal. // // An invalid message is not equal to a valid message. // An invalid message is only equal to another invalid message of the // same type. An invalid message often corresponds to a nil pointer // of the concrete message type. For example, (*pb.M)(nil) is not equal // to &pb.M{}. // If two valid messages marshal to the same bytes under deterministic // serialization, then Equal is guaranteed to report true. func Equal(x, y Message) bool { if x == nil || y == nil { return x == nil && y == nil } if reflect.TypeOf(x).Kind() == reflect.Ptr && x == y { // Avoid an expensive comparison if both inputs are identical pointers. return true } mx := x.ProtoReflect() my := y.ProtoReflect() if mx.IsValid() != my.IsValid() { return false } // Only one of the messages needs to implement the fast-path for it to work. pmx := protoMethods(mx) pmy := protoMethods(my) if pmx != nil && pmy != nil && pmx.Equal != nil && pmy.Equal != nil { return pmx.Equal(protoiface.EqualInput{MessageA: mx, MessageB: my}).Equal } vx := protoreflect.ValueOfMessage(mx) vy := protoreflect.ValueOfMessage(my) return vx.Equal(vy) }
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/proto/decode_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/decode_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 proto import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // unmarshalScalar decodes a value of the given kind. // // Message values are decoded into a []byte which aliases the input data. func (o UnmarshalOptions) unmarshalScalar(b []byte, wtyp protowire.Type, fd protoreflect.FieldDescriptor) (val protoreflect.Value, n int, err error) { switch fd.Kind() { case protoreflect.BoolKind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBool(protowire.DecodeBool(v)), n, nil case protoreflect.EnumKind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfEnum(protoreflect.EnumNumber(v)), n, nil case protoreflect.Int32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(v)), n, nil case protoreflect.Sint32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32))), n, nil case protoreflect.Uint32Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint32(uint32(v)), n, nil case protoreflect.Int64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(int64(v)), n, nil case protoreflect.Sint64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(protowire.DecodeZigZag(v)), n, nil case protoreflect.Uint64Kind: if wtyp != protowire.VarintType { return val, 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint64(v), n, nil case protoreflect.Sfixed32Kind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt32(int32(v)), n, nil case protoreflect.Fixed32Kind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint32(uint32(v)), n, nil case protoreflect.FloatKind: if wtyp != protowire.Fixed32Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v))), n, nil case protoreflect.Sfixed64Kind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfInt64(int64(v)), n, nil case protoreflect.Fixed64Kind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfUint64(v), n, nil case protoreflect.DoubleKind: if wtyp != protowire.Fixed64Type { return val, 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfFloat64(math.Float64frombits(v)), n, nil case protoreflect.StringKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } if strs.EnforceUTF8(fd) && !utf8.Valid(v) { return protoreflect.Value{}, 0, errors.InvalidUTF8(string(fd.FullName())) } return protoreflect.ValueOfString(string(v)), n, nil case protoreflect.BytesKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(append(emptyBuf[:], v...)), n, nil case protoreflect.MessageKind: if wtyp != protowire.BytesType { return val, 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(v), n, nil case protoreflect.GroupKind: if wtyp != protowire.StartGroupType { return val, 0, errUnknown } v, n := protowire.ConsumeGroup(fd.Number(), b) if n < 0 { return val, 0, errDecode } return protoreflect.ValueOfBytes(v), n, nil default: return val, 0, errUnknown } } func (o UnmarshalOptions) unmarshalList(b []byte, wtyp protowire.Type, list protoreflect.List, fd protoreflect.FieldDescriptor) (n int, err error) { switch fd.Kind() { case protoreflect.BoolKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfBool(protowire.DecodeBool(v))) return n, nil case protoreflect.EnumKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfEnum(protoreflect.EnumNumber(v))) return n, nil case protoreflect.Int32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) return n, nil case protoreflect.Sint32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(protowire.DecodeZigZag(v & math.MaxUint32)))) return n, nil case protoreflect.Uint32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint32(uint32(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint32(uint32(v))) return n, nil case protoreflect.Int64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(int64(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(int64(v))) return n, nil case protoreflect.Sint64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(protowire.DecodeZigZag(v))) return n, nil case protoreflect.Uint64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeVarint(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint64(v)) } return n, nil } if wtyp != protowire.VarintType { return 0, errUnknown } v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint64(v)) return n, nil case protoreflect.Sfixed32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt32(int32(v))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt32(int32(v))) return n, nil case protoreflect.Fixed32Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint32(uint32(v))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint32(uint32(v))) return n, nil case protoreflect.FloatKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed32(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) } return n, nil } if wtyp != protowire.Fixed32Type { return 0, errUnknown } v, n := protowire.ConsumeFixed32(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfFloat32(math.Float32frombits(uint32(v)))) return n, nil case protoreflect.Sfixed64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfInt64(int64(v))) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfInt64(int64(v))) return n, nil case protoreflect.Fixed64Kind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfUint64(v)) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfUint64(v)) return n, nil case protoreflect.DoubleKind: if wtyp == protowire.BytesType { buf, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } for len(buf) > 0 { v, n := protowire.ConsumeFixed64(buf) if n < 0 { return 0, errDecode } buf = buf[n:] list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) } return n, nil } if wtyp != protowire.Fixed64Type { return 0, errUnknown } v, n := protowire.ConsumeFixed64(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfFloat64(math.Float64frombits(v))) return n, nil case protoreflect.StringKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } if strs.EnforceUTF8(fd) && !utf8.Valid(v) { return 0, errors.InvalidUTF8(string(fd.FullName())) } list.Append(protoreflect.ValueOfString(string(v))) return n, nil case protoreflect.BytesKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } list.Append(protoreflect.ValueOfBytes(append(emptyBuf[:], v...))) return n, nil case protoreflect.MessageKind: if wtyp != protowire.BytesType { return 0, errUnknown } v, n := protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } m := list.NewElement() if err := o.unmarshalMessage(v, m.Message()); err != nil { return 0, err } list.Append(m) return n, nil case protoreflect.GroupKind: if wtyp != protowire.StartGroupType { return 0, errUnknown } v, n := protowire.ConsumeGroup(fd.Number(), b) if n < 0 { return 0, errDecode } m := list.NewElement() if err := o.unmarshalMessage(v, m.Message()); err != nil { return 0, err } list.Append(m) return n, nil default: return 0, errUnknown } } // We append to an empty array rather than a nil []byte to get non-nil zero-length byte slices. var emptyBuf [0]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/proto/proto_methods.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/proto_methods.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. // The protoreflect build tag disables use of fast-path methods. //go:build !protoreflect // +build !protoreflect package proto import ( "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" ) const hasProtoMethods = true func protoMethods(m protoreflect.Message) *protoiface.Methods { return m.ProtoMethods() }
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/proto/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto import ( "errors" "fmt" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/order" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/runtime/protoiface" protoerrors "google.golang.org/protobuf/internal/errors" ) // MarshalOptions configures the marshaler. // // Example usage: // // b, err := MarshalOptions{Deterministic: true}.Marshal(m) type MarshalOptions struct { pragma.NoUnkeyedLiterals // AllowPartial allows messages that have missing required fields to marshal // without returning an error. If AllowPartial is false (the default), // Marshal will return an error if there are any missing required fields. AllowPartial bool // Deterministic controls whether the same message will always be // serialized to the same bytes within the same binary. // // Setting this option guarantees that repeated serialization of // the same message will return the same bytes, and that different // processes of the same binary (which may be executing on different // machines) will serialize equal messages to the same bytes. // It has no effect on the resulting size of the encoded message compared // to a non-deterministic marshal. // // Note that the deterministic serialization is NOT canonical across // languages. It is not guaranteed to remain stable over time. It is // unstable across different builds with schema changes due to unknown // fields. Users who need canonical serialization (e.g., persistent // storage in a canonical form, fingerprinting, etc.) must define // their own canonicalization specification and implement their own // serializer rather than relying on this API. // // If deterministic serialization is requested, map entries will be // sorted by keys in lexographical order. This is an implementation // detail and subject to change. Deterministic bool // UseCachedSize indicates that the result of a previous Size call // may be reused. // // Setting this option asserts that: // // 1. Size has previously been called on this message with identical // options (except for UseCachedSize itself). // // 2. The message and all its submessages have not changed in any // way since the Size call. For lazily decoded messages, accessing // a message results in decoding the message, which is a change. // // If either of these invariants is violated, // the results are undefined and may include panics or corrupted output. // // Implementations MAY take this option into account to provide // better performance, but there is no guarantee that they will do so. // There is absolutely no guarantee that Size followed by Marshal with // UseCachedSize set will perform equivalently to Marshal alone. UseCachedSize bool } // flags turns the specified MarshalOptions (user-facing) into // protoiface.MarshalInputFlags (used internally by the marshaler). // // See impl.marshalOptions.Options for the inverse operation. func (o MarshalOptions) flags() protoiface.MarshalInputFlags { var flags protoiface.MarshalInputFlags // Note: o.AllowPartial is always forced to true by MarshalOptions.marshal, // which is why it is not a part of MarshalInputFlags. if o.Deterministic { flags |= protoiface.MarshalDeterministic } if o.UseCachedSize { flags |= protoiface.MarshalUseCachedSize } return flags } // Marshal returns the wire-format encoding of m. // // This is the most common entry point for encoding a Protobuf message. // // See the [MarshalOptions] type if you need more control. func Marshal(m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to output. if m == nil { return nil, nil } out, err := MarshalOptions{}.marshal(nil, m.ProtoReflect()) if len(out.Buf) == 0 && err == nil { out.Buf = emptyBytesForMessage(m) } return out.Buf, err } // Marshal returns the wire-format encoding of m. func (o MarshalOptions) Marshal(m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to output. if m == nil { return nil, nil } out, err := o.marshal(nil, m.ProtoReflect()) if len(out.Buf) == 0 && err == nil { out.Buf = emptyBytesForMessage(m) } return out.Buf, err } // emptyBytesForMessage returns a nil buffer if and only if m is invalid, // otherwise it returns a non-nil empty buffer. // // This is to assist the edge-case where user-code does the following: // // m1.OptionalBytes, _ = proto.Marshal(m2) // // where they expect the proto2 "optional_bytes" field to be populated // if any only if m2 is a valid message. func emptyBytesForMessage(m Message) []byte { if m == nil || !m.ProtoReflect().IsValid() { return nil } return emptyBuf[:] } // MarshalAppend appends the wire-format encoding of m to b, // returning the result. // // This is a less common entry point than [Marshal], which is only needed if you // need to supply your own buffers for performance reasons. func (o MarshalOptions) MarshalAppend(b []byte, m Message) ([]byte, error) { // Treat nil message interface as an empty message; nothing to append. if m == nil { return b, nil } out, err := o.marshal(b, m.ProtoReflect()) return out.Buf, err } // MarshalState returns the wire-format encoding of a message. // // This method permits fine-grained control over the marshaler. // Most users should use [Marshal] instead. func (o MarshalOptions) MarshalState(in protoiface.MarshalInput) (protoiface.MarshalOutput, error) { return o.marshal(in.Buf, in.Message) } // marshal is a centralized function that all marshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for marshal that do not go through this. func (o MarshalOptions) marshal(b []byte, m protoreflect.Message) (out protoiface.MarshalOutput, err error) { allowPartial := o.AllowPartial o.AllowPartial = true if methods := protoMethods(m); methods != nil && methods.Marshal != nil && !(o.Deterministic && methods.Flags&protoiface.SupportMarshalDeterministic == 0) { in := protoiface.MarshalInput{ Message: m, Buf: b, Flags: o.flags(), } if methods.Size != nil { sout := methods.Size(protoiface.SizeInput{ Message: m, Flags: in.Flags, }) if cap(b) < len(b)+sout.Size { in.Buf = make([]byte, len(b), growcap(cap(b), len(b)+sout.Size)) copy(in.Buf, b) } in.Flags |= protoiface.MarshalUseCachedSize } out, err = methods.Marshal(in) } else { out.Buf, err = o.marshalMessageSlow(b, m) } if err != nil { var mismatch *protoerrors.SizeMismatchError if errors.As(err, &mismatch) { return out, fmt.Errorf("marshaling %s: %v", string(m.Descriptor().FullName()), err) } return out, err } if allowPartial { return out, nil } return out, checkInitialized(m) } func (o MarshalOptions) marshalMessage(b []byte, m protoreflect.Message) ([]byte, error) { out, err := o.marshal(b, m) return out.Buf, err } // growcap scales up the capacity of a slice. // // Given a slice with a current capacity of oldcap and a desired // capacity of wantcap, growcap returns a new capacity >= wantcap. // // The algorithm is mostly identical to the one used by append as of Go 1.14. func growcap(oldcap, wantcap int) (newcap int) { if wantcap > oldcap*2 { newcap = wantcap } else if oldcap < 1024 { // The Go 1.14 runtime takes this case when len(s) < 1024, // not when cap(s) < 1024. The difference doesn't seem // significant here. newcap = oldcap * 2 } else { newcap = oldcap for 0 < newcap && newcap < wantcap { newcap += newcap / 4 } if newcap <= 0 { newcap = wantcap } } return newcap } func (o MarshalOptions) marshalMessageSlow(b []byte, m protoreflect.Message) ([]byte, error) { if messageset.IsMessageSet(m.Descriptor()) { return o.marshalMessageSet(b, m) } fieldOrder := order.AnyFieldOrder if o.Deterministic { // TODO: This should use a more natural ordering like NumberFieldOrder, // but doing so breaks golden tests that make invalid assumption about // output stability of this implementation. fieldOrder = order.LegacyFieldOrder } var err error order.RangeFields(m, fieldOrder, func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { b, err = o.marshalField(b, fd, v) return err == nil }) if err != nil { return b, err } b = append(b, m.GetUnknown()...) return b, nil } func (o MarshalOptions) marshalField(b []byte, fd protoreflect.FieldDescriptor, value protoreflect.Value) ([]byte, error) { switch { case fd.IsList(): return o.marshalList(b, fd, value.List()) case fd.IsMap(): return o.marshalMap(b, fd, value.Map()) default: b = protowire.AppendTag(b, fd.Number(), wireTypes[fd.Kind()]) return o.marshalSingular(b, fd, value) } } func (o MarshalOptions) marshalList(b []byte, fd protoreflect.FieldDescriptor, list protoreflect.List) ([]byte, error) { if fd.IsPacked() && list.Len() > 0 { b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) b, pos := appendSpeculativeLength(b) for i, llen := 0, list.Len(); i < llen; i++ { var err error b, err = o.marshalSingular(b, fd, list.Get(i)) if err != nil { return b, err } } b = finishSpeculativeLength(b, pos) return b, nil } kind := fd.Kind() for i, llen := 0, list.Len(); i < llen; i++ { var err error b = protowire.AppendTag(b, fd.Number(), wireTypes[kind]) b, err = o.marshalSingular(b, fd, list.Get(i)) if err != nil { return b, err } } return b, nil } func (o MarshalOptions) marshalMap(b []byte, fd protoreflect.FieldDescriptor, mapv protoreflect.Map) ([]byte, error) { keyf := fd.MapKey() valf := fd.MapValue() keyOrder := order.AnyKeyOrder if o.Deterministic { keyOrder = order.GenericKeyOrder } var err error order.RangeEntries(mapv, keyOrder, func(key protoreflect.MapKey, value protoreflect.Value) bool { b = protowire.AppendTag(b, fd.Number(), protowire.BytesType) var pos int b, pos = appendSpeculativeLength(b) b, err = o.marshalField(b, keyf, key.Value()) if err != nil { return false } b, err = o.marshalField(b, valf, value) if err != nil { return false } b = finishSpeculativeLength(b, pos) return true }) return b, err } // When encoding length-prefixed fields, we speculatively set aside some number of bytes // for the length, encode the data, and then encode the length (shifting the data if necessary // to make room). const speculativeLength = 1 func appendSpeculativeLength(b []byte) ([]byte, int) { pos := len(b) b = append(b, "\x00\x00\x00\x00"[:speculativeLength]...) return b, pos } func finishSpeculativeLength(b []byte, pos int) []byte { mlen := len(b) - pos - speculativeLength msiz := protowire.SizeVarint(uint64(mlen)) if msiz != speculativeLength { for i := 0; i < msiz-speculativeLength; i++ { b = append(b, 0) } copy(b[pos+msiz:], b[pos+speculativeLength:]) b = b[:pos+msiz+mlen] } protowire.AppendVarint(b[:pos], uint64(mlen)) return b }
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/proto/wrapperopaque.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/wrapperopaque.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 proto // ValueOrNil returns nil if has is false, or a pointer to a new variable // containing the value returned by the specified getter. // // This function is similar to the wrappers (proto.Int32(), proto.String(), // etc.), but is generic (works for any field type) and works with the hasser // and getter of a field, as opposed to a value. // // This is convenient when populating builder fields. // // Example: // // hop := attr.GetDirectHop() // injectedRoute := ripb.InjectedRoute_builder{ // Prefixes: route.GetPrefixes(), // NextHop: proto.ValueOrNil(hop.HasAddress(), hop.GetAddress), // } func ValueOrNil[T any](has bool, getter func() T) *T { if !has { return nil } v := getter() return &v } // ValueOrDefault returns the protobuf message val if val is not nil, otherwise // it returns a pointer to an empty val message. // // This function allows for translating code from the old Open Struct API to the // new Opaque API. // // The old Open Struct API represented oneof fields with a wrapper struct: // // var signedImg *accountpb.SignedImage // profile := &accountpb.Profile{ // // The Avatar oneof will be set, with an empty SignedImage. // Avatar: &accountpb.Profile_SignedImage{signedImg}, // } // // The new Opaque API treats oneof fields like regular fields, there are no more // wrapper structs: // // var signedImg *accountpb.SignedImage // profile := &accountpb.Profile{} // profile.SetSignedImage(signedImg) // // For convenience, the Opaque API also offers Builders, which allow for a // direct translation of struct initialization. However, because Builders use // nilness to represent field presence (but there is no non-nil wrapper struct // anymore), Builders cannot distinguish between an unset oneof and a set oneof // with nil message. The above code would need to be translated with help of the // ValueOrDefault function to retain the same behavior: // // var signedImg *accountpb.SignedImage // return &accountpb.Profile_builder{ // SignedImage: proto.ValueOrDefault(signedImg), // }.Build() func ValueOrDefault[T interface { *P Message }, P any](val T) T { if val == nil { return T(new(P)) } return val } // ValueOrDefaultBytes is like ValueOrDefault but for working with fields of // type []byte. func ValueOrDefaultBytes(val []byte) []byte { if val == nil { return []byte{} } return 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/proto/extension.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto import ( "google.golang.org/protobuf/reflect/protoreflect" ) // HasExtension reports whether an extension field is populated. // It returns false if m is invalid or if xt does not extend m. func HasExtension(m Message, xt protoreflect.ExtensionType) bool { // Treat nil message interface or descriptor as an empty message; no populated // fields. if m == nil || xt == nil { return false } // As a special-case, we reports invalid or mismatching descriptors // as always not being populated (since they aren't). mr := m.ProtoReflect() xd := xt.TypeDescriptor() if mr.Descriptor() != xd.ContainingMessage() { return false } return mr.Has(xd) } // ClearExtension clears an extension field such that subsequent // [HasExtension] calls return false. // It panics if m is invalid or if xt does not extend m. func ClearExtension(m Message, xt protoreflect.ExtensionType) { m.ProtoReflect().Clear(xt.TypeDescriptor()) } // GetExtension retrieves the value for an extension field. // If the field is unpopulated, it returns the default value for // scalars and an immutable, empty value for lists or messages. // It panics if xt does not extend m. // // The type of the value is dependent on the field type of the extension. // For extensions generated by protoc-gen-go, the Go type is as follows: // // ╔═══════════════════╤═════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠═══════════════════╪═════════════════════════╣ // ║ bool │ bool ║ // ║ int32 │ int32, sint32, sfixed32 ║ // ║ int64 │ int64, sint64, sfixed64 ║ // ║ uint32 │ uint32, fixed32 ║ // ║ uint64 │ uint64, fixed64 ║ // ║ float32 │ float ║ // ║ float64 │ double ║ // ║ string │ string ║ // ║ []byte │ bytes ║ // ║ protoreflect.Enum │ enum ║ // ║ proto.Message │ message, group ║ // ╚═══════════════════╧═════════════════════════╝ // // The protoreflect.Enum and proto.Message types are the concrete Go type // associated with the named enum or message. Repeated fields are represented // using a Go slice of the base element type. // // If a generated extension descriptor variable is directly passed to // GetExtension, then the call should be followed immediately by a // type assertion to the expected output value. For example: // // mm := proto.GetExtension(m, foopb.E_MyExtension).(*foopb.MyMessage) // // This pattern enables static analysis tools to verify that the asserted type // matches the Go type associated with the extension field and // also enables a possible future migration to a type-safe extension API. // // Since singular messages are the most common extension type, the pattern of // calling HasExtension followed by GetExtension may be simplified to: // // if mm := proto.GetExtension(m, foopb.E_MyExtension).(*foopb.MyMessage); mm != nil { // ... // make use of mm // } // // The mm variable is non-nil if and only if HasExtension reports true. func GetExtension(m Message, xt protoreflect.ExtensionType) any { // Treat nil message interface as an empty message; return the default. if m == nil { return xt.InterfaceOf(xt.Zero()) } return xt.InterfaceOf(m.ProtoReflect().Get(xt.TypeDescriptor())) } // SetExtension stores the value of an extension field. // It panics if m is invalid, xt does not extend m, or if type of v // is invalid for the specified extension field. // // The type of the value is dependent on the field type of the extension. // For extensions generated by protoc-gen-go, the Go type is as follows: // // ╔═══════════════════╤═════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠═══════════════════╪═════════════════════════╣ // ║ bool │ bool ║ // ║ int32 │ int32, sint32, sfixed32 ║ // ║ int64 │ int64, sint64, sfixed64 ║ // ║ uint32 │ uint32, fixed32 ║ // ║ uint64 │ uint64, fixed64 ║ // ║ float32 │ float ║ // ║ float64 │ double ║ // ║ string │ string ║ // ║ []byte │ bytes ║ // ║ protoreflect.Enum │ enum ║ // ║ proto.Message │ message, group ║ // ╚═══════════════════╧═════════════════════════╝ // // The protoreflect.Enum and proto.Message types are the concrete Go type // associated with the named enum or message. Repeated fields are represented // using a Go slice of the base element type. // // If a generated extension descriptor variable is directly passed to // SetExtension (e.g., foopb.E_MyExtension), then the value should be a // concrete type that matches the expected Go type for the extension descriptor // so that static analysis tools can verify type correctness. // This also enables a possible future migration to a type-safe extension API. func SetExtension(m Message, xt protoreflect.ExtensionType, v any) { xd := xt.TypeDescriptor() pv := xt.ValueOf(v) // Specially treat an invalid list, map, or message as clear. isValid := true switch { case xd.IsList(): isValid = pv.List().IsValid() case xd.IsMap(): isValid = pv.Map().IsValid() case xd.Message() != nil: isValid = pv.Message().IsValid() } if !isValid { m.ProtoReflect().Clear(xd) return } m.ProtoReflect().Set(xd, pv) } // RangeExtensions iterates over every populated extension field in m in an // undefined order, calling f for each extension type and value encountered. // It returns immediately if f returns false. // While iterating, mutating operations may only be performed // on the current extension field. func RangeExtensions(m Message, f func(protoreflect.ExtensionType, any) bool) { // Treat nil message interface as an empty message; nothing to range over. if m == nil { return } m.ProtoReflect().Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { if fd.IsExtension() { xt := fd.(protoreflect.ExtensionTypeDescriptor).Type() vi := xt.InterfaceOf(v) return f(xt, vi) } 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/proto/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto provides functions operating on protocol buffer messages. // // For documentation on protocol buffers in general, see: // https://protobuf.dev. // // For a tutorial on using protocol buffers with Go, see: // https://protobuf.dev/getting-started/gotutorial. // // For a guide to generated Go protocol buffer code, see: // https://protobuf.dev/reference/go/go-generated. // // # Binary serialization // // This package contains functions to convert to and from the wire format, // an efficient binary serialization of protocol buffers. // // - [Size] reports the size of a message in the wire format. // // - [Marshal] converts a message to the wire format. // The [MarshalOptions] type provides more control over wire marshaling. // // - [Unmarshal] converts a message from the wire format. // The [UnmarshalOptions] type provides more control over wire unmarshaling. // // # Basic message operations // // - [Clone] makes a deep copy of a message. // // - [Merge] merges the content of a message into another. // // - [Equal] compares two messages. For more control over comparisons // and detailed reporting of differences, see package // [google.golang.org/protobuf/testing/protocmp]. // // - [Reset] clears the content of a message. // // - [CheckInitialized] reports whether all required fields in a message are set. // // # Optional scalar constructors // // The API for some generated messages represents optional scalar fields // as pointers to a value. For example, an optional string field has the // Go type *string. // // - [Bool], [Int32], [Int64], [Uint32], [Uint64], [Float32], [Float64], and [String] // take a value and return a pointer to a new instance of it, // to simplify construction of optional field values. // // Generated enum types usually have an Enum method which performs the // same operation. // // Optional scalar fields are only supported in proto2. // // # Extension accessors // // - [HasExtension], [GetExtension], [SetExtension], and [ClearExtension] // access extension field values in a protocol buffer message. // // Extension fields are only supported in proto2. // // # Related packages // // - Package [google.golang.org/protobuf/encoding/protojson] converts messages to // and from JSON. // // - Package [google.golang.org/protobuf/encoding/prototext] converts messages to // and from the text format. // // - Package [google.golang.org/protobuf/reflect/protoreflect] provides a // reflection interface for protocol buffer data types. // // - Package [google.golang.org/protobuf/testing/protocmp] provides features // to compare protocol buffer messages with the [github.com/google/go-cmp/cmp] // package. // // - Package [google.golang.org/protobuf/types/dynamicpb] provides a dynamic // message type, suitable for working with messages where the protocol buffer // type is only known at runtime. // // This module contains additional packages for more specialized use cases. // Consult the individual package documentation for details. package proto
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/proto/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/decode.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 proto import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/runtime/protoiface" ) // UnmarshalOptions configures the unmarshaler. // // Example usage: // // err := UnmarshalOptions{DiscardUnknown: true}.Unmarshal(b, m) type UnmarshalOptions struct { pragma.NoUnkeyedLiterals // Merge merges the input into the destination message. // The default behavior is to always reset the message before unmarshaling, // unless Merge is specified. Merge bool // AllowPartial accepts input for messages that will result in missing // required fields. If AllowPartial is false (the default), Unmarshal will // return an error if there are any missing required fields. AllowPartial bool // If DiscardUnknown is set, unknown fields are ignored. DiscardUnknown bool // Resolver is used for looking up types when unmarshaling extension fields. // If nil, this defaults to using protoregistry.GlobalTypes. Resolver interface { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } // RecursionLimit limits how deeply messages may be nested. // If zero, a default limit is applied. RecursionLimit int // // NoLazyDecoding turns off lazy decoding, which otherwise is enabled by // default. Lazy decoding only affects submessages (annotated with [lazy = // true] in the .proto file) within messages that use the Opaque API. NoLazyDecoding bool } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). // // See the [UnmarshalOptions] type if you need more control. func Unmarshal(b []byte, m Message) error { _, err := UnmarshalOptions{RecursionLimit: protowire.DefaultRecursionLimit}.unmarshal(b, m.ProtoReflect()) return err } // Unmarshal parses the wire-format message in b and places the result in m. // The provided message must be mutable (e.g., a non-nil pointer to a message). func (o UnmarshalOptions) Unmarshal(b []byte, m Message) error { if o.RecursionLimit == 0 { o.RecursionLimit = protowire.DefaultRecursionLimit } _, err := o.unmarshal(b, m.ProtoReflect()) return err } // UnmarshalState parses a wire-format message and places the result in m. // // This method permits fine-grained control over the unmarshaler. // Most users should use [Unmarshal] instead. func (o UnmarshalOptions) UnmarshalState(in protoiface.UnmarshalInput) (protoiface.UnmarshalOutput, error) { if o.RecursionLimit == 0 { o.RecursionLimit = protowire.DefaultRecursionLimit } return o.unmarshal(in.Buf, in.Message) } // unmarshal is a centralized function that all unmarshal operations go through. // For profiling purposes, avoid changing the name of this function or // introducing other code paths for unmarshal that do not go through this. func (o UnmarshalOptions) unmarshal(b []byte, m protoreflect.Message) (out protoiface.UnmarshalOutput, err error) { if o.Resolver == nil { o.Resolver = protoregistry.GlobalTypes } if !o.Merge { Reset(m.Interface()) } allowPartial := o.AllowPartial o.Merge = true o.AllowPartial = true methods := protoMethods(m) if methods != nil && methods.Unmarshal != nil && !(o.DiscardUnknown && methods.Flags&protoiface.SupportUnmarshalDiscardUnknown == 0) { in := protoiface.UnmarshalInput{ Message: m, Buf: b, Resolver: o.Resolver, Depth: o.RecursionLimit, } if o.DiscardUnknown { in.Flags |= protoiface.UnmarshalDiscardUnknown } if !allowPartial { // This does not affect how current unmarshal functions work, it just allows them // to record this for lazy the decoding case. in.Flags |= protoiface.UnmarshalCheckRequired } if o.NoLazyDecoding { in.Flags |= protoiface.UnmarshalNoLazyDecoding } out, err = methods.Unmarshal(in) } else { o.RecursionLimit-- if o.RecursionLimit < 0 { return out, errors.New("exceeded max recursion depth") } err = o.unmarshalMessageSlow(b, m) } if err != nil { return out, err } if allowPartial || (out.Flags&protoiface.UnmarshalInitialized != 0) { return out, nil } return out, checkInitialized(m) } func (o UnmarshalOptions) unmarshalMessage(b []byte, m protoreflect.Message) error { _, err := o.unmarshal(b, m) return err } func (o UnmarshalOptions) unmarshalMessageSlow(b []byte, m protoreflect.Message) error { md := m.Descriptor() if messageset.IsMessageSet(md) { return o.unmarshalMessageSet(b, m) } fields := md.Fields() for len(b) > 0 { // Parse the tag (field number and wire type). num, wtyp, tagLen := protowire.ConsumeTag(b) if tagLen < 0 { return errDecode } if num > protowire.MaxValidNumber { return errDecode } // Find the field descriptor for this field number. fd := fields.ByNumber(num) if fd == nil && md.ExtensionRanges().Has(num) { extType, err := o.Resolver.FindExtensionByNumber(md.FullName(), num) if err != nil && err != protoregistry.NotFound { return errors.New("%v: unable to resolve extension %v: %v", md.FullName(), num, err) } if extType != nil { fd = extType.TypeDescriptor() } } var err error if fd == nil { err = errUnknown } // Parse the field value. var valLen int switch { case err != nil: case fd.IsList(): valLen, err = o.unmarshalList(b[tagLen:], wtyp, m.Mutable(fd).List(), fd) case fd.IsMap(): valLen, err = o.unmarshalMap(b[tagLen:], wtyp, m.Mutable(fd).Map(), fd) default: valLen, err = o.unmarshalSingular(b[tagLen:], wtyp, m, fd) } if err != nil { if err != errUnknown { return err } valLen = protowire.ConsumeFieldValue(num, wtyp, b[tagLen:]) if valLen < 0 { return errDecode } if !o.DiscardUnknown { m.SetUnknown(append(m.GetUnknown(), b[:tagLen+valLen]...)) } } b = b[tagLen+valLen:] } return nil } func (o UnmarshalOptions) unmarshalSingular(b []byte, wtyp protowire.Type, m protoreflect.Message, fd protoreflect.FieldDescriptor) (n int, err error) { v, n, err := o.unmarshalScalar(b, wtyp, fd) if err != nil { return 0, err } switch fd.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: m2 := m.Mutable(fd).Message() if err := o.unmarshalMessage(v.Bytes(), m2); err != nil { return n, err } default: // Non-message scalars replace the previous value. m.Set(fd, v) } return n, nil } func (o UnmarshalOptions) unmarshalMap(b []byte, wtyp protowire.Type, mapv protoreflect.Map, fd protoreflect.FieldDescriptor) (n int, err error) { if wtyp != protowire.BytesType { return 0, errUnknown } b, n = protowire.ConsumeBytes(b) if n < 0 { return 0, errDecode } var ( keyField = fd.MapKey() valField = fd.MapValue() key protoreflect.Value val protoreflect.Value haveKey bool haveVal bool ) switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: val = mapv.NewValue() } // Map entries are represented as a two-element message with fields // containing the key and value. for len(b) > 0 { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return 0, errDecode } if num > protowire.MaxValidNumber { return 0, errDecode } b = b[n:] err = errUnknown switch num { case genid.MapEntry_Key_field_number: key, n, err = o.unmarshalScalar(b, wtyp, keyField) if err != nil { break } haveKey = true case genid.MapEntry_Value_field_number: var v protoreflect.Value v, n, err = o.unmarshalScalar(b, wtyp, valField) if err != nil { break } switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: if err := o.unmarshalMessage(v.Bytes(), val.Message()); err != nil { return 0, err } default: val = v } haveVal = true } if err == errUnknown { n = protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return 0, errDecode } } else if err != nil { return 0, err } b = b[n:] } // Every map entry should have entries for key and value, but this is not strictly required. if !haveKey { key = keyField.Default() } if !haveVal { switch valField.Kind() { case protoreflect.GroupKind, protoreflect.MessageKind: default: val = valField.Default() } } mapv.Set(key.MapKey(), val) return n, nil } // errUnknown is used internally to indicate fields which should be added // to the unknown field set of a message. It is never returned from an exported // function. var errUnknown = errors.New("BUG: internal error (unknown)") var errDecode = errors.New("cannot parse invalid wire-format data")
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/proto/wrappers.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/proto/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 proto // Bool stores v in a new bool value and returns a pointer to it. func Bool(v bool) *bool { return &v } // Int32 stores v in a new int32 value and returns a pointer to it. func Int32(v int32) *int32 { return &v } // Int64 stores v in a new int64 value and returns a pointer to it. func Int64(v int64) *int64 { return &v } // Float32 stores v in a new float32 value and returns a pointer to it. func Float32(v float32) *float32 { return &v } // Float64 stores v in a new float64 value and returns a pointer to it. func Float64(v float64) *float64 { return &v } // Uint32 stores v in a new uint32 value and returns a pointer to it. func Uint32(v uint32) *uint32 { return &v } // Uint64 stores v in a new uint64 value and returns a pointer to it. func Uint64(v uint64) *uint64 { return &v } // String stores v in a new string value and returns a pointer to it. func String(v string) *string { 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/runtime/protoimpl/impl.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/runtime/protoimpl/impl.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 protoimpl contains the default implementation for messages // generated by protoc-gen-go. // // WARNING: This package should only ever be imported by generated messages. // The compatibility agreement covers nothing except for functionality needed // to keep existing generated messages operational. Breakages that occur due // to unauthorized usages of this package are not the author's responsibility. package protoimpl import ( "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/filetype" "google.golang.org/protobuf/internal/impl" "google.golang.org/protobuf/internal/protolazy" ) // UnsafeEnabled specifies whether package unsafe can be used. const UnsafeEnabled = impl.UnsafeEnabled type ( // Types used by generated code in init functions. DescBuilder = filedesc.Builder TypeBuilder = filetype.Builder // Types used by generated code to implement EnumType, MessageType, and ExtensionType. EnumInfo = impl.EnumInfo MessageInfo = impl.MessageInfo ExtensionInfo = impl.ExtensionInfo // Types embedded in generated messages. MessageState = impl.MessageState SizeCache = impl.SizeCache WeakFields = impl.WeakFields UnknownFields = impl.UnknownFields ExtensionFields = impl.ExtensionFields ExtensionFieldV1 = impl.ExtensionField Pointer = impl.Pointer LazyUnmarshalInfo = *protolazy.XXX_lazyUnmarshalInfo RaceDetectHookData = impl.RaceDetectHookData ) var X impl.Export
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/runtime/protoimpl/version.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/runtime/protoimpl/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 protoimpl import ( "google.golang.org/protobuf/internal/version" ) const ( // MaxVersion is the maximum supported version for generated .pb.go files. // It is always the current version of the module. MaxVersion = version.Minor // GenVersion is the runtime version required by generated .pb.go files. // This is incremented when generated code relies on new functionality // in the runtime. GenVersion = 20 // MinVersion is the minimum supported version for generated .pb.go files. // This is incremented when the runtime drops support for old code. MinVersion = 0 ) // EnforceVersion is used by code generated by protoc-gen-go // to statically enforce minimum and maximum versions of this package. // A compilation failure implies either that: // - the runtime package is too old and needs to be updated OR // - the generated code is too old and needs to be regenerated. // // The runtime package can be upgraded by running: // // go get google.golang.org/protobuf // // The generated code can be regenerated by running: // // protoc --go_out=${PROTOC_GEN_GO_ARGS} ${PROTO_FILES} // // Example usage by generated code: // // const ( // // Verify that this generated code is sufficiently up-to-date. // _ = protoimpl.EnforceVersion(genVersion - protoimpl.MinVersion) // // Verify that runtime/protoimpl is sufficiently up-to-date. // _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - genVersion) // ) // // The genVersion is the current minor version used to generated the code. // This compile-time check relies on negative integer overflow of a uint // being a compilation failure (guaranteed by the Go specification). type EnforceVersion uint // This enforces the following invariant: // // MinVersion ≤ GenVersion ≤ MaxVersion const ( _ = EnforceVersion(GenVersion - MinVersion) _ = EnforceVersion(MaxVersion - GenVersion) )
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/runtime/protoiface/methods.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/runtime/protoiface/methods.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 protoiface contains types referenced or implemented by messages. // // WARNING: This package should only be imported by message implementations. // The functionality found in this package should be accessed through // higher-level abstractions provided by the proto package. package protoiface import ( "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) // Methods is a set of optional fast-path implementations of various operations. type Methods = struct { pragma.NoUnkeyedLiterals // Flags indicate support for optional features. Flags SupportFlags // Size returns the size in bytes of the wire-format encoding of a message. // Marshal must be provided if a custom Size is provided. Size func(SizeInput) SizeOutput // Marshal formats a message in the wire-format encoding to the provided buffer. // Size should be provided if a custom Marshal is provided. // It must not return an error for a partial message. Marshal func(MarshalInput) (MarshalOutput, error) // Unmarshal parses the wire-format encoding and merges the result into a message. // It must not reset the target message or return an error for a partial message. Unmarshal func(UnmarshalInput) (UnmarshalOutput, error) // Merge merges the contents of a source message into a destination message. Merge func(MergeInput) MergeOutput // CheckInitialized returns an error if any required fields in the message are not set. CheckInitialized func(CheckInitializedInput) (CheckInitializedOutput, error) // Equal compares two messages and returns EqualOutput.Equal == true if they are equal. Equal func(EqualInput) EqualOutput } // SupportFlags indicate support for optional features. type SupportFlags = uint64 const ( // SupportMarshalDeterministic reports whether MarshalOptions.Deterministic is supported. SupportMarshalDeterministic SupportFlags = 1 << iota // SupportUnmarshalDiscardUnknown reports whether UnmarshalOptions.DiscardUnknown is supported. SupportUnmarshalDiscardUnknown ) // SizeInput is input to the Size method. type SizeInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Flags MarshalInputFlags } // SizeOutput is output from the Size method. type SizeOutput = struct { pragma.NoUnkeyedLiterals Size int } // MarshalInput is input to the Marshal method. type MarshalInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Buf []byte // output is appended to this buffer Flags MarshalInputFlags } // MarshalOutput is output from the Marshal method. type MarshalOutput = struct { pragma.NoUnkeyedLiterals Buf []byte // contains marshaled message } // MarshalInputFlags configure the marshaler. // Most flags correspond to fields in proto.MarshalOptions. type MarshalInputFlags = uint8 const ( MarshalDeterministic MarshalInputFlags = 1 << iota MarshalUseCachedSize ) // UnmarshalInput is input to the Unmarshal method. type UnmarshalInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message Buf []byte // input buffer Flags UnmarshalInputFlags Resolver interface { FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } Depth int } // UnmarshalOutput is output from the Unmarshal method. type UnmarshalOutput = struct { pragma.NoUnkeyedLiterals Flags UnmarshalOutputFlags } // UnmarshalInputFlags configure the unmarshaler. // Most flags correspond to fields in proto.UnmarshalOptions. type UnmarshalInputFlags = uint8 const ( UnmarshalDiscardUnknown UnmarshalInputFlags = 1 << iota // UnmarshalAliasBuffer permits unmarshal operations to alias the input buffer. // The unmarshaller must not modify the contents of the buffer. UnmarshalAliasBuffer // UnmarshalValidated indicates that validation has already been // performed on the input buffer. UnmarshalValidated // UnmarshalCheckRequired is set if this unmarshal operation ultimately will care if required fields are // initialized. UnmarshalCheckRequired // UnmarshalNoLazyDecoding is set if this unmarshal operation should not use // lazy decoding, even when otherwise available. UnmarshalNoLazyDecoding ) // UnmarshalOutputFlags are output from the Unmarshal method. type UnmarshalOutputFlags = uint8 const ( // UnmarshalInitialized may be set on return if all required fields are known to be set. // If unset, then it does not necessarily indicate that the message is uninitialized, // only that its status could not be confirmed. UnmarshalInitialized UnmarshalOutputFlags = 1 << iota ) // MergeInput is input to the Merge method. type MergeInput = struct { pragma.NoUnkeyedLiterals Source protoreflect.Message Destination protoreflect.Message } // MergeOutput is output from the Merge method. type MergeOutput = struct { pragma.NoUnkeyedLiterals Flags MergeOutputFlags } // MergeOutputFlags are output from the Merge method. type MergeOutputFlags = uint8 const ( // MergeComplete reports whether the merge was performed. // If unset, the merger must have made no changes to the destination. MergeComplete MergeOutputFlags = 1 << iota ) // CheckInitializedInput is input to the CheckInitialized method. type CheckInitializedInput = struct { pragma.NoUnkeyedLiterals Message protoreflect.Message } // CheckInitializedOutput is output from the CheckInitialized method. type CheckInitializedOutput = struct { pragma.NoUnkeyedLiterals } // EqualInput is input to the Equal method. type EqualInput = struct { pragma.NoUnkeyedLiterals MessageA protoreflect.Message MessageB protoreflect.Message } // EqualOutput is output from the Equal method. type EqualOutput = struct { pragma.NoUnkeyedLiterals Equal bool }
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/runtime/protoiface/legacy.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/runtime/protoiface/legacy.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 protoiface type MessageV1 interface { Reset() String() string ProtoMessage() } type ExtensionRangeV1 struct { Start, End int32 // both inclusive }
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/types/gofeaturespb/go_features.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/types/gofeaturespb/go_features.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2023 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/go_features.proto package gofeaturespb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" descriptorpb "google.golang.org/protobuf/types/descriptorpb" reflect "reflect" sync "sync" unsafe "unsafe" ) type GoFeatures_APILevel int32 const ( // API_LEVEL_UNSPECIFIED results in selecting the OPEN API, // but needs to be a separate value to distinguish between // an explicitly set api level or a missing api level. GoFeatures_API_LEVEL_UNSPECIFIED GoFeatures_APILevel = 0 GoFeatures_API_OPEN GoFeatures_APILevel = 1 GoFeatures_API_HYBRID GoFeatures_APILevel = 2 GoFeatures_API_OPAQUE GoFeatures_APILevel = 3 ) // Enum value maps for GoFeatures_APILevel. var ( GoFeatures_APILevel_name = map[int32]string{ 0: "API_LEVEL_UNSPECIFIED", 1: "API_OPEN", 2: "API_HYBRID", 3: "API_OPAQUE", } GoFeatures_APILevel_value = map[string]int32{ "API_LEVEL_UNSPECIFIED": 0, "API_OPEN": 1, "API_HYBRID": 2, "API_OPAQUE": 3, } ) func (x GoFeatures_APILevel) Enum() *GoFeatures_APILevel { p := new(GoFeatures_APILevel) *p = x return p } func (x GoFeatures_APILevel) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (GoFeatures_APILevel) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_go_features_proto_enumTypes[0].Descriptor() } func (GoFeatures_APILevel) Type() protoreflect.EnumType { return &file_google_protobuf_go_features_proto_enumTypes[0] } func (x GoFeatures_APILevel) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *GoFeatures_APILevel) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = GoFeatures_APILevel(num) return nil } // Deprecated: Use GoFeatures_APILevel.Descriptor instead. func (GoFeatures_APILevel) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0, 0} } type GoFeatures_StripEnumPrefix int32 const ( GoFeatures_STRIP_ENUM_PREFIX_UNSPECIFIED GoFeatures_StripEnumPrefix = 0 GoFeatures_STRIP_ENUM_PREFIX_KEEP GoFeatures_StripEnumPrefix = 1 GoFeatures_STRIP_ENUM_PREFIX_GENERATE_BOTH GoFeatures_StripEnumPrefix = 2 GoFeatures_STRIP_ENUM_PREFIX_STRIP GoFeatures_StripEnumPrefix = 3 ) // Enum value maps for GoFeatures_StripEnumPrefix. var ( GoFeatures_StripEnumPrefix_name = map[int32]string{ 0: "STRIP_ENUM_PREFIX_UNSPECIFIED", 1: "STRIP_ENUM_PREFIX_KEEP", 2: "STRIP_ENUM_PREFIX_GENERATE_BOTH", 3: "STRIP_ENUM_PREFIX_STRIP", } GoFeatures_StripEnumPrefix_value = map[string]int32{ "STRIP_ENUM_PREFIX_UNSPECIFIED": 0, "STRIP_ENUM_PREFIX_KEEP": 1, "STRIP_ENUM_PREFIX_GENERATE_BOTH": 2, "STRIP_ENUM_PREFIX_STRIP": 3, } ) func (x GoFeatures_StripEnumPrefix) Enum() *GoFeatures_StripEnumPrefix { p := new(GoFeatures_StripEnumPrefix) *p = x return p } func (x GoFeatures_StripEnumPrefix) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (GoFeatures_StripEnumPrefix) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_go_features_proto_enumTypes[1].Descriptor() } func (GoFeatures_StripEnumPrefix) Type() protoreflect.EnumType { return &file_google_protobuf_go_features_proto_enumTypes[1] } func (x GoFeatures_StripEnumPrefix) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *GoFeatures_StripEnumPrefix) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = GoFeatures_StripEnumPrefix(num) return nil } // Deprecated: Use GoFeatures_StripEnumPrefix.Descriptor instead. func (GoFeatures_StripEnumPrefix) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0, 1} } type GoFeatures struct { state protoimpl.MessageState `protogen:"open.v1"` // Whether or not to generate the deprecated UnmarshalJSON method for enums. // Can only be true for proto using the Open Struct api. LegacyUnmarshalJsonEnum *bool `protobuf:"varint,1,opt,name=legacy_unmarshal_json_enum,json=legacyUnmarshalJsonEnum" json:"legacy_unmarshal_json_enum,omitempty"` // One of OPEN, HYBRID or OPAQUE. ApiLevel *GoFeatures_APILevel `protobuf:"varint,2,opt,name=api_level,json=apiLevel,enum=pb.GoFeatures_APILevel" json:"api_level,omitempty"` StripEnumPrefix *GoFeatures_StripEnumPrefix `protobuf:"varint,3,opt,name=strip_enum_prefix,json=stripEnumPrefix,enum=pb.GoFeatures_StripEnumPrefix" json:"strip_enum_prefix,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *GoFeatures) Reset() { *x = GoFeatures{} mi := &file_google_protobuf_go_features_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *GoFeatures) String() string { return protoimpl.X.MessageStringOf(x) } func (*GoFeatures) ProtoMessage() {} func (x *GoFeatures) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_go_features_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use GoFeatures.ProtoReflect.Descriptor instead. func (*GoFeatures) Descriptor() ([]byte, []int) { return file_google_protobuf_go_features_proto_rawDescGZIP(), []int{0} } func (x *GoFeatures) GetLegacyUnmarshalJsonEnum() bool { if x != nil && x.LegacyUnmarshalJsonEnum != nil { return *x.LegacyUnmarshalJsonEnum } return false } func (x *GoFeatures) GetApiLevel() GoFeatures_APILevel { if x != nil && x.ApiLevel != nil { return *x.ApiLevel } return GoFeatures_API_LEVEL_UNSPECIFIED } func (x *GoFeatures) GetStripEnumPrefix() GoFeatures_StripEnumPrefix { if x != nil && x.StripEnumPrefix != nil { return *x.StripEnumPrefix } return GoFeatures_STRIP_ENUM_PREFIX_UNSPECIFIED } var file_google_protobuf_go_features_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptorpb.FeatureSet)(nil), ExtensionType: (*GoFeatures)(nil), Field: 1002, Name: "pb.go", Tag: "bytes,1002,opt,name=go", Filename: "google/protobuf/go_features.proto", }, } // Extension fields to descriptorpb.FeatureSet. var ( // optional pb.GoFeatures go = 1002; E_Go = &file_google_protobuf_go_features_proto_extTypes[0] ) var File_google_protobuf_go_features_proto protoreflect.FileDescriptor const file_google_protobuf_go_features_proto_rawDesc = "" + "\n" + "!google/protobuf/go_features.proto\x12\x02pb\x1a google/protobuf/descriptor.proto\"\xab\x05\n" + "\n" + "GoFeatures\x12\xbe\x01\n" + "\x1alegacy_unmarshal_json_enum\x18\x01 \x01(\bB\x80\x01\x88\x01\x01\x98\x01\x06\x98\x01\x01\xa2\x01\t\x12\x04true\x18\x84\a\xa2\x01\n" + "\x12\x05false\x18\xe7\a\xb2\x01[\b\xe8\a\x10\xe8\a\x1aSThe legacy UnmarshalJSON API is deprecated and will be removed in a future edition.R\x17legacyUnmarshalJsonEnum\x12t\n" + "\tapi_level\x18\x02 \x01(\x0e2\x17.pb.GoFeatures.APILevelB>\x88\x01\x01\x98\x01\x03\x98\x01\x01\xa2\x01\x1a\x12\x15API_LEVEL_UNSPECIFIED\x18\x84\a\xa2\x01\x0f\x12\n" + "API_OPAQUE\x18\xe9\a\xb2\x01\x03\b\xe8\aR\bapiLevel\x12|\n" + "\x11strip_enum_prefix\x18\x03 \x01(\x0e2\x1e.pb.GoFeatures.StripEnumPrefixB0\x88\x01\x01\x98\x01\x06\x98\x01\a\x98\x01\x01\xa2\x01\x1b\x12\x16STRIP_ENUM_PREFIX_KEEP\x18\x84\a\xb2\x01\x03\b\xe9\aR\x0fstripEnumPrefix\"S\n" + "\bAPILevel\x12\x19\n" + "\x15API_LEVEL_UNSPECIFIED\x10\x00\x12\f\n" + "\bAPI_OPEN\x10\x01\x12\x0e\n" + "\n" + "API_HYBRID\x10\x02\x12\x0e\n" + "\n" + "API_OPAQUE\x10\x03\"\x92\x01\n" + "\x0fStripEnumPrefix\x12!\n" + "\x1dSTRIP_ENUM_PREFIX_UNSPECIFIED\x10\x00\x12\x1a\n" + "\x16STRIP_ENUM_PREFIX_KEEP\x10\x01\x12#\n" + "\x1fSTRIP_ENUM_PREFIX_GENERATE_BOTH\x10\x02\x12\x1b\n" + "\x17STRIP_ENUM_PREFIX_STRIP\x10\x03:<\n" + "\x02go\x12\x1b.google.protobuf.FeatureSet\x18\xea\a \x01(\v2\x0e.pb.GoFeaturesR\x02goB/Z-google.golang.org/protobuf/types/gofeaturespb" var ( file_google_protobuf_go_features_proto_rawDescOnce sync.Once file_google_protobuf_go_features_proto_rawDescData []byte ) func file_google_protobuf_go_features_proto_rawDescGZIP() []byte { file_google_protobuf_go_features_proto_rawDescOnce.Do(func() { file_google_protobuf_go_features_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_go_features_proto_rawDesc), len(file_google_protobuf_go_features_proto_rawDesc))) }) return file_google_protobuf_go_features_proto_rawDescData } var file_google_protobuf_go_features_proto_enumTypes = make([]protoimpl.EnumInfo, 2) var file_google_protobuf_go_features_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_go_features_proto_goTypes = []any{ (GoFeatures_APILevel)(0), // 0: pb.GoFeatures.APILevel (GoFeatures_StripEnumPrefix)(0), // 1: pb.GoFeatures.StripEnumPrefix (*GoFeatures)(nil), // 2: pb.GoFeatures (*descriptorpb.FeatureSet)(nil), // 3: google.protobuf.FeatureSet } var file_google_protobuf_go_features_proto_depIdxs = []int32{ 0, // 0: pb.GoFeatures.api_level:type_name -> pb.GoFeatures.APILevel 1, // 1: pb.GoFeatures.strip_enum_prefix:type_name -> pb.GoFeatures.StripEnumPrefix 3, // 2: pb.go:extendee -> google.protobuf.FeatureSet 2, // 3: pb.go:type_name -> pb.GoFeatures 4, // [4:4] is the sub-list for method output_type 4, // [4:4] is the sub-list for method input_type 3, // [3:4] is the sub-list for extension type_name 2, // [2:3] is the sub-list for extension extendee 0, // [0:2] is the sub-list for field type_name } func init() { file_google_protobuf_go_features_proto_init() } func file_google_protobuf_go_features_proto_init() { if File_google_protobuf_go_features_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_go_features_proto_rawDesc), len(file_google_protobuf_go_features_proto_rawDesc)), NumEnums: 2, NumMessages: 1, NumExtensions: 1, NumServices: 0, }, GoTypes: file_google_protobuf_go_features_proto_goTypes, DependencyIndexes: file_google_protobuf_go_features_proto_depIdxs, EnumInfos: file_google_protobuf_go_features_proto_enumTypes, MessageInfos: file_google_protobuf_go_features_proto_msgTypes, ExtensionInfos: file_google_protobuf_go_features_proto_extTypes, }.Build() File_google_protobuf_go_features_proto = out.File file_google_protobuf_go_features_proto_goTypes = nil file_google_protobuf_go_features_proto_depIdxs = 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/types/descriptorpb/descriptor.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/types/descriptorpb/descriptor.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // The messages in this file describe the definitions found in .proto files. // A valid .proto file can be translated directly to a FileDescriptorProto // without any other information (e.g. without reading its imports). // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/descriptor.proto package descriptorpb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" unsafe "unsafe" ) // The full set of known editions. type Edition int32 const ( // A placeholder for an unknown edition value. Edition_EDITION_UNKNOWN Edition = 0 // A placeholder edition for specifying default behaviors *before* a feature // was first introduced. This is effectively an "infinite past". Edition_EDITION_LEGACY Edition = 900 // Legacy syntax "editions". These pre-date editions, but behave much like // distinct editions. These can't be used to specify the edition of proto // files, but feature definitions must supply proto2/proto3 defaults for // backwards compatibility. Edition_EDITION_PROTO2 Edition = 998 Edition_EDITION_PROTO3 Edition = 999 // Editions that have been released. The specific values are arbitrary and // should not be depended on, but they will always be time-ordered for easy // comparison. Edition_EDITION_2023 Edition = 1000 Edition_EDITION_2024 Edition = 1001 // Placeholder editions for testing feature resolution. These should not be // used or relied on outside of tests. Edition_EDITION_1_TEST_ONLY Edition = 1 Edition_EDITION_2_TEST_ONLY Edition = 2 Edition_EDITION_99997_TEST_ONLY Edition = 99997 Edition_EDITION_99998_TEST_ONLY Edition = 99998 Edition_EDITION_99999_TEST_ONLY Edition = 99999 // Placeholder for specifying unbounded edition support. This should only // ever be used by plugins that can expect to never require any changes to // support a new edition. Edition_EDITION_MAX Edition = 2147483647 ) // Enum value maps for Edition. var ( Edition_name = map[int32]string{ 0: "EDITION_UNKNOWN", 900: "EDITION_LEGACY", 998: "EDITION_PROTO2", 999: "EDITION_PROTO3", 1000: "EDITION_2023", 1001: "EDITION_2024", 1: "EDITION_1_TEST_ONLY", 2: "EDITION_2_TEST_ONLY", 99997: "EDITION_99997_TEST_ONLY", 99998: "EDITION_99998_TEST_ONLY", 99999: "EDITION_99999_TEST_ONLY", 2147483647: "EDITION_MAX", } Edition_value = map[string]int32{ "EDITION_UNKNOWN": 0, "EDITION_LEGACY": 900, "EDITION_PROTO2": 998, "EDITION_PROTO3": 999, "EDITION_2023": 1000, "EDITION_2024": 1001, "EDITION_1_TEST_ONLY": 1, "EDITION_2_TEST_ONLY": 2, "EDITION_99997_TEST_ONLY": 99997, "EDITION_99998_TEST_ONLY": 99998, "EDITION_99999_TEST_ONLY": 99999, "EDITION_MAX": 2147483647, } ) func (x Edition) Enum() *Edition { p := new(Edition) *p = x return p } func (x Edition) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (Edition) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[0].Descriptor() } func (Edition) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[0] } func (x Edition) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *Edition) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = Edition(num) return nil } // Deprecated: Use Edition.Descriptor instead. func (Edition) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{0} } // Describes the 'visibility' of a symbol with respect to the proto import // system. Symbols can only be imported when the visibility rules do not prevent // it (ex: local symbols cannot be imported). Visibility modifiers can only set // on `message` and `enum` as they are the only types available to be referenced // from other files. type SymbolVisibility int32 const ( SymbolVisibility_VISIBILITY_UNSET SymbolVisibility = 0 SymbolVisibility_VISIBILITY_LOCAL SymbolVisibility = 1 SymbolVisibility_VISIBILITY_EXPORT SymbolVisibility = 2 ) // Enum value maps for SymbolVisibility. var ( SymbolVisibility_name = map[int32]string{ 0: "VISIBILITY_UNSET", 1: "VISIBILITY_LOCAL", 2: "VISIBILITY_EXPORT", } SymbolVisibility_value = map[string]int32{ "VISIBILITY_UNSET": 0, "VISIBILITY_LOCAL": 1, "VISIBILITY_EXPORT": 2, } ) func (x SymbolVisibility) Enum() *SymbolVisibility { p := new(SymbolVisibility) *p = x return p } func (x SymbolVisibility) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (SymbolVisibility) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[1].Descriptor() } func (SymbolVisibility) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[1] } func (x SymbolVisibility) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *SymbolVisibility) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = SymbolVisibility(num) return nil } // Deprecated: Use SymbolVisibility.Descriptor instead. func (SymbolVisibility) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{1} } // The verification state of the extension range. type ExtensionRangeOptions_VerificationState int32 const ( // All the extensions of the range must be declared. ExtensionRangeOptions_DECLARATION ExtensionRangeOptions_VerificationState = 0 ExtensionRangeOptions_UNVERIFIED ExtensionRangeOptions_VerificationState = 1 ) // Enum value maps for ExtensionRangeOptions_VerificationState. var ( ExtensionRangeOptions_VerificationState_name = map[int32]string{ 0: "DECLARATION", 1: "UNVERIFIED", } ExtensionRangeOptions_VerificationState_value = map[string]int32{ "DECLARATION": 0, "UNVERIFIED": 1, } ) func (x ExtensionRangeOptions_VerificationState) Enum() *ExtensionRangeOptions_VerificationState { p := new(ExtensionRangeOptions_VerificationState) *p = x return p } func (x ExtensionRangeOptions_VerificationState) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (ExtensionRangeOptions_VerificationState) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[2].Descriptor() } func (ExtensionRangeOptions_VerificationState) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[2] } func (x ExtensionRangeOptions_VerificationState) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *ExtensionRangeOptions_VerificationState) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = ExtensionRangeOptions_VerificationState(num) return nil } // Deprecated: Use ExtensionRangeOptions_VerificationState.Descriptor instead. func (ExtensionRangeOptions_VerificationState) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{3, 0} } type FieldDescriptorProto_Type int32 const ( // 0 is reserved for errors. // Order is weird for historical reasons. FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1 FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if // negative values are likely. FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3 FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4 // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if // negative values are likely. FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5 FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6 FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7 FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8 FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9 // Tag-delimited aggregate. // Group type is deprecated and not supported after google.protobuf. However, Proto3 // implementations should still be able to parse the group wire format and // treat group fields as unknown fields. In Editions, the group wire format // can be enabled via the `message_encoding` feature. FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10 FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11 // Length-delimited aggregate. // New in version 2. FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12 FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13 FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14 FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15 FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16 FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17 // Uses ZigZag encoding. FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18 // Uses ZigZag encoding. ) // Enum value maps for FieldDescriptorProto_Type. var ( FieldDescriptorProto_Type_name = map[int32]string{ 1: "TYPE_DOUBLE", 2: "TYPE_FLOAT", 3: "TYPE_INT64", 4: "TYPE_UINT64", 5: "TYPE_INT32", 6: "TYPE_FIXED64", 7: "TYPE_FIXED32", 8: "TYPE_BOOL", 9: "TYPE_STRING", 10: "TYPE_GROUP", 11: "TYPE_MESSAGE", 12: "TYPE_BYTES", 13: "TYPE_UINT32", 14: "TYPE_ENUM", 15: "TYPE_SFIXED32", 16: "TYPE_SFIXED64", 17: "TYPE_SINT32", 18: "TYPE_SINT64", } FieldDescriptorProto_Type_value = map[string]int32{ "TYPE_DOUBLE": 1, "TYPE_FLOAT": 2, "TYPE_INT64": 3, "TYPE_UINT64": 4, "TYPE_INT32": 5, "TYPE_FIXED64": 6, "TYPE_FIXED32": 7, "TYPE_BOOL": 8, "TYPE_STRING": 9, "TYPE_GROUP": 10, "TYPE_MESSAGE": 11, "TYPE_BYTES": 12, "TYPE_UINT32": 13, "TYPE_ENUM": 14, "TYPE_SFIXED32": 15, "TYPE_SFIXED64": 16, "TYPE_SINT32": 17, "TYPE_SINT64": 18, } ) func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type { p := new(FieldDescriptorProto_Type) *p = x return p } func (x FieldDescriptorProto_Type) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldDescriptorProto_Type) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[3].Descriptor() } func (FieldDescriptorProto_Type) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[3] } func (x FieldDescriptorProto_Type) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldDescriptorProto_Type) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldDescriptorProto_Type(num) return nil } // Deprecated: Use FieldDescriptorProto_Type.Descriptor instead. func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 0} } type FieldDescriptorProto_Label int32 const ( // 0 is reserved for errors FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1 FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3 // The required label is only allowed in google.protobuf. In proto3 and Editions // it's explicitly prohibited. In Editions, the `field_presence` feature // can be used to get this behavior. FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2 ) // Enum value maps for FieldDescriptorProto_Label. var ( FieldDescriptorProto_Label_name = map[int32]string{ 1: "LABEL_OPTIONAL", 3: "LABEL_REPEATED", 2: "LABEL_REQUIRED", } FieldDescriptorProto_Label_value = map[string]int32{ "LABEL_OPTIONAL": 1, "LABEL_REPEATED": 3, "LABEL_REQUIRED": 2, } ) func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label { p := new(FieldDescriptorProto_Label) *p = x return p } func (x FieldDescriptorProto_Label) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldDescriptorProto_Label) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[4].Descriptor() } func (FieldDescriptorProto_Label) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[4] } func (x FieldDescriptorProto_Label) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldDescriptorProto_Label) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldDescriptorProto_Label(num) return nil } // Deprecated: Use FieldDescriptorProto_Label.Descriptor instead. func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{4, 1} } // Generated classes can be optimized for speed or code size. type FileOptions_OptimizeMode int32 const ( FileOptions_SPEED FileOptions_OptimizeMode = 1 // Generate complete code for parsing, serialization, // etc. FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2 // Use ReflectionOps to implement these methods. FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3 // Generate code using MessageLite and the lite runtime. ) // Enum value maps for FileOptions_OptimizeMode. var ( FileOptions_OptimizeMode_name = map[int32]string{ 1: "SPEED", 2: "CODE_SIZE", 3: "LITE_RUNTIME", } FileOptions_OptimizeMode_value = map[string]int32{ "SPEED": 1, "CODE_SIZE": 2, "LITE_RUNTIME": 3, } ) func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode { p := new(FileOptions_OptimizeMode) *p = x return p } func (x FileOptions_OptimizeMode) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FileOptions_OptimizeMode) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[5].Descriptor() } func (FileOptions_OptimizeMode) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[5] } func (x FileOptions_OptimizeMode) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FileOptions_OptimizeMode) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FileOptions_OptimizeMode(num) return nil } // Deprecated: Use FileOptions_OptimizeMode.Descriptor instead. func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{10, 0} } type FieldOptions_CType int32 const ( // Default mode. FieldOptions_STRING FieldOptions_CType = 0 // The option [ctype=CORD] may be applied to a non-repeated field of type // "bytes". It indicates that in C++, the data should be stored in a Cord // instead of a string. For very large strings, this may reduce memory // fragmentation. It may also allow better performance when parsing from a // Cord, or when parsing with aliasing enabled, as the parsed Cord may then // alias the original buffer. FieldOptions_CORD FieldOptions_CType = 1 FieldOptions_STRING_PIECE FieldOptions_CType = 2 ) // Enum value maps for FieldOptions_CType. var ( FieldOptions_CType_name = map[int32]string{ 0: "STRING", 1: "CORD", 2: "STRING_PIECE", } FieldOptions_CType_value = map[string]int32{ "STRING": 0, "CORD": 1, "STRING_PIECE": 2, } ) func (x FieldOptions_CType) Enum() *FieldOptions_CType { p := new(FieldOptions_CType) *p = x return p } func (x FieldOptions_CType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_CType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[6].Descriptor() } func (FieldOptions_CType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[6] } func (x FieldOptions_CType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_CType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_CType(num) return nil } // Deprecated: Use FieldOptions_CType.Descriptor instead. func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 0} } type FieldOptions_JSType int32 const ( // Use the default type. FieldOptions_JS_NORMAL FieldOptions_JSType = 0 // Use JavaScript strings. FieldOptions_JS_STRING FieldOptions_JSType = 1 // Use JavaScript numbers. FieldOptions_JS_NUMBER FieldOptions_JSType = 2 ) // Enum value maps for FieldOptions_JSType. var ( FieldOptions_JSType_name = map[int32]string{ 0: "JS_NORMAL", 1: "JS_STRING", 2: "JS_NUMBER", } FieldOptions_JSType_value = map[string]int32{ "JS_NORMAL": 0, "JS_STRING": 1, "JS_NUMBER": 2, } ) func (x FieldOptions_JSType) Enum() *FieldOptions_JSType { p := new(FieldOptions_JSType) *p = x return p } func (x FieldOptions_JSType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_JSType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[7].Descriptor() } func (FieldOptions_JSType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[7] } func (x FieldOptions_JSType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_JSType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_JSType(num) return nil } // Deprecated: Use FieldOptions_JSType.Descriptor instead. func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 1} } // If set to RETENTION_SOURCE, the option will be omitted from the binary. type FieldOptions_OptionRetention int32 const ( FieldOptions_RETENTION_UNKNOWN FieldOptions_OptionRetention = 0 FieldOptions_RETENTION_RUNTIME FieldOptions_OptionRetention = 1 FieldOptions_RETENTION_SOURCE FieldOptions_OptionRetention = 2 ) // Enum value maps for FieldOptions_OptionRetention. var ( FieldOptions_OptionRetention_name = map[int32]string{ 0: "RETENTION_UNKNOWN", 1: "RETENTION_RUNTIME", 2: "RETENTION_SOURCE", } FieldOptions_OptionRetention_value = map[string]int32{ "RETENTION_UNKNOWN": 0, "RETENTION_RUNTIME": 1, "RETENTION_SOURCE": 2, } ) func (x FieldOptions_OptionRetention) Enum() *FieldOptions_OptionRetention { p := new(FieldOptions_OptionRetention) *p = x return p } func (x FieldOptions_OptionRetention) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_OptionRetention) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[8].Descriptor() } func (FieldOptions_OptionRetention) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[8] } func (x FieldOptions_OptionRetention) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_OptionRetention) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_OptionRetention(num) return nil } // Deprecated: Use FieldOptions_OptionRetention.Descriptor instead. func (FieldOptions_OptionRetention) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 2} } // This indicates the types of entities that the field may apply to when used // as an option. If it is unset, then the field may be freely used as an // option on any kind of entity. type FieldOptions_OptionTargetType int32 const ( FieldOptions_TARGET_TYPE_UNKNOWN FieldOptions_OptionTargetType = 0 FieldOptions_TARGET_TYPE_FILE FieldOptions_OptionTargetType = 1 FieldOptions_TARGET_TYPE_EXTENSION_RANGE FieldOptions_OptionTargetType = 2 FieldOptions_TARGET_TYPE_MESSAGE FieldOptions_OptionTargetType = 3 FieldOptions_TARGET_TYPE_FIELD FieldOptions_OptionTargetType = 4 FieldOptions_TARGET_TYPE_ONEOF FieldOptions_OptionTargetType = 5 FieldOptions_TARGET_TYPE_ENUM FieldOptions_OptionTargetType = 6 FieldOptions_TARGET_TYPE_ENUM_ENTRY FieldOptions_OptionTargetType = 7 FieldOptions_TARGET_TYPE_SERVICE FieldOptions_OptionTargetType = 8 FieldOptions_TARGET_TYPE_METHOD FieldOptions_OptionTargetType = 9 ) // Enum value maps for FieldOptions_OptionTargetType. var ( FieldOptions_OptionTargetType_name = map[int32]string{ 0: "TARGET_TYPE_UNKNOWN", 1: "TARGET_TYPE_FILE", 2: "TARGET_TYPE_EXTENSION_RANGE", 3: "TARGET_TYPE_MESSAGE", 4: "TARGET_TYPE_FIELD", 5: "TARGET_TYPE_ONEOF", 6: "TARGET_TYPE_ENUM", 7: "TARGET_TYPE_ENUM_ENTRY", 8: "TARGET_TYPE_SERVICE", 9: "TARGET_TYPE_METHOD", } FieldOptions_OptionTargetType_value = map[string]int32{ "TARGET_TYPE_UNKNOWN": 0, "TARGET_TYPE_FILE": 1, "TARGET_TYPE_EXTENSION_RANGE": 2, "TARGET_TYPE_MESSAGE": 3, "TARGET_TYPE_FIELD": 4, "TARGET_TYPE_ONEOF": 5, "TARGET_TYPE_ENUM": 6, "TARGET_TYPE_ENUM_ENTRY": 7, "TARGET_TYPE_SERVICE": 8, "TARGET_TYPE_METHOD": 9, } ) func (x FieldOptions_OptionTargetType) Enum() *FieldOptions_OptionTargetType { p := new(FieldOptions_OptionTargetType) *p = x return p } func (x FieldOptions_OptionTargetType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FieldOptions_OptionTargetType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[9].Descriptor() } func (FieldOptions_OptionTargetType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[9] } func (x FieldOptions_OptionTargetType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FieldOptions_OptionTargetType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FieldOptions_OptionTargetType(num) return nil } // Deprecated: Use FieldOptions_OptionTargetType.Descriptor instead. func (FieldOptions_OptionTargetType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{12, 3} } // Is this method side-effect-free (or safe in HTTP parlance), or idempotent, // or neither? HTTP based RPC implementation may choose GET verb for safe // methods, and PUT verb for idempotent methods instead of the default POST. type MethodOptions_IdempotencyLevel int32 const ( MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0 MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1 // implies idempotent MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2 // idempotent, but may have side effects ) // Enum value maps for MethodOptions_IdempotencyLevel. var ( MethodOptions_IdempotencyLevel_name = map[int32]string{ 0: "IDEMPOTENCY_UNKNOWN", 1: "NO_SIDE_EFFECTS", 2: "IDEMPOTENT", } MethodOptions_IdempotencyLevel_value = map[string]int32{ "IDEMPOTENCY_UNKNOWN": 0, "NO_SIDE_EFFECTS": 1, "IDEMPOTENT": 2, } ) func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel { p := new(MethodOptions_IdempotencyLevel) *p = x return p } func (x MethodOptions_IdempotencyLevel) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (MethodOptions_IdempotencyLevel) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[10].Descriptor() } func (MethodOptions_IdempotencyLevel) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[10] } func (x MethodOptions_IdempotencyLevel) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = MethodOptions_IdempotencyLevel(num) return nil } // Deprecated: Use MethodOptions_IdempotencyLevel.Descriptor instead. func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{17, 0} } type FeatureSet_FieldPresence int32 const ( FeatureSet_FIELD_PRESENCE_UNKNOWN FeatureSet_FieldPresence = 0 FeatureSet_EXPLICIT FeatureSet_FieldPresence = 1 FeatureSet_IMPLICIT FeatureSet_FieldPresence = 2 FeatureSet_LEGACY_REQUIRED FeatureSet_FieldPresence = 3 ) // Enum value maps for FeatureSet_FieldPresence. var ( FeatureSet_FieldPresence_name = map[int32]string{ 0: "FIELD_PRESENCE_UNKNOWN", 1: "EXPLICIT", 2: "IMPLICIT", 3: "LEGACY_REQUIRED", } FeatureSet_FieldPresence_value = map[string]int32{ "FIELD_PRESENCE_UNKNOWN": 0, "EXPLICIT": 1, "IMPLICIT": 2, "LEGACY_REQUIRED": 3, } ) func (x FeatureSet_FieldPresence) Enum() *FeatureSet_FieldPresence { p := new(FeatureSet_FieldPresence) *p = x return p } func (x FeatureSet_FieldPresence) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_FieldPresence) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[11].Descriptor() } func (FeatureSet_FieldPresence) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[11] } func (x FeatureSet_FieldPresence) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_FieldPresence) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_FieldPresence(num) return nil } // Deprecated: Use FeatureSet_FieldPresence.Descriptor instead. func (FeatureSet_FieldPresence) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 0} } type FeatureSet_EnumType int32 const ( FeatureSet_ENUM_TYPE_UNKNOWN FeatureSet_EnumType = 0 FeatureSet_OPEN FeatureSet_EnumType = 1 FeatureSet_CLOSED FeatureSet_EnumType = 2 ) // Enum value maps for FeatureSet_EnumType. var ( FeatureSet_EnumType_name = map[int32]string{ 0: "ENUM_TYPE_UNKNOWN", 1: "OPEN", 2: "CLOSED", } FeatureSet_EnumType_value = map[string]int32{ "ENUM_TYPE_UNKNOWN": 0, "OPEN": 1, "CLOSED": 2, } ) func (x FeatureSet_EnumType) Enum() *FeatureSet_EnumType { p := new(FeatureSet_EnumType) *p = x return p } func (x FeatureSet_EnumType) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_EnumType) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[12].Descriptor() } func (FeatureSet_EnumType) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[12] } func (x FeatureSet_EnumType) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_EnumType) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_EnumType(num) return nil } // Deprecated: Use FeatureSet_EnumType.Descriptor instead. func (FeatureSet_EnumType) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 1} } type FeatureSet_RepeatedFieldEncoding int32 const ( FeatureSet_REPEATED_FIELD_ENCODING_UNKNOWN FeatureSet_RepeatedFieldEncoding = 0 FeatureSet_PACKED FeatureSet_RepeatedFieldEncoding = 1 FeatureSet_EXPANDED FeatureSet_RepeatedFieldEncoding = 2 ) // Enum value maps for FeatureSet_RepeatedFieldEncoding. var ( FeatureSet_RepeatedFieldEncoding_name = map[int32]string{ 0: "REPEATED_FIELD_ENCODING_UNKNOWN", 1: "PACKED", 2: "EXPANDED", } FeatureSet_RepeatedFieldEncoding_value = map[string]int32{ "REPEATED_FIELD_ENCODING_UNKNOWN": 0, "PACKED": 1, "EXPANDED": 2, } ) func (x FeatureSet_RepeatedFieldEncoding) Enum() *FeatureSet_RepeatedFieldEncoding { p := new(FeatureSet_RepeatedFieldEncoding) *p = x return p } func (x FeatureSet_RepeatedFieldEncoding) String() string { return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x)) } func (FeatureSet_RepeatedFieldEncoding) Descriptor() protoreflect.EnumDescriptor { return file_google_protobuf_descriptor_proto_enumTypes[13].Descriptor() } func (FeatureSet_RepeatedFieldEncoding) Type() protoreflect.EnumType { return &file_google_protobuf_descriptor_proto_enumTypes[13] } func (x FeatureSet_RepeatedFieldEncoding) Number() protoreflect.EnumNumber { return protoreflect.EnumNumber(x) } // Deprecated: Do not use. func (x *FeatureSet_RepeatedFieldEncoding) UnmarshalJSON(b []byte) error { num, err := protoimpl.X.UnmarshalJSONEnum(x.Descriptor(), b) if err != nil { return err } *x = FeatureSet_RepeatedFieldEncoding(num) return nil } // Deprecated: Use FeatureSet_RepeatedFieldEncoding.Descriptor instead. func (FeatureSet_RepeatedFieldEncoding) EnumDescriptor() ([]byte, []int) { return file_google_protobuf_descriptor_proto_rawDescGZIP(), []int{19, 2} } type FeatureSet_Utf8Validation int32 const ( FeatureSet_UTF8_VALIDATION_UNKNOWN FeatureSet_Utf8Validation = 0 FeatureSet_VERIFY FeatureSet_Utf8Validation = 2 FeatureSet_NONE FeatureSet_Utf8Validation = 3 )
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/types/known/timestamppb/timestamp.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/types/known/timestamppb/timestamp.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/timestamp.proto // Package timestamppb contains generated types for google/protobuf/timestamp.proto. // // The Timestamp message represents a timestamp, // an instant in time since the Unix epoch (January 1st, 1970). // // # Conversion to a Go Time // // The AsTime method can be used to convert a Timestamp message to a // standard Go time.Time value in UTC: // // t := ts.AsTime() // ... // make use of t as a time.Time // // Converting to a time.Time is a common operation so that the extensive // set of time-based operations provided by the time package can be leveraged. // See https://golang.org/pkg/time for more information. // // The AsTime method performs the conversion on a best-effort basis. Timestamps // with denormal values (e.g., nanoseconds beyond 0 and 99999999, inclusive) // are normalized during the conversion to a time.Time. To manually check for // invalid Timestamps per the documented limitations in timestamp.proto, // additionally call the CheckValid method: // // if err := ts.CheckValid(); err != nil { // ... // handle error // } // // # Conversion from a Go Time // // The timestamppb.New function can be used to construct a Timestamp message // from a standard Go time.Time value: // // ts := timestamppb.New(t) // ... // make use of ts as a *timestamppb.Timestamp // // In order to construct a Timestamp representing the current time, use Now: // // ts := timestamppb.Now() // ... // make use of ts as a *timestamppb.Timestamp package timestamppb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" sync "sync" time "time" unsafe "unsafe" ) // A Timestamp represents a point in time independent of any time zone or local // calendar, encoded as a count of seconds and fractions of seconds at // nanosecond resolution. The count is relative to an epoch at UTC midnight on // January 1, 1970, in the proleptic Gregorian calendar which extends the // Gregorian calendar backwards to year one. // // All minutes are 60 seconds long. Leap seconds are "smeared" so that no leap // second table is needed for interpretation, using a [24-hour linear // smear](https://developers.google.com/time/smear). // // The range is from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59.999999999Z. By // restricting to that range, we ensure that we can convert to and from [RFC // 3339](https://www.ietf.org/rfc/rfc3339.txt) date strings. // // # Examples // // Example 1: Compute Timestamp from POSIX `time()`. // // Timestamp timestamp; // timestamp.set_seconds(time(NULL)); // timestamp.set_nanos(0); // // Example 2: Compute Timestamp from POSIX `gettimeofday()`. // // struct timeval tv; // gettimeofday(&tv, NULL); // // Timestamp timestamp; // timestamp.set_seconds(tv.tv_sec); // timestamp.set_nanos(tv.tv_usec * 1000); // // Example 3: Compute Timestamp from Win32 `GetSystemTimeAsFileTime()`. // // FILETIME ft; // GetSystemTimeAsFileTime(&ft); // UINT64 ticks = (((UINT64)ft.dwHighDateTime) << 32) | ft.dwLowDateTime; // // // A Windows tick is 100 nanoseconds. Windows epoch 1601-01-01T00:00:00Z // // is 11644473600 seconds before Unix epoch 1970-01-01T00:00:00Z. // Timestamp timestamp; // timestamp.set_seconds((INT64) ((ticks / 10000000) - 11644473600LL)); // timestamp.set_nanos((INT32) ((ticks % 10000000) * 100)); // // Example 4: Compute Timestamp from Java `System.currentTimeMillis()`. // // long millis = System.currentTimeMillis(); // // Timestamp timestamp = Timestamp.newBuilder().setSeconds(millis / 1000) // .setNanos((int) ((millis % 1000) * 1000000)).build(); // // Example 5: Compute Timestamp from Java `Instant.now()`. // // Instant now = Instant.now(); // // Timestamp timestamp = // Timestamp.newBuilder().setSeconds(now.getEpochSecond()) // .setNanos(now.getNano()).build(); // // Example 6: Compute Timestamp from current time in Python. // // timestamp = Timestamp() // timestamp.GetCurrentTime() // // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A proto3 JSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a proto3 JSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. // // In JavaScript, one can convert a Date object to this format using the // standard // [toISOString()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString) // method. In Python, a standard `datetime.datetime` object can be converted // to this format using // [`strftime`](https://docs.python.org/2/library/time.html#time.strftime) with // the time format spec '%Y-%m-%dT%H:%M:%S.%fZ'. Likewise, in Java, one can use // the Joda Time's [`ISODateTimeFormat.dateTime()`]( // http://joda-time.sourceforge.net/apidocs/org/joda/time/format/ISODateTimeFormat.html#dateTime() // ) to obtain a formatter capable of generating timestamps in this format. type Timestamp struct { state protoimpl.MessageState `protogen:"open.v1"` // Represents seconds of UTC time since Unix epoch // 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to // 9999-12-31T23:59:59Z inclusive. Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` // Non-negative fractions of a second at nanosecond resolution. Negative // second values with fractions must still have non-negative nanos values // that count forward in time. Must be from 0 to 999,999,999 // inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // Now constructs a new Timestamp from the current time. func Now() *Timestamp { return New(time.Now()) } // New constructs a new Timestamp from the provided time.Time. func New(t time.Time) *Timestamp { return &Timestamp{Seconds: int64(t.Unix()), Nanos: int32(t.Nanosecond())} } // AsTime converts x to a time.Time. func (x *Timestamp) AsTime() time.Time { return time.Unix(int64(x.GetSeconds()), int64(x.GetNanos())).UTC() } // IsValid reports whether the timestamp is valid. // It is equivalent to CheckValid == nil. func (x *Timestamp) IsValid() bool { return x.check() == 0 } // CheckValid returns an error if the timestamp is invalid. // In particular, it checks whether the value represents a date that is // in the range of 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive. // An error is reported for a nil Timestamp. func (x *Timestamp) CheckValid() error { switch x.check() { case invalidNil: return protoimpl.X.NewError("invalid nil Timestamp") case invalidUnderflow: return protoimpl.X.NewError("timestamp (%v) before 0001-01-01", x) case invalidOverflow: return protoimpl.X.NewError("timestamp (%v) after 9999-12-31", x) case invalidNanos: return protoimpl.X.NewError("timestamp (%v) has out-of-range nanos", x) default: return nil } } const ( _ = iota invalidNil invalidUnderflow invalidOverflow invalidNanos ) func (x *Timestamp) check() uint { const minTimestamp = -62135596800 // Seconds between 1970-01-01T00:00:00Z and 0001-01-01T00:00:00Z, inclusive const maxTimestamp = +253402300799 // Seconds between 1970-01-01T00:00:00Z and 9999-12-31T23:59:59Z, inclusive secs := x.GetSeconds() nanos := x.GetNanos() switch { case x == nil: return invalidNil case secs < minTimestamp: return invalidUnderflow case secs > maxTimestamp: return invalidOverflow case nanos < 0 || nanos >= 1e9: return invalidNanos default: return 0 } } func (x *Timestamp) Reset() { *x = Timestamp{} mi := &file_google_protobuf_timestamp_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Timestamp) String() string { return protoimpl.X.MessageStringOf(x) } func (*Timestamp) ProtoMessage() {} func (x *Timestamp) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_timestamp_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Timestamp.ProtoReflect.Descriptor instead. func (*Timestamp) Descriptor() ([]byte, []int) { return file_google_protobuf_timestamp_proto_rawDescGZIP(), []int{0} } func (x *Timestamp) GetSeconds() int64 { if x != nil { return x.Seconds } return 0 } func (x *Timestamp) GetNanos() int32 { if x != nil { return x.Nanos } return 0 } var File_google_protobuf_timestamp_proto protoreflect.FileDescriptor const file_google_protobuf_timestamp_proto_rawDesc = "" + "\n" + "\x1fgoogle/protobuf/timestamp.proto\x12\x0fgoogle.protobuf\";\n" + "\tTimestamp\x12\x18\n" + "\aseconds\x18\x01 \x01(\x03R\aseconds\x12\x14\n" + "\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x85\x01\n" + "\x13com.google.protobufB\x0eTimestampProtoP\x01Z2google.golang.org/protobuf/types/known/timestamppb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_timestamp_proto_rawDescOnce sync.Once file_google_protobuf_timestamp_proto_rawDescData []byte ) func file_google_protobuf_timestamp_proto_rawDescGZIP() []byte { file_google_protobuf_timestamp_proto_rawDescOnce.Do(func() { file_google_protobuf_timestamp_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_timestamp_proto_rawDesc), len(file_google_protobuf_timestamp_proto_rawDesc))) }) return file_google_protobuf_timestamp_proto_rawDescData } var file_google_protobuf_timestamp_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_timestamp_proto_goTypes = []any{ (*Timestamp)(nil), // 0: google.protobuf.Timestamp } var file_google_protobuf_timestamp_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_timestamp_proto_init() } func file_google_protobuf_timestamp_proto_init() { if File_google_protobuf_timestamp_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_timestamp_proto_rawDesc), len(file_google_protobuf_timestamp_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_timestamp_proto_goTypes, DependencyIndexes: file_google_protobuf_timestamp_proto_depIdxs, MessageInfos: file_google_protobuf_timestamp_proto_msgTypes, }.Build() File_google_protobuf_timestamp_proto = out.File file_google_protobuf_timestamp_proto_goTypes = nil file_google_protobuf_timestamp_proto_depIdxs = 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/types/known/durationpb/duration.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/types/known/durationpb/duration.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/duration.proto // Package durationpb contains generated types for google/protobuf/duration.proto. // // The Duration message represents a signed span of time. // // # Conversion to a Go Duration // // The AsDuration method can be used to convert a Duration message to a // standard Go time.Duration value: // // d := dur.AsDuration() // ... // make use of d as a time.Duration // // Converting to a time.Duration is a common operation so that the extensive // set of time-based operations provided by the time package can be leveraged. // See https://golang.org/pkg/time for more information. // // The AsDuration method performs the conversion on a best-effort basis. // Durations with denormal values (e.g., nanoseconds beyond -99999999 and // +99999999, inclusive; or seconds and nanoseconds with opposite signs) // are normalized during the conversion to a time.Duration. To manually check for // invalid Duration per the documented limitations in duration.proto, // additionally call the CheckValid method: // // if err := dur.CheckValid(); err != nil { // ... // handle error // } // // Note that the documented limitations in duration.proto does not protect a // Duration from overflowing the representable range of a time.Duration in Go. // The AsDuration method uses saturation arithmetic such that an overflow clamps // the resulting value to the closest representable value (e.g., math.MaxInt64 // for positive overflow and math.MinInt64 for negative overflow). // // # Conversion from a Go Duration // // The durationpb.New function can be used to construct a Duration message // from a standard Go time.Duration value: // // dur := durationpb.New(d) // ... // make use of d as a *durationpb.Duration package durationpb import ( protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" math "math" reflect "reflect" sync "sync" time "time" unsafe "unsafe" ) // A Duration represents a signed, fixed-length span of time represented // as a count of seconds and fractions of seconds at nanosecond // resolution. It is independent of any calendar and concepts like "day" // or "month". It is related to Timestamp in that the difference between // two Timestamp values is a Duration and it can be added or subtracted // from a Timestamp. Range is approximately +-10,000 years. // // # Examples // // Example 1: Compute Duration from two Timestamps in pseudo code. // // Timestamp start = ...; // Timestamp end = ...; // Duration duration = ...; // // duration.seconds = end.seconds - start.seconds; // duration.nanos = end.nanos - start.nanos; // // if (duration.seconds < 0 && duration.nanos > 0) { // duration.seconds += 1; // duration.nanos -= 1000000000; // } else if (duration.seconds > 0 && duration.nanos < 0) { // duration.seconds -= 1; // duration.nanos += 1000000000; // } // // Example 2: Compute Timestamp from Timestamp + Duration in pseudo code. // // Timestamp start = ...; // Duration duration = ...; // Timestamp end = ...; // // end.seconds = start.seconds + duration.seconds; // end.nanos = start.nanos + duration.nanos; // // if (end.nanos < 0) { // end.seconds -= 1; // end.nanos += 1000000000; // } else if (end.nanos >= 1000000000) { // end.seconds += 1; // end.nanos -= 1000000000; // } // // Example 3: Compute Duration from datetime.timedelta in Python. // // td = datetime.timedelta(days=3, minutes=10) // duration = Duration() // duration.FromTimedelta(td) // // # JSON Mapping // // In JSON format, the Duration type is encoded as a string rather than an // object, where the string ends in the suffix "s" (indicating seconds) and // is preceded by the number of seconds, with nanoseconds expressed as // fractional seconds. For example, 3 seconds with 0 nanoseconds should be // encoded in JSON format as "3s", while 3 seconds and 1 nanosecond should // be expressed in JSON format as "3.000000001s", and 3 seconds and 1 // microsecond should be expressed in JSON format as "3.000001s". type Duration struct { state protoimpl.MessageState `protogen:"open.v1"` // Signed seconds of the span of time. Must be from -315,576,000,000 // to +315,576,000,000 inclusive. Note: these bounds are computed from: // 60 sec/min * 60 min/hr * 24 hr/day * 365.25 days/year * 10000 years Seconds int64 `protobuf:"varint,1,opt,name=seconds,proto3" json:"seconds,omitempty"` // Signed fractions of a second at nanosecond resolution of the span // of time. Durations less than one second are represented with a 0 // `seconds` field and a positive or negative `nanos` field. For durations // of one second or more, a non-zero value for the `nanos` field must be // of the same sign as the `seconds` field. Must be from -999,999,999 // to +999,999,999 inclusive. Nanos int32 `protobuf:"varint,2,opt,name=nanos,proto3" json:"nanos,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // New constructs a new Duration from the provided time.Duration. func New(d time.Duration) *Duration { nanos := d.Nanoseconds() secs := nanos / 1e9 nanos -= secs * 1e9 return &Duration{Seconds: int64(secs), Nanos: int32(nanos)} } // AsDuration converts x to a time.Duration, // returning the closest duration value in the event of overflow. func (x *Duration) AsDuration() time.Duration { secs := x.GetSeconds() nanos := x.GetNanos() d := time.Duration(secs) * time.Second overflow := d/time.Second != time.Duration(secs) d += time.Duration(nanos) * time.Nanosecond overflow = overflow || (secs < 0 && nanos < 0 && d > 0) overflow = overflow || (secs > 0 && nanos > 0 && d < 0) if overflow { switch { case secs < 0: return time.Duration(math.MinInt64) case secs > 0: return time.Duration(math.MaxInt64) } } return d } // IsValid reports whether the duration is valid. // It is equivalent to CheckValid == nil. func (x *Duration) IsValid() bool { return x.check() == 0 } // CheckValid returns an error if the duration is invalid. // In particular, it checks whether the value is within the range of // -10000 years to +10000 years inclusive. // An error is reported for a nil Duration. func (x *Duration) CheckValid() error { switch x.check() { case invalidNil: return protoimpl.X.NewError("invalid nil Duration") case invalidUnderflow: return protoimpl.X.NewError("duration (%v) exceeds -10000 years", x) case invalidOverflow: return protoimpl.X.NewError("duration (%v) exceeds +10000 years", x) case invalidNanosRange: return protoimpl.X.NewError("duration (%v) has out-of-range nanos", x) case invalidNanosSign: return protoimpl.X.NewError("duration (%v) has seconds and nanos with different signs", x) default: return nil } } const ( _ = iota invalidNil invalidUnderflow invalidOverflow invalidNanosRange invalidNanosSign ) func (x *Duration) check() uint { const absDuration = 315576000000 // 10000yr * 365.25day/yr * 24hr/day * 60min/hr * 60sec/min secs := x.GetSeconds() nanos := x.GetNanos() switch { case x == nil: return invalidNil case secs < -absDuration: return invalidUnderflow case secs > +absDuration: return invalidOverflow case nanos <= -1e9 || nanos >= +1e9: return invalidNanosRange case (secs > 0 && nanos < 0) || (secs < 0 && nanos > 0): return invalidNanosSign default: return 0 } } func (x *Duration) Reset() { *x = Duration{} mi := &file_google_protobuf_duration_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Duration) String() string { return protoimpl.X.MessageStringOf(x) } func (*Duration) ProtoMessage() {} func (x *Duration) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_duration_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Duration.ProtoReflect.Descriptor instead. func (*Duration) Descriptor() ([]byte, []int) { return file_google_protobuf_duration_proto_rawDescGZIP(), []int{0} } func (x *Duration) GetSeconds() int64 { if x != nil { return x.Seconds } return 0 } func (x *Duration) GetNanos() int32 { if x != nil { return x.Nanos } return 0 } var File_google_protobuf_duration_proto protoreflect.FileDescriptor const file_google_protobuf_duration_proto_rawDesc = "" + "\n" + "\x1egoogle/protobuf/duration.proto\x12\x0fgoogle.protobuf\":\n" + "\bDuration\x12\x18\n" + "\aseconds\x18\x01 \x01(\x03R\aseconds\x12\x14\n" + "\x05nanos\x18\x02 \x01(\x05R\x05nanosB\x83\x01\n" + "\x13com.google.protobufB\rDurationProtoP\x01Z1google.golang.org/protobuf/types/known/durationpb\xf8\x01\x01\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_duration_proto_rawDescOnce sync.Once file_google_protobuf_duration_proto_rawDescData []byte ) func file_google_protobuf_duration_proto_rawDescGZIP() []byte { file_google_protobuf_duration_proto_rawDescOnce.Do(func() { file_google_protobuf_duration_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_duration_proto_rawDesc), len(file_google_protobuf_duration_proto_rawDesc))) }) return file_google_protobuf_duration_proto_rawDescData } var file_google_protobuf_duration_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_duration_proto_goTypes = []any{ (*Duration)(nil), // 0: google.protobuf.Duration } var file_google_protobuf_duration_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_duration_proto_init() } func file_google_protobuf_duration_proto_init() { if File_google_protobuf_duration_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_duration_proto_rawDesc), len(file_google_protobuf_duration_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_duration_proto_goTypes, DependencyIndexes: file_google_protobuf_duration_proto_depIdxs, MessageInfos: file_google_protobuf_duration_proto_msgTypes, }.Build() File_google_protobuf_duration_proto = out.File file_google_protobuf_duration_proto_goTypes = nil file_google_protobuf_duration_proto_depIdxs = 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/types/known/anypb/any.pb.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/types/known/anypb/any.pb.go
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Code generated by protoc-gen-go. DO NOT EDIT. // source: google/protobuf/any.proto // Package anypb contains generated types for google/protobuf/any.proto. // // The Any message is a dynamic representation of any other message value. // It is functionally a tuple of the full name of the remote message type and // the serialized bytes of the remote message value. // // # Constructing an Any // // An Any message containing another message value is constructed using New: // // any, err := anypb.New(m) // if err != nil { // ... // handle error // } // ... // make use of any // // # Unmarshaling an Any // // With a populated Any message, the underlying message can be serialized into // a remote concrete message value in a few ways. // // If the exact concrete type is known, then a new (or pre-existing) instance // of that message can be passed to the UnmarshalTo method: // // m := new(foopb.MyMessage) // if err := any.UnmarshalTo(m); err != nil { // ... // handle error // } // ... // make use of m // // If the exact concrete type is not known, then the UnmarshalNew method can be // used to unmarshal the contents into a new instance of the remote message type: // // m, err := any.UnmarshalNew() // if err != nil { // ... // handle error // } // ... // make use of m // // UnmarshalNew uses the global type registry to resolve the message type and // construct a new instance of that message to unmarshal into. In order for a // message type to appear in the global registry, the Go type representing that // protobuf message type must be linked into the Go binary. For messages // generated by protoc-gen-go, this is achieved through an import of the // generated Go package representing a .proto file. // // A common pattern with UnmarshalNew is to use a type switch with the resulting // proto.Message value: // // switch m := m.(type) { // case *foopb.MyMessage: // ... // make use of m as a *foopb.MyMessage // case *barpb.OtherMessage: // ... // make use of m as a *barpb.OtherMessage // case *bazpb.SomeMessage: // ... // make use of m as a *bazpb.SomeMessage // } // // This pattern ensures that the generated packages containing the message types // listed in the case clauses are linked into the Go binary and therefore also // registered in the global registry. // // # Type checking an Any // // In order to type check whether an Any message represents some other message, // then use the MessageIs method: // // if any.MessageIs((*foopb.MyMessage)(nil)) { // ... // make use of any, knowing that it contains a foopb.MyMessage // } // // The MessageIs method can also be used with an allocated instance of the target // message type if the intention is to unmarshal into it if the type matches: // // m := new(foopb.MyMessage) // if any.MessageIs(m) { // if err := any.UnmarshalTo(m); err != nil { // ... // handle error // } // ... // make use of m // } package anypb import ( proto "google.golang.org/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoregistry "google.golang.org/protobuf/reflect/protoregistry" protoimpl "google.golang.org/protobuf/runtime/protoimpl" reflect "reflect" strings "strings" sync "sync" unsafe "unsafe" ) // `Any` contains an arbitrary serialized protocol buffer message along with a // URL that describes the type of the serialized message. // // Protobuf library provides support to pack/unpack Any values in the form // of utility functions or additional generated methods of the Any type. // // Example 1: Pack and unpack a message in C++. // // Foo foo = ...; // Any any; // any.PackFrom(foo); // ... // if (any.UnpackTo(&foo)) { // ... // } // // Example 2: Pack and unpack a message in Java. // // Foo foo = ...; // Any any = Any.pack(foo); // ... // if (any.is(Foo.class)) { // foo = any.unpack(Foo.class); // } // // or ... // if (any.isSameTypeAs(Foo.getDefaultInstance())) { // foo = any.unpack(Foo.getDefaultInstance()); // } // // Example 3: Pack and unpack a message in Python. // // foo = Foo(...) // any = Any() // any.Pack(foo) // ... // if any.Is(Foo.DESCRIPTOR): // any.Unpack(foo) // ... // // Example 4: Pack and unpack a message in Go // // foo := &pb.Foo{...} // any, err := anypb.New(foo) // if err != nil { // ... // } // ... // foo := &pb.Foo{} // if err := any.UnmarshalTo(foo); err != nil { // ... // } // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". // // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": <string>, // "lastName": <string> // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } type Any struct { state protoimpl.MessageState `protogen:"open.v1"` // A URL/resource name that uniquely identifies the type of the serialized // protocol buffer message. This string must contain at least // one "/" character. The last segment of the URL's path must represent // the fully qualified name of the type (as in // `path/google.protobuf.Duration`). The name should be in a canonical form // (e.g., leading "." is not accepted). // // In practice, teams usually precompile into the binary all types that they // expect it to use in the context of Any. However, for URLs which use the // scheme `http`, `https`, or no scheme, one can optionally set up a type // server that maps type URLs to message definitions as follows: // // - If no scheme is provided, `https` is assumed. // - An HTTP GET on the URL must yield a [google.protobuf.Type][] // value in binary format, or produce an error. // - Applications are allowed to cache lookup results based on the // URL, or have them precompiled into a binary to avoid any // lookup. Therefore, binary compatibility needs to be preserved // on changes to types. (Use versioned type names to manage // breaking changes.) // // Note: this functionality is not currently available in the official // protobuf release, and it is not used for type URLs beginning with // type.googleapis.com. As of May 2023, there are no widely used type server // implementations and no plans to implement one. // // Schemes other than `http`, `https` (or the empty scheme) might be // used with implementation specific semantics. TypeUrl string `protobuf:"bytes,1,opt,name=type_url,json=typeUrl,proto3" json:"type_url,omitempty"` // Must be a valid serialized protocol buffer of the above specified type. Value []byte `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } // New marshals src into a new Any instance. func New(src proto.Message) (*Any, error) { dst := new(Any) if err := dst.MarshalFrom(src); err != nil { return nil, err } return dst, nil } // MarshalFrom marshals src into dst as the underlying message // using the provided marshal options. // // If no options are specified, call dst.MarshalFrom instead. func MarshalFrom(dst *Any, src proto.Message, opts proto.MarshalOptions) error { const urlPrefix = "type.googleapis.com/" if src == nil { return protoimpl.X.NewError("invalid nil source message") } b, err := opts.Marshal(src) if err != nil { return err } dst.TypeUrl = urlPrefix + string(src.ProtoReflect().Descriptor().FullName()) dst.Value = b return nil } // UnmarshalTo unmarshals the underlying message from src into dst // using the provided unmarshal options. // It reports an error if dst is not of the right message type. // // If no options are specified, call src.UnmarshalTo instead. func UnmarshalTo(src *Any, dst proto.Message, opts proto.UnmarshalOptions) error { if src == nil { return protoimpl.X.NewError("invalid nil source message") } if !src.MessageIs(dst) { got := dst.ProtoReflect().Descriptor().FullName() want := src.MessageName() return protoimpl.X.NewError("mismatched message type: got %q, want %q", got, want) } return opts.Unmarshal(src.GetValue(), dst) } // UnmarshalNew unmarshals the underlying message from src into dst, // which is newly created message using a type resolved from the type URL. // The message type is resolved according to opt.Resolver, // which should implement protoregistry.MessageTypeResolver. // It reports an error if the underlying message type could not be resolved. // // If no options are specified, call src.UnmarshalNew instead. func UnmarshalNew(src *Any, opts proto.UnmarshalOptions) (dst proto.Message, err error) { if src.GetTypeUrl() == "" { return nil, protoimpl.X.NewError("invalid empty type URL") } if opts.Resolver == nil { opts.Resolver = protoregistry.GlobalTypes } r, ok := opts.Resolver.(protoregistry.MessageTypeResolver) if !ok { return nil, protoregistry.NotFound } mt, err := r.FindMessageByURL(src.GetTypeUrl()) if err != nil { if err == protoregistry.NotFound { return nil, err } return nil, protoimpl.X.NewError("could not resolve %q: %v", src.GetTypeUrl(), err) } dst = mt.New().Interface() return dst, opts.Unmarshal(src.GetValue(), dst) } // MessageIs reports whether the underlying message is of the same type as m. func (x *Any) MessageIs(m proto.Message) bool { if m == nil { return false } url := x.GetTypeUrl() name := string(m.ProtoReflect().Descriptor().FullName()) if !strings.HasSuffix(url, name) { return false } return len(url) == len(name) || url[len(url)-len(name)-1] == '/' } // MessageName reports the full name of the underlying message, // returning an empty string if invalid. func (x *Any) MessageName() protoreflect.FullName { url := x.GetTypeUrl() name := protoreflect.FullName(url) if i := strings.LastIndexByte(url, '/'); i >= 0 { name = name[i+len("/"):] } if !name.IsValid() { return "" } return name } // MarshalFrom marshals m into x as the underlying message. func (x *Any) MarshalFrom(m proto.Message) error { return MarshalFrom(x, m, proto.MarshalOptions{}) } // UnmarshalTo unmarshals the contents of the underlying message of x into m. // It resets m before performing the unmarshal operation. // It reports an error if m is not of the right message type. func (x *Any) UnmarshalTo(m proto.Message) error { return UnmarshalTo(x, m, proto.UnmarshalOptions{}) } // UnmarshalNew unmarshals the contents of the underlying message of x into // a newly allocated message of the specified type. // It reports an error if the underlying message type could not be resolved. func (x *Any) UnmarshalNew() (proto.Message, error) { return UnmarshalNew(x, proto.UnmarshalOptions{}) } func (x *Any) Reset() { *x = Any{} mi := &file_google_protobuf_any_proto_msgTypes[0] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } func (x *Any) String() string { return protoimpl.X.MessageStringOf(x) } func (*Any) ProtoMessage() {} func (x *Any) ProtoReflect() protoreflect.Message { mi := &file_google_protobuf_any_proto_msgTypes[0] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { ms.StoreMessageInfo(mi) } return ms } return mi.MessageOf(x) } // Deprecated: Use Any.ProtoReflect.Descriptor instead. func (*Any) Descriptor() ([]byte, []int) { return file_google_protobuf_any_proto_rawDescGZIP(), []int{0} } func (x *Any) GetTypeUrl() string { if x != nil { return x.TypeUrl } return "" } func (x *Any) GetValue() []byte { if x != nil { return x.Value } return nil } var File_google_protobuf_any_proto protoreflect.FileDescriptor const file_google_protobuf_any_proto_rawDesc = "" + "\n" + "\x19google/protobuf/any.proto\x12\x0fgoogle.protobuf\"6\n" + "\x03Any\x12\x19\n" + "\btype_url\x18\x01 \x01(\tR\atypeUrl\x12\x14\n" + "\x05value\x18\x02 \x01(\fR\x05valueBv\n" + "\x13com.google.protobufB\bAnyProtoP\x01Z,google.golang.org/protobuf/types/known/anypb\xa2\x02\x03GPB\xaa\x02\x1eGoogle.Protobuf.WellKnownTypesb\x06proto3" var ( file_google_protobuf_any_proto_rawDescOnce sync.Once file_google_protobuf_any_proto_rawDescData []byte ) func file_google_protobuf_any_proto_rawDescGZIP() []byte { file_google_protobuf_any_proto_rawDescOnce.Do(func() { file_google_protobuf_any_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_google_protobuf_any_proto_rawDesc), len(file_google_protobuf_any_proto_rawDesc))) }) return file_google_protobuf_any_proto_rawDescData } var file_google_protobuf_any_proto_msgTypes = make([]protoimpl.MessageInfo, 1) var file_google_protobuf_any_proto_goTypes = []any{ (*Any)(nil), // 0: google.protobuf.Any } var file_google_protobuf_any_proto_depIdxs = []int32{ 0, // [0:0] is the sub-list for method output_type 0, // [0:0] is the sub-list for method input_type 0, // [0:0] is the sub-list for extension type_name 0, // [0:0] is the sub-list for extension extendee 0, // [0:0] is the sub-list for field type_name } func init() { file_google_protobuf_any_proto_init() } func file_google_protobuf_any_proto_init() { if File_google_protobuf_any_proto != nil { return } type x struct{} out := protoimpl.TypeBuilder{ File: protoimpl.DescBuilder{ GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_google_protobuf_any_proto_rawDesc), len(file_google_protobuf_any_proto_rawDesc)), NumEnums: 0, NumMessages: 1, NumExtensions: 0, NumServices: 0, }, GoTypes: file_google_protobuf_any_proto_goTypes, DependencyIndexes: file_google_protobuf_any_proto_depIdxs, MessageInfos: file_google_protobuf_any_proto_msgTypes, }.Build() File_google_protobuf_any_proto = out.File file_google_protobuf_any_proto_goTypes = nil file_google_protobuf_any_proto_depIdxs = 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/reflect/protoregistry/registry.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoregistry/registry.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 protoregistry provides data structures to register and lookup // protobuf descriptor types. // // The [Files] registry contains file descriptors and provides the ability // to iterate over the files or lookup a specific descriptor within the files. // [Files] only contains protobuf descriptors and has no understanding of Go // type information that may be associated with each descriptor. // // The [Types] registry contains descriptor types for which there is a known // Go type associated with that descriptor. It provides the ability to iterate // over the registered types or lookup a type by name. package protoregistry import ( "fmt" "os" "strings" "sync" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/flags" "google.golang.org/protobuf/reflect/protoreflect" ) // conflictPolicy configures the policy for handling registration conflicts. // // It can be over-written at compile time with a linker-initialized variable: // // go build -ldflags "-X google.golang.org/protobuf/reflect/protoregistry.conflictPolicy=warn" // // It can be over-written at program execution with an environment variable: // // GOLANG_PROTOBUF_REGISTRATION_CONFLICT=warn ./main // // Neither of the above are covered by the compatibility promise and // may be removed in a future release of this module. var conflictPolicy = "panic" // "panic" | "warn" | "ignore" // ignoreConflict reports whether to ignore a registration conflict // given the descriptor being registered and the error. // It is a variable so that the behavior is easily overridden in another file. var ignoreConflict = func(d protoreflect.Descriptor, err error) bool { const env = "GOLANG_PROTOBUF_REGISTRATION_CONFLICT" const faq = "https://protobuf.dev/reference/go/faq#namespace-conflict" policy := conflictPolicy if v := os.Getenv(env); v != "" { policy = v } switch policy { case "panic": panic(fmt.Sprintf("%v\nSee %v\n", err, faq)) case "warn": fmt.Fprintf(os.Stderr, "WARNING: %v\nSee %v\n\n", err, faq) return true case "ignore": return true default: panic("invalid " + env + " value: " + os.Getenv(env)) } } var globalMutex sync.RWMutex // GlobalFiles is a global registry of file descriptors. var GlobalFiles *Files = new(Files) // GlobalTypes is the registry used by default for type lookups // unless a local registry is provided by the user. var GlobalTypes *Types = new(Types) // NotFound is a sentinel error value to indicate that the type was not found. // // Since registry lookup can happen in the critical performance path, resolvers // must return this exact error value, not an error wrapping it. var NotFound = errors.New("not found") // Files is a registry for looking up or iterating over files and the // descriptors contained within them. // The Find and Range methods are safe for concurrent use. type Files struct { // The map of descsByName contains: // EnumDescriptor // EnumValueDescriptor // MessageDescriptor // ExtensionDescriptor // ServiceDescriptor // *packageDescriptor // // Note that files are stored as a slice, since a package may contain // multiple files. Only top-level declarations are registered. // Note that enum values are in the top-level since that are in the same // scope as the parent enum. descsByName map[protoreflect.FullName]any filesByPath map[string][]protoreflect.FileDescriptor numFiles int } type packageDescriptor struct { files []protoreflect.FileDescriptor } // RegisterFile registers the provided file descriptor. // // If any descriptor within the file conflicts with the descriptor of any // previously registered file (e.g., two enums with the same full name), // then the file is not registered and an error is returned. // // It is permitted for multiple files to have the same file path. func (r *Files) RegisterFile(file protoreflect.FileDescriptor) error { if r == GlobalFiles { globalMutex.Lock() defer globalMutex.Unlock() } if r.descsByName == nil { r.descsByName = map[protoreflect.FullName]any{ "": &packageDescriptor{}, } r.filesByPath = make(map[string][]protoreflect.FileDescriptor) } path := file.Path() if prev := r.filesByPath[path]; len(prev) > 0 { r.checkGenProtoConflict(path) err := errors.New("file %q is already registered", file.Path()) err = amendErrorWithCaller(err, prev[0], file) if !(r == GlobalFiles && ignoreConflict(file, err)) { return err } } for name := file.Package(); name != ""; name = name.Parent() { switch prev := r.descsByName[name]; prev.(type) { case nil, *packageDescriptor: default: err := errors.New("file %q has a package name conflict over %v", file.Path(), name) err = amendErrorWithCaller(err, prev, file) if r == GlobalFiles && ignoreConflict(file, err) { err = nil } return err } } var err error var hasConflict bool rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) { if prev := r.descsByName[d.FullName()]; prev != nil { hasConflict = true err = errors.New("file %q has a name conflict over %v", file.Path(), d.FullName()) err = amendErrorWithCaller(err, prev, file) if r == GlobalFiles && ignoreConflict(d, err) { err = nil } } }) if hasConflict { return err } for name := file.Package(); name != ""; name = name.Parent() { if r.descsByName[name] == nil { r.descsByName[name] = &packageDescriptor{} } } p := r.descsByName[file.Package()].(*packageDescriptor) p.files = append(p.files, file) rangeTopLevelDescriptors(file, func(d protoreflect.Descriptor) { r.descsByName[d.FullName()] = d }) r.filesByPath[path] = append(r.filesByPath[path], file) r.numFiles++ return nil } // Several well-known types were hosted in the google.golang.org/genproto module // but were later moved to this module. To avoid a weak dependency on the // genproto module (and its relatively large set of transitive dependencies), // we rely on a registration conflict to determine whether the genproto version // is too old (i.e., does not contain aliases to the new type declarations). func (r *Files) checkGenProtoConflict(path string) { if r != GlobalFiles { return } var prevPath string const prevModule = "google.golang.org/genproto" const prevVersion = "cb27e3aa (May 26th, 2020)" switch path { case "google/protobuf/field_mask.proto": prevPath = prevModule + "/protobuf/field_mask" case "google/protobuf/api.proto": prevPath = prevModule + "/protobuf/api" case "google/protobuf/type.proto": prevPath = prevModule + "/protobuf/ptype" case "google/protobuf/source_context.proto": prevPath = prevModule + "/protobuf/source_context" default: return } pkgName := strings.TrimSuffix(strings.TrimPrefix(path, "google/protobuf/"), ".proto") pkgName = strings.Replace(pkgName, "_", "", -1) + "pb" // e.g., "field_mask" => "fieldmaskpb" currPath := "google.golang.org/protobuf/types/known/" + pkgName panic(fmt.Sprintf(""+ "duplicate registration of %q\n"+ "\n"+ "The generated definition for this file has moved:\n"+ "\tfrom: %q\n"+ "\tto: %q\n"+ "A dependency on the %q module must\n"+ "be at version %v or higher.\n"+ "\n"+ "Upgrade the dependency by running:\n"+ "\tgo get -u %v\n", path, prevPath, currPath, prevModule, prevVersion, prevPath)) } // FindDescriptorByName looks up a descriptor by the full name. // // This returns (nil, [NotFound]) if not found. func (r *Files) FindDescriptorByName(name protoreflect.FullName) (protoreflect.Descriptor, error) { if r == nil { return nil, NotFound } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } prefix := name suffix := nameSuffix("") for prefix != "" { if d, ok := r.descsByName[prefix]; ok { switch d := d.(type) { case protoreflect.EnumDescriptor: if d.FullName() == name { return d, nil } case protoreflect.EnumValueDescriptor: if d.FullName() == name { return d, nil } case protoreflect.MessageDescriptor: if d.FullName() == name { return d, nil } if d := findDescriptorInMessage(d, suffix); d != nil && d.FullName() == name { return d, nil } case protoreflect.ExtensionDescriptor: if d.FullName() == name { return d, nil } case protoreflect.ServiceDescriptor: if d.FullName() == name { return d, nil } if d := d.Methods().ByName(suffix.Pop()); d != nil && d.FullName() == name { return d, nil } } return nil, NotFound } prefix = prefix.Parent() suffix = nameSuffix(name[len(prefix)+len("."):]) } return nil, NotFound } func findDescriptorInMessage(md protoreflect.MessageDescriptor, suffix nameSuffix) protoreflect.Descriptor { name := suffix.Pop() if suffix == "" { if ed := md.Enums().ByName(name); ed != nil { return ed } for i := md.Enums().Len() - 1; i >= 0; i-- { if vd := md.Enums().Get(i).Values().ByName(name); vd != nil { return vd } } if xd := md.Extensions().ByName(name); xd != nil { return xd } if fd := md.Fields().ByName(name); fd != nil { return fd } if od := md.Oneofs().ByName(name); od != nil { return od } } if md := md.Messages().ByName(name); md != nil { if suffix == "" { return md } return findDescriptorInMessage(md, suffix) } return nil } type nameSuffix string func (s *nameSuffix) Pop() (name protoreflect.Name) { if i := strings.IndexByte(string(*s), '.'); i >= 0 { name, *s = protoreflect.Name((*s)[:i]), (*s)[i+1:] } else { name, *s = protoreflect.Name((*s)), "" } return name } // FindFileByPath looks up a file by the path. // // This returns (nil, [NotFound]) if not found. // This returns an error if multiple files have the same path. func (r *Files) FindFileByPath(path string) (protoreflect.FileDescriptor, error) { if r == nil { return nil, NotFound } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } fds := r.filesByPath[path] switch len(fds) { case 0: return nil, NotFound case 1: return fds[0], nil default: return nil, errors.New("multiple files named %q", path) } } // NumFiles reports the number of registered files, // including duplicate files with the same name. func (r *Files) NumFiles() int { if r == nil { return 0 } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } return r.numFiles } // RangeFiles iterates over all registered files while f returns true. // If multiple files have the same name, RangeFiles iterates over all of them. // The iteration order is undefined. func (r *Files) RangeFiles(f func(protoreflect.FileDescriptor) bool) { if r == nil { return } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } for _, files := range r.filesByPath { for _, file := range files { if !f(file) { return } } } } // NumFilesByPackage reports the number of registered files in a proto package. func (r *Files) NumFilesByPackage(name protoreflect.FullName) int { if r == nil { return 0 } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } p, ok := r.descsByName[name].(*packageDescriptor) if !ok { return 0 } return len(p.files) } // RangeFilesByPackage iterates over all registered files in a given proto package // while f returns true. The iteration order is undefined. func (r *Files) RangeFilesByPackage(name protoreflect.FullName, f func(protoreflect.FileDescriptor) bool) { if r == nil { return } if r == GlobalFiles { globalMutex.RLock() defer globalMutex.RUnlock() } p, ok := r.descsByName[name].(*packageDescriptor) if !ok { return } for _, file := range p.files { if !f(file) { return } } } // rangeTopLevelDescriptors iterates over all top-level descriptors in a file // which will be directly entered into the registry. func rangeTopLevelDescriptors(fd protoreflect.FileDescriptor, f func(protoreflect.Descriptor)) { eds := fd.Enums() for i := eds.Len() - 1; i >= 0; i-- { f(eds.Get(i)) vds := eds.Get(i).Values() for i := vds.Len() - 1; i >= 0; i-- { f(vds.Get(i)) } } mds := fd.Messages() for i := mds.Len() - 1; i >= 0; i-- { f(mds.Get(i)) } xds := fd.Extensions() for i := xds.Len() - 1; i >= 0; i-- { f(xds.Get(i)) } sds := fd.Services() for i := sds.Len() - 1; i >= 0; i-- { f(sds.Get(i)) } } // MessageTypeResolver is an interface for looking up messages. // // A compliant implementation must deterministically return the same type // if no error is encountered. // // The [Types] type implements this interface. type MessageTypeResolver interface { // FindMessageByName looks up a message by its full name. // E.g., "google.protobuf.Any" // // This return (nil, NotFound) if not found. FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) // FindMessageByURL looks up a message by a URL identifier. // See documentation on google.protobuf.Any.type_url for the URL format. // // This returns (nil, NotFound) if not found. FindMessageByURL(url string) (protoreflect.MessageType, error) } // ExtensionTypeResolver is an interface for looking up extensions. // // A compliant implementation must deterministically return the same type // if no error is encountered. // // The [Types] type implements this interface. type ExtensionTypeResolver interface { // FindExtensionByName looks up a extension field by the field's full name. // Note that this is the full name of the field as determined by // where the extension is declared and is unrelated to the full name of the // message being extended. // // This returns (nil, NotFound) if not found. FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) // FindExtensionByNumber looks up a extension field by the field number // within some parent message, identified by full name. // // This returns (nil, NotFound) if not found. FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) } var ( _ MessageTypeResolver = (*Types)(nil) _ ExtensionTypeResolver = (*Types)(nil) ) // Types is a registry for looking up or iterating over descriptor types. // The Find and Range methods are safe for concurrent use. type Types struct { typesByName typesByName extensionsByMessage extensionsByMessage numEnums int numMessages int numExtensions int } type ( typesByName map[protoreflect.FullName]any extensionsByMessage map[protoreflect.FullName]extensionsByNumber extensionsByNumber map[protoreflect.FieldNumber]protoreflect.ExtensionType ) // RegisterMessage registers the provided message type. // // If a naming conflict occurs, the type is not registered and an error is returned. func (r *Types) RegisterMessage(mt protoreflect.MessageType) error { // Under rare circumstances getting the descriptor might recursively // examine the registry, so fetch it before locking. md := mt.Descriptor() if r == GlobalTypes { globalMutex.Lock() defer globalMutex.Unlock() } if err := r.register("message", md, mt); err != nil { return err } r.numMessages++ return nil } // RegisterEnum registers the provided enum type. // // If a naming conflict occurs, the type is not registered and an error is returned. func (r *Types) RegisterEnum(et protoreflect.EnumType) error { // Under rare circumstances getting the descriptor might recursively // examine the registry, so fetch it before locking. ed := et.Descriptor() if r == GlobalTypes { globalMutex.Lock() defer globalMutex.Unlock() } if err := r.register("enum", ed, et); err != nil { return err } r.numEnums++ return nil } // RegisterExtension registers the provided extension type. // // If a naming conflict occurs, the type is not registered and an error is returned. func (r *Types) RegisterExtension(xt protoreflect.ExtensionType) error { // Under rare circumstances getting the descriptor might recursively // examine the registry, so fetch it before locking. // // A known case where this can happen: Fetching the TypeDescriptor for a // legacy ExtensionDesc can consult the global registry. xd := xt.TypeDescriptor() if r == GlobalTypes { globalMutex.Lock() defer globalMutex.Unlock() } field := xd.Number() message := xd.ContainingMessage().FullName() if prev := r.extensionsByMessage[message][field]; prev != nil { err := errors.New("extension number %d is already registered on message %v", field, message) err = amendErrorWithCaller(err, prev, xt) if !(r == GlobalTypes && ignoreConflict(xd, err)) { return err } } if err := r.register("extension", xd, xt); err != nil { return err } if r.extensionsByMessage == nil { r.extensionsByMessage = make(extensionsByMessage) } if r.extensionsByMessage[message] == nil { r.extensionsByMessage[message] = make(extensionsByNumber) } r.extensionsByMessage[message][field] = xt r.numExtensions++ return nil } func (r *Types) register(kind string, desc protoreflect.Descriptor, typ any) error { name := desc.FullName() prev := r.typesByName[name] if prev != nil { err := errors.New("%v %v is already registered", kind, name) err = amendErrorWithCaller(err, prev, typ) if !(r == GlobalTypes && ignoreConflict(desc, err)) { return err } } if r.typesByName == nil { r.typesByName = make(typesByName) } r.typesByName[name] = typ return nil } // FindEnumByName looks up an enum by its full name. // E.g., "google.protobuf.Field.Kind". // // This returns (nil, [NotFound]) if not found. func (r *Types) FindEnumByName(enum protoreflect.FullName) (protoreflect.EnumType, error) { if r == nil { return nil, NotFound } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } if v := r.typesByName[enum]; v != nil { if et, _ := v.(protoreflect.EnumType); et != nil { return et, nil } return nil, errors.New("found wrong type: got %v, want enum", typeName(v)) } return nil, NotFound } // FindMessageByName looks up a message by its full name, // e.g. "google.protobuf.Any". // // This returns (nil, [NotFound]) if not found. func (r *Types) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { if r == nil { return nil, NotFound } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } if v := r.typesByName[message]; v != nil { if mt, _ := v.(protoreflect.MessageType); mt != nil { return mt, nil } return nil, errors.New("found wrong type: got %v, want message", typeName(v)) } return nil, NotFound } // FindMessageByURL looks up a message by a URL identifier. // See documentation on google.protobuf.Any.type_url for the URL format. // // This returns (nil, [NotFound]) if not found. func (r *Types) FindMessageByURL(url string) (protoreflect.MessageType, error) { // This function is similar to FindMessageByName but // truncates anything before and including '/' in the URL. if r == nil { return nil, NotFound } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } message := protoreflect.FullName(url) if i := strings.LastIndexByte(url, '/'); i >= 0 { message = message[i+len("/"):] } if v := r.typesByName[message]; v != nil { if mt, _ := v.(protoreflect.MessageType); mt != nil { return mt, nil } return nil, errors.New("found wrong type: got %v, want message", typeName(v)) } return nil, NotFound } // FindExtensionByName looks up a extension field by the field's full name. // Note that this is the full name of the field as determined by // where the extension is declared and is unrelated to the full name of the // message being extended. // // This returns (nil, [NotFound]) if not found. func (r *Types) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { if r == nil { return nil, NotFound } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } if v := r.typesByName[field]; v != nil { if xt, _ := v.(protoreflect.ExtensionType); xt != nil { return xt, nil } // MessageSet extensions are special in that the name of the extension // is the name of the message type used to extend the MessageSet. // This naming scheme is used by text and JSON serialization. // // This feature is protected by the ProtoLegacy flag since MessageSets // are a proto1 feature that is long deprecated. if flags.ProtoLegacy { if _, ok := v.(protoreflect.MessageType); ok { field := field.Append(messageset.ExtensionName) if v := r.typesByName[field]; v != nil { if xt, _ := v.(protoreflect.ExtensionType); xt != nil { if messageset.IsMessageSetExtension(xt.TypeDescriptor()) { return xt, nil } } } } } return nil, errors.New("found wrong type: got %v, want extension", typeName(v)) } return nil, NotFound } // FindExtensionByNumber looks up a extension field by the field number // within some parent message, identified by full name. // // This returns (nil, [NotFound]) if not found. func (r *Types) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { if r == nil { return nil, NotFound } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } if xt, ok := r.extensionsByMessage[message][field]; ok { return xt, nil } return nil, NotFound } // NumEnums reports the number of registered enums. func (r *Types) NumEnums() int { if r == nil { return 0 } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } return r.numEnums } // RangeEnums iterates over all registered enums while f returns true. // Iteration order is undefined. func (r *Types) RangeEnums(f func(protoreflect.EnumType) bool) { if r == nil { return } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } for _, typ := range r.typesByName { if et, ok := typ.(protoreflect.EnumType); ok { if !f(et) { return } } } } // NumMessages reports the number of registered messages. func (r *Types) NumMessages() int { if r == nil { return 0 } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } return r.numMessages } // RangeMessages iterates over all registered messages while f returns true. // Iteration order is undefined. func (r *Types) RangeMessages(f func(protoreflect.MessageType) bool) { if r == nil { return } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } for _, typ := range r.typesByName { if mt, ok := typ.(protoreflect.MessageType); ok { if !f(mt) { return } } } } // NumExtensions reports the number of registered extensions. func (r *Types) NumExtensions() int { if r == nil { return 0 } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } return r.numExtensions } // RangeExtensions iterates over all registered extensions while f returns true. // Iteration order is undefined. func (r *Types) RangeExtensions(f func(protoreflect.ExtensionType) bool) { if r == nil { return } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } for _, typ := range r.typesByName { if xt, ok := typ.(protoreflect.ExtensionType); ok { if !f(xt) { return } } } } // NumExtensionsByMessage reports the number of registered extensions for // a given message type. func (r *Types) NumExtensionsByMessage(message protoreflect.FullName) int { if r == nil { return 0 } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } return len(r.extensionsByMessage[message]) } // RangeExtensionsByMessage iterates over all registered extensions filtered // by a given message type while f returns true. Iteration order is undefined. func (r *Types) RangeExtensionsByMessage(message protoreflect.FullName, f func(protoreflect.ExtensionType) bool) { if r == nil { return } if r == GlobalTypes { globalMutex.RLock() defer globalMutex.RUnlock() } for _, xt := range r.extensionsByMessage[message] { if !f(xt) { return } } } func typeName(t any) string { switch t.(type) { case protoreflect.EnumType: return "enum" case protoreflect.MessageType: return "message" case protoreflect.ExtensionType: return "extension" default: return fmt.Sprintf("%T", t) } } func amendErrorWithCaller(err error, prev, curr any) error { prevPkg := goPackage(prev) currPkg := goPackage(curr) if prevPkg == "" || currPkg == "" || prevPkg == currPkg { return err } return errors.New("%s\n\tpreviously from: %q\n\tcurrently from: %q", err, prevPkg, currPkg) } func goPackage(v any) string { switch d := v.(type) { case protoreflect.EnumType: v = d.Descriptor() case protoreflect.MessageType: v = d.Descriptor() case protoreflect.ExtensionType: v = d.TypeDescriptor() } if d, ok := v.(protoreflect.Descriptor); ok { v = d.ParentFile() } if d, ok := v.(interface{ GoPackagePath() string }); ok { return d.GoPackagePath() } 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/reflect/protoreflect/value_union.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/value_union.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 protoreflect import ( "fmt" "math" ) // Value is a union where only one Go type may be set at a time. // The Value is used to represent all possible values a field may take. // The following shows which Go type is used to represent each proto [Kind]: // // ╔════════════╤═════════════════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠════════════╪═════════════════════════════════════╣ // ║ bool │ BoolKind ║ // ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║ // ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║ // ║ uint32 │ Uint32Kind, Fixed32Kind ║ // ║ uint64 │ Uint64Kind, Fixed64Kind ║ // ║ float32 │ FloatKind ║ // ║ float64 │ DoubleKind ║ // ║ string │ StringKind ║ // ║ []byte │ BytesKind ║ // ║ EnumNumber │ EnumKind ║ // ║ Message │ MessageKind, GroupKind ║ // ╚════════════╧═════════════════════════════════════╝ // // Multiple protobuf Kinds may be represented by a single Go type if the type // can losslessly represent the information for the proto kind. For example, // [Int64Kind], [Sint64Kind], and [Sfixed64Kind] are all represented by int64, // but use different integer encoding methods. // // The [List] or [Map] types are used if the field cardinality is repeated. // A field is a [List] if [FieldDescriptor.IsList] reports true. // A field is a [Map] if [FieldDescriptor.IsMap] reports true. // // Converting to/from a Value and a concrete Go value panics on type mismatch. // For example, [ValueOf]("hello").Int() panics because this attempts to // retrieve an int64 from a string. // // [List], [Map], and [Message] Values are called "composite" values. // // A composite Value may alias (reference) memory at some location, // such that changes to the Value updates the that location. // A composite value acquired with a Mutable method, such as [Message.Mutable], // always references the source object. // // For example: // // // Append a 0 to a "repeated int32" field. // // Since the Value returned by Mutable is guaranteed to alias // // the source message, modifying the Value modifies the message. // message.Mutable(fieldDesc).List().Append(protoreflect.ValueOfInt32(0)) // // // Assign [0] to a "repeated int32" field by creating a new Value, // // modifying it, and assigning it. // list := message.NewField(fieldDesc).List() // list.Append(protoreflect.ValueOfInt32(0)) // message.Set(fieldDesc, list) // // ERROR: Since it is not defined whether Set aliases the source, // // appending to the List here may or may not modify the message. // list.Append(protoreflect.ValueOfInt32(0)) // // Some operations, such as [Message.Get], may return an "empty, read-only" // composite Value. Modifying an empty, read-only value panics. type Value value // The protoreflect API uses a custom Value union type instead of any // to keep the future open for performance optimizations. Using an any // always incurs an allocation for primitives (e.g., int64) since it needs to // be boxed on the heap (as interfaces can only contain pointers natively). // Instead, we represent the Value union as a flat struct that internally keeps // track of which type is set. Using unsafe, the Value union can be reduced // down to 24B, which is identical in size to a slice. // // The latest compiler (Go1.11) currently suffers from some limitations: // • With inlining, the compiler should be able to statically prove that // only one of these switch cases are taken and inline one specific case. // See https://golang.org/issue/22310. // ValueOf returns a Value initialized with the concrete value stored in v. // This panics if the type does not match one of the allowed types in the // Value union. func ValueOf(v any) Value { switch v := v.(type) { case nil: return Value{} case bool: return ValueOfBool(v) case int32: return ValueOfInt32(v) case int64: return ValueOfInt64(v) case uint32: return ValueOfUint32(v) case uint64: return ValueOfUint64(v) case float32: return ValueOfFloat32(v) case float64: return ValueOfFloat64(v) case string: return ValueOfString(v) case []byte: return ValueOfBytes(v) case EnumNumber: return ValueOfEnum(v) case Message, List, Map: return valueOfIface(v) case ProtoMessage: panic(fmt.Sprintf("invalid proto.Message(%T) type, expected a protoreflect.Message type", v)) default: panic(fmt.Sprintf("invalid type: %T", v)) } } // ValueOfBool returns a new boolean value. func ValueOfBool(v bool) Value { if v { return Value{typ: boolType, num: 1} } else { return Value{typ: boolType, num: 0} } } // ValueOfInt32 returns a new int32 value. func ValueOfInt32(v int32) Value { return Value{typ: int32Type, num: uint64(v)} } // ValueOfInt64 returns a new int64 value. func ValueOfInt64(v int64) Value { return Value{typ: int64Type, num: uint64(v)} } // ValueOfUint32 returns a new uint32 value. func ValueOfUint32(v uint32) Value { return Value{typ: uint32Type, num: uint64(v)} } // ValueOfUint64 returns a new uint64 value. func ValueOfUint64(v uint64) Value { return Value{typ: uint64Type, num: v} } // ValueOfFloat32 returns a new float32 value. func ValueOfFloat32(v float32) Value { return Value{typ: float32Type, num: uint64(math.Float64bits(float64(v)))} } // ValueOfFloat64 returns a new float64 value. func ValueOfFloat64(v float64) Value { return Value{typ: float64Type, num: uint64(math.Float64bits(float64(v)))} } // ValueOfString returns a new string value. func ValueOfString(v string) Value { return valueOfString(v) } // ValueOfBytes returns a new bytes value. func ValueOfBytes(v []byte) Value { return valueOfBytes(v[:len(v):len(v)]) } // ValueOfEnum returns a new enum value. func ValueOfEnum(v EnumNumber) Value { return Value{typ: enumType, num: uint64(v)} } // ValueOfMessage returns a new Message value. func ValueOfMessage(v Message) Value { return valueOfIface(v) } // ValueOfList returns a new List value. func ValueOfList(v List) Value { return valueOfIface(v) } // ValueOfMap returns a new Map value. func ValueOfMap(v Map) Value { return valueOfIface(v) } // IsValid reports whether v is populated with a value. func (v Value) IsValid() bool { return v.typ != nilType } // Interface returns v as an any. // // Invariant: v == ValueOf(v).Interface() func (v Value) Interface() any { switch v.typ { case nilType: return nil case boolType: return v.Bool() case int32Type: return int32(v.Int()) case int64Type: return int64(v.Int()) case uint32Type: return uint32(v.Uint()) case uint64Type: return uint64(v.Uint()) case float32Type: return float32(v.Float()) case float64Type: return float64(v.Float()) case stringType: return v.String() case bytesType: return v.Bytes() case enumType: return v.Enum() default: return v.getIface() } } func (v Value) typeName() string { switch v.typ { case nilType: return "nil" case boolType: return "bool" case int32Type: return "int32" case int64Type: return "int64" case uint32Type: return "uint32" case uint64Type: return "uint64" case float32Type: return "float32" case float64Type: return "float64" case stringType: return "string" case bytesType: return "bytes" case enumType: return "enum" default: switch v := v.getIface().(type) { case Message: return "message" case List: return "list" case Map: return "map" default: return fmt.Sprintf("<unknown: %T>", v) } } } func (v Value) panicMessage(what string) string { return fmt.Sprintf("type mismatch: cannot convert %v to %s", v.typeName(), what) } // Bool returns v as a bool and panics if the type is not a bool. func (v Value) Bool() bool { switch v.typ { case boolType: return v.num > 0 default: panic(v.panicMessage("bool")) } } // Int returns v as a int64 and panics if the type is not a int32 or int64. func (v Value) Int() int64 { switch v.typ { case int32Type, int64Type: return int64(v.num) default: panic(v.panicMessage("int")) } } // Uint returns v as a uint64 and panics if the type is not a uint32 or uint64. func (v Value) Uint() uint64 { switch v.typ { case uint32Type, uint64Type: return uint64(v.num) default: panic(v.panicMessage("uint")) } } // Float returns v as a float64 and panics if the type is not a float32 or float64. func (v Value) Float() float64 { switch v.typ { case float32Type, float64Type: return math.Float64frombits(uint64(v.num)) default: panic(v.panicMessage("float")) } } // String returns v as a string. Since this method implements [fmt.Stringer], // this returns the formatted string value for any non-string type. func (v Value) String() string { switch v.typ { case stringType: return v.getString() default: return fmt.Sprint(v.Interface()) } } // Bytes returns v as a []byte and panics if the type is not a []byte. func (v Value) Bytes() []byte { switch v.typ { case bytesType: return v.getBytes() default: panic(v.panicMessage("bytes")) } } // Enum returns v as a [EnumNumber] and panics if the type is not a [EnumNumber]. func (v Value) Enum() EnumNumber { switch v.typ { case enumType: return EnumNumber(v.num) default: panic(v.panicMessage("enum")) } } // Message returns v as a [Message] and panics if the type is not a [Message]. func (v Value) Message() Message { switch vi := v.getIface().(type) { case Message: return vi default: panic(v.panicMessage("message")) } } // List returns v as a [List] and panics if the type is not a [List]. func (v Value) List() List { switch vi := v.getIface().(type) { case List: return vi default: panic(v.panicMessage("list")) } } // Map returns v as a [Map] and panics if the type is not a [Map]. func (v Value) Map() Map { switch vi := v.getIface().(type) { case Map: return vi default: panic(v.panicMessage("map")) } } // MapKey returns v as a [MapKey] and panics for invalid [MapKey] types. func (v Value) MapKey() MapKey { switch v.typ { case boolType, int32Type, int64Type, uint32Type, uint64Type, stringType: return MapKey(v) default: panic(v.panicMessage("map key")) } } // MapKey is used to index maps, where the Go type of the MapKey must match // the specified key [Kind] (see [MessageDescriptor.IsMapEntry]). // The following shows what Go type is used to represent each proto [Kind]: // // ╔═════════╤═════════════════════════════════════╗ // ║ Go type │ Protobuf kind ║ // ╠═════════╪═════════════════════════════════════╣ // ║ bool │ BoolKind ║ // ║ int32 │ Int32Kind, Sint32Kind, Sfixed32Kind ║ // ║ int64 │ Int64Kind, Sint64Kind, Sfixed64Kind ║ // ║ uint32 │ Uint32Kind, Fixed32Kind ║ // ║ uint64 │ Uint64Kind, Fixed64Kind ║ // ║ string │ StringKind ║ // ╚═════════╧═════════════════════════════════════╝ // // A MapKey is constructed and accessed through a [Value]: // // k := ValueOf("hash").MapKey() // convert string to MapKey // s := k.String() // convert MapKey to string // // The MapKey is a strict subset of valid types used in [Value]; // converting a [Value] to a MapKey with an invalid type panics. type MapKey value // IsValid reports whether k is populated with a value. func (k MapKey) IsValid() bool { return Value(k).IsValid() } // Interface returns k as an any. func (k MapKey) Interface() any { return Value(k).Interface() } // Bool returns k as a bool and panics if the type is not a bool. func (k MapKey) Bool() bool { return Value(k).Bool() } // Int returns k as a int64 and panics if the type is not a int32 or int64. func (k MapKey) Int() int64 { return Value(k).Int() } // Uint returns k as a uint64 and panics if the type is not a uint32 or uint64. func (k MapKey) Uint() uint64 { return Value(k).Uint() } // String returns k as a string. Since this method implements [fmt.Stringer], // this returns the formatted string value for any non-string type. func (k MapKey) String() string { return Value(k).String() } // Value returns k as a [Value]. func (k MapKey) Value() Value { return Value(k) }
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/reflect/protoreflect/proto.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/proto.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 protoreflect provides interfaces to dynamically manipulate messages. // // This package includes type descriptors which describe the structure of types // defined in proto source files and value interfaces which provide the // ability to examine and manipulate the contents of messages. // // # Protocol Buffer Descriptors // // Protobuf descriptors (e.g., [EnumDescriptor] or [MessageDescriptor]) // are immutable objects that represent protobuf type information. // They are wrappers around the messages declared in descriptor.proto. // Protobuf descriptors alone lack any information regarding Go types. // // Enums and messages generated by this module implement [Enum] and [ProtoMessage], // where the Descriptor and ProtoReflect.Descriptor accessors respectively // return the protobuf descriptor for the values. // // The protobuf descriptor interfaces are not meant to be implemented by // user code since they might need to be extended in the future to support // additions to the protobuf language. // The [google.golang.org/protobuf/reflect/protodesc] package converts between // google.protobuf.DescriptorProto messages and protobuf descriptors. // // # Go Type Descriptors // // A type descriptor (e.g., [EnumType] or [MessageType]) is a constructor for // a concrete Go type that represents the associated protobuf descriptor. // There is commonly a one-to-one relationship between protobuf descriptors and // Go type descriptors, but it can potentially be a one-to-many relationship. // // Enums and messages generated by this module implement [Enum] and [ProtoMessage], // where the Type and ProtoReflect.Type accessors respectively // return the protobuf descriptor for the values. // // The [google.golang.org/protobuf/types/dynamicpb] package can be used to // create Go type descriptors from protobuf descriptors. // // # Value Interfaces // // The [Enum] and [Message] interfaces provide a reflective view over an // enum or message instance. For enums, it provides the ability to retrieve // the enum value number for any concrete enum type. For messages, it provides // the ability to access or manipulate fields of the message. // // To convert a [google.golang.org/protobuf/proto.Message] to a [protoreflect.Message], use the // former's ProtoReflect method. Since the ProtoReflect method is new to the // v2 message interface, it may not be present on older message implementations. // The [github.com/golang/protobuf/proto.MessageReflect] function can be used // to obtain a reflective view on older messages. // // # Relationships // // The following diagrams demonstrate the relationships between // various types declared in this package. // // ┌───────────────────────────────────┐ // V │ // ┌────────────── New(n) ─────────────┐ │ // │ │ │ // │ ┌──── Descriptor() ──┐ │ ┌── Number() ──┐ │ // │ │ V V │ V │ // ╔════════════╗ ╔════════════════╗ ╔════════╗ ╔════════════╗ // ║ EnumType ║ ║ EnumDescriptor ║ ║ Enum ║ ║ EnumNumber ║ // ╚════════════╝ ╚════════════════╝ ╚════════╝ ╚════════════╝ // Λ Λ │ │ // │ └─── Descriptor() ──┘ │ // │ │ // └────────────────── Type() ───────┘ // // • An [EnumType] describes a concrete Go enum type. // It has an EnumDescriptor and can construct an Enum instance. // // • An [EnumDescriptor] describes an abstract protobuf enum type. // // • An [Enum] is a concrete enum instance. Generated enums implement Enum. // // ┌──────────────── New() ─────────────────┐ // │ │ // │ ┌─── Descriptor() ─────┐ │ ┌── Interface() ───┐ // │ │ V V │ V // ╔═════════════╗ ╔═══════════════════╗ ╔═════════╗ ╔══════════════╗ // ║ MessageType ║ ║ MessageDescriptor ║ ║ Message ║ ║ ProtoMessage ║ // ╚═════════════╝ ╚═══════════════════╝ ╚═════════╝ ╚══════════════╝ // Λ Λ │ │ Λ │ // │ └──── Descriptor() ────┘ │ └─ ProtoReflect() ─┘ // │ │ // └─────────────────── Type() ─────────┘ // // • A [MessageType] describes a concrete Go message type. // It has a [MessageDescriptor] and can construct a [Message] instance. // Just as how Go's [reflect.Type] is a reflective description of a Go type, // a [MessageType] is a reflective description of a Go type for a protobuf message. // // • A [MessageDescriptor] describes an abstract protobuf message type. // It has no understanding of Go types. In order to construct a [MessageType] // from just a [MessageDescriptor], you can consider looking up the message type // in the global registry using the FindMessageByName method on // [google.golang.org/protobuf/reflect/protoregistry.GlobalTypes] // or constructing a dynamic [MessageType] using // [google.golang.org/protobuf/types/dynamicpb.NewMessageType]. // // • A [Message] is a reflective view over a concrete message instance. // Generated messages implement [ProtoMessage], which can convert to a [Message]. // Just as how Go's [reflect.Value] is a reflective view over a Go value, // a [Message] is a reflective view over a concrete protobuf message instance. // Using Go reflection as an analogy, the [ProtoMessage.ProtoReflect] method is similar to // calling [reflect.ValueOf], and the [Message.Interface] method is similar to // calling [reflect.Value.Interface]. // // ┌── TypeDescriptor() ──┐ ┌───── Descriptor() ─────┐ // │ V │ V // ╔═══════════════╗ ╔═════════════════════════╗ ╔═════════════════════╗ // ║ ExtensionType ║ ║ ExtensionTypeDescriptor ║ ║ ExtensionDescriptor ║ // ╚═══════════════╝ ╚═════════════════════════╝ ╚═════════════════════╝ // Λ │ │ Λ │ Λ // └─────── Type() ───────┘ │ └─── may implement ────┘ │ // │ │ // └────── implements ────────┘ // // • An [ExtensionType] describes a concrete Go implementation of an extension. // It has an [ExtensionTypeDescriptor] and can convert to/from // an abstract [Value] and a Go value. // // • An [ExtensionTypeDescriptor] is an [ExtensionDescriptor] // which also has an [ExtensionType]. // // • An [ExtensionDescriptor] describes an abstract protobuf extension field and // may not always be an [ExtensionTypeDescriptor]. package protoreflect import ( "fmt" "strings" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/pragma" ) type doNotImplement pragma.DoNotImplement // ProtoMessage is the top-level interface that all proto messages implement. // This is declared in the protoreflect package to avoid a cyclic dependency; // use the [google.golang.org/protobuf/proto.Message] type instead, which aliases this type. type ProtoMessage interface{ ProtoReflect() Message } // Syntax is the language version of the proto file. type Syntax syntax type syntax int8 // keep exact type opaque as the int type may change const ( Proto2 Syntax = 2 Proto3 Syntax = 3 Editions Syntax = 4 ) // IsValid reports whether the syntax is valid. func (s Syntax) IsValid() bool { switch s { case Proto2, Proto3, Editions: return true default: return false } } // String returns s as a proto source identifier (e.g., "proto2"). func (s Syntax) String() string { switch s { case Proto2: return "proto2" case Proto3: return "proto3" case Editions: return "editions" default: return fmt.Sprintf("<unknown:%d>", s) } } // GoString returns s as a Go source identifier (e.g., "Proto2"). func (s Syntax) GoString() string { switch s { case Proto2: return "Proto2" case Proto3: return "Proto3" default: return fmt.Sprintf("Syntax(%d)", s) } } // Cardinality determines whether a field is optional, required, or repeated. type Cardinality cardinality type cardinality int8 // keep exact type opaque as the int type may change // Constants as defined by the google.protobuf.Cardinality enumeration. const ( Optional Cardinality = 1 // appears zero or one times Required Cardinality = 2 // appears exactly one time; invalid with Proto3 Repeated Cardinality = 3 // appears zero or more times ) // IsValid reports whether the cardinality is valid. func (c Cardinality) IsValid() bool { switch c { case Optional, Required, Repeated: return true default: return false } } // String returns c as a proto source identifier (e.g., "optional"). func (c Cardinality) String() string { switch c { case Optional: return "optional" case Required: return "required" case Repeated: return "repeated" default: return fmt.Sprintf("<unknown:%d>", c) } } // GoString returns c as a Go source identifier (e.g., "Optional"). func (c Cardinality) GoString() string { switch c { case Optional: return "Optional" case Required: return "Required" case Repeated: return "Repeated" default: return fmt.Sprintf("Cardinality(%d)", c) } } // Kind indicates the basic proto kind of a field. type Kind kind type kind int8 // keep exact type opaque as the int type may change // Constants as defined by the google.protobuf.Field.Kind enumeration. const ( BoolKind Kind = 8 EnumKind Kind = 14 Int32Kind Kind = 5 Sint32Kind Kind = 17 Uint32Kind Kind = 13 Int64Kind Kind = 3 Sint64Kind Kind = 18 Uint64Kind Kind = 4 Sfixed32Kind Kind = 15 Fixed32Kind Kind = 7 FloatKind Kind = 2 Sfixed64Kind Kind = 16 Fixed64Kind Kind = 6 DoubleKind Kind = 1 StringKind Kind = 9 BytesKind Kind = 12 MessageKind Kind = 11 GroupKind Kind = 10 ) // IsValid reports whether the kind is valid. func (k Kind) IsValid() bool { switch k { case BoolKind, EnumKind, Int32Kind, Sint32Kind, Uint32Kind, Int64Kind, Sint64Kind, Uint64Kind, Sfixed32Kind, Fixed32Kind, FloatKind, Sfixed64Kind, Fixed64Kind, DoubleKind, StringKind, BytesKind, MessageKind, GroupKind: return true default: return false } } // String returns k as a proto source identifier (e.g., "bool"). func (k Kind) String() string { switch k { case BoolKind: return "bool" case EnumKind: return "enum" case Int32Kind: return "int32" case Sint32Kind: return "sint32" case Uint32Kind: return "uint32" case Int64Kind: return "int64" case Sint64Kind: return "sint64" case Uint64Kind: return "uint64" case Sfixed32Kind: return "sfixed32" case Fixed32Kind: return "fixed32" case FloatKind: return "float" case Sfixed64Kind: return "sfixed64" case Fixed64Kind: return "fixed64" case DoubleKind: return "double" case StringKind: return "string" case BytesKind: return "bytes" case MessageKind: return "message" case GroupKind: return "group" default: return fmt.Sprintf("<unknown:%d>", k) } } // GoString returns k as a Go source identifier (e.g., "BoolKind"). func (k Kind) GoString() string { switch k { case BoolKind: return "BoolKind" case EnumKind: return "EnumKind" case Int32Kind: return "Int32Kind" case Sint32Kind: return "Sint32Kind" case Uint32Kind: return "Uint32Kind" case Int64Kind: return "Int64Kind" case Sint64Kind: return "Sint64Kind" case Uint64Kind: return "Uint64Kind" case Sfixed32Kind: return "Sfixed32Kind" case Fixed32Kind: return "Fixed32Kind" case FloatKind: return "FloatKind" case Sfixed64Kind: return "Sfixed64Kind" case Fixed64Kind: return "Fixed64Kind" case DoubleKind: return "DoubleKind" case StringKind: return "StringKind" case BytesKind: return "BytesKind" case MessageKind: return "MessageKind" case GroupKind: return "GroupKind" default: return fmt.Sprintf("Kind(%d)", k) } } // FieldNumber is the field number in a message. type FieldNumber = protowire.Number // FieldNumbers represent a list of field numbers. type FieldNumbers interface { // Len reports the number of fields in the list. Len() int // Get returns the ith field number. It panics if out of bounds. Get(i int) FieldNumber // Has reports whether n is within the list of fields. Has(n FieldNumber) bool doNotImplement } // FieldRanges represent a list of field number ranges. type FieldRanges interface { // Len reports the number of ranges in the list. Len() int // Get returns the ith range. It panics if out of bounds. Get(i int) [2]FieldNumber // start inclusive; end exclusive // Has reports whether n is within any of the ranges. Has(n FieldNumber) bool doNotImplement } // EnumNumber is the numeric value for an enum. type EnumNumber int32 // EnumRanges represent a list of enum number ranges. type EnumRanges interface { // Len reports the number of ranges in the list. Len() int // Get returns the ith range. It panics if out of bounds. Get(i int) [2]EnumNumber // start inclusive; end inclusive // Has reports whether n is within any of the ranges. Has(n EnumNumber) bool doNotImplement } // Name is the short name for a proto declaration. This is not the name // as used in Go source code, which might not be identical to the proto name. type Name string // e.g., "Kind" // IsValid reports whether s is a syntactically valid name. // An empty name is invalid. func (s Name) IsValid() bool { return consumeIdent(string(s)) == len(s) } // Names represent a list of names. type Names interface { // Len reports the number of names in the list. Len() int // Get returns the ith name. It panics if out of bounds. Get(i int) Name // Has reports whether s matches any names in the list. Has(s Name) bool doNotImplement } // FullName is a qualified name that uniquely identifies a proto declaration. // A qualified name is the concatenation of the proto package along with the // fully-declared name (i.e., name of parent preceding the name of the child), // with a '.' delimiter placed between each [Name]. // // This should not have any leading or trailing dots. type FullName string // e.g., "google.protobuf.Field.Kind" // IsValid reports whether s is a syntactically valid full name. // An empty full name is invalid. func (s FullName) IsValid() bool { i := consumeIdent(string(s)) if i < 0 { return false } for len(s) > i { if s[i] != '.' { return false } i++ n := consumeIdent(string(s[i:])) if n < 0 { return false } i += n } return true } func consumeIdent(s string) (i int) { if len(s) == 0 || !isLetter(s[i]) { return -1 } i++ for len(s) > i && isLetterDigit(s[i]) { i++ } return i } func isLetter(c byte) bool { return c == '_' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') } func isLetterDigit(c byte) bool { return isLetter(c) || ('0' <= c && c <= '9') } // Name returns the short name, which is the last identifier segment. // A single segment FullName is the [Name] itself. func (n FullName) Name() Name { if i := strings.LastIndexByte(string(n), '.'); i >= 0 { return Name(n[i+1:]) } return Name(n) } // Parent returns the full name with the trailing identifier removed. // A single segment FullName has no parent. func (n FullName) Parent() FullName { if i := strings.LastIndexByte(string(n), '.'); i >= 0 { return n[:i] } return "" } // Append returns the qualified name appended with the provided short name. // // Invariant: n == n.Parent().Append(n.Name()) // assuming n is valid func (n FullName) Append(s Name) FullName { if n == "" { return FullName(s) } return n + "." + FullName(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/protobuf/reflect/protoreflect/source.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/source.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 protoreflect import ( "strconv" ) // SourceLocations is a list of source locations. type SourceLocations interface { // Len reports the number of source locations in the proto file. Len() int // Get returns the ith SourceLocation. It panics if out of bounds. Get(int) SourceLocation // ByPath returns the SourceLocation for the given path, // returning the first location if multiple exist for the same path. // If multiple locations exist for the same path, // then SourceLocation.Next index can be used to identify the // index of the next SourceLocation. // If no location exists for this path, it returns the zero value. ByPath(path SourcePath) SourceLocation // ByDescriptor returns the SourceLocation for the given descriptor, // returning the first location if multiple exist for the same path. // If no location exists for this descriptor, it returns the zero value. ByDescriptor(desc Descriptor) SourceLocation doNotImplement } // SourceLocation describes a source location and // corresponds with the google.protobuf.SourceCodeInfo.Location message. type SourceLocation struct { // Path is the path to the declaration from the root file descriptor. // The contents of this slice must not be mutated. Path SourcePath // StartLine and StartColumn are the zero-indexed starting location // in the source file for the declaration. StartLine, StartColumn int // EndLine and EndColumn are the zero-indexed ending location // in the source file for the declaration. // In the descriptor.proto, the end line may be omitted if it is identical // to the start line. Here, it is always populated. EndLine, EndColumn int // LeadingDetachedComments are the leading detached comments // for the declaration. The contents of this slice must not be mutated. LeadingDetachedComments []string // LeadingComments is the leading attached comment for the declaration. LeadingComments string // TrailingComments is the trailing attached comment for the declaration. TrailingComments string // Next is an index into SourceLocations for the next source location that // has the same Path. It is zero if there is no next location. Next int } // SourcePath identifies part of a file descriptor for a source location. // The SourcePath is a sequence of either field numbers or indexes into // a repeated field that form a path starting from the root file descriptor. // // See google.protobuf.SourceCodeInfo.Location.path. type SourcePath []int32 // Equal reports whether p1 equals p2. func (p1 SourcePath) Equal(p2 SourcePath) bool { if len(p1) != len(p2) { return false } for i := range p1 { if p1[i] != p2[i] { return false } } return true } // String formats the path in a humanly readable manner. // The output is guaranteed to be deterministic, // making it suitable for use as a key into a Go map. // It is not guaranteed to be stable as the exact output could change // in a future version of this module. // // Example output: // // .message_type[6].nested_type[15].field[3] func (p SourcePath) String() string { b := p.appendFileDescriptorProto(nil) for _, i := range p { b = append(b, '.') b = strconv.AppendInt(b, int64(i), 10) } return string(b) } type appendFunc func(*SourcePath, []byte) []byte func (p *SourcePath) appendSingularField(b []byte, name string, f appendFunc) []byte { if len(*p) == 0 { return b } b = append(b, '.') b = append(b, name...) *p = (*p)[1:] if f != nil { b = f(p, b) } return b } func (p *SourcePath) appendRepeatedField(b []byte, name string, f appendFunc) []byte { b = p.appendSingularField(b, name, nil) if len(*p) == 0 || (*p)[0] < 0 { return b } b = append(b, '[') b = strconv.AppendUint(b, uint64((*p)[0]), 10) b = append(b, ']') *p = (*p)[1:] if f != nil { b = f(p, b) } return b }
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/reflect/protoreflect/value_unsafe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/value_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 protoreflect import ( "unsafe" "google.golang.org/protobuf/internal/pragma" ) type ( ifaceHeader struct { _ [0]any // if interfaces have greater alignment than unsafe.Pointer, this will enforce it. Type unsafe.Pointer Data unsafe.Pointer } ) var ( nilType = typeOf(nil) boolType = typeOf(*new(bool)) int32Type = typeOf(*new(int32)) int64Type = typeOf(*new(int64)) uint32Type = typeOf(*new(uint32)) uint64Type = typeOf(*new(uint64)) float32Type = typeOf(*new(float32)) float64Type = typeOf(*new(float64)) stringType = typeOf(*new(string)) bytesType = typeOf(*new([]byte)) enumType = typeOf(*new(EnumNumber)) ) // typeOf returns a pointer to the Go type information. // The pointer is comparable and equal if and only if the types are identical. func typeOf(t any) unsafe.Pointer { return (*ifaceHeader)(unsafe.Pointer(&t)).Type } // value is a union where only one type can be represented at a time. // The struct is 24B large on 64-bit systems and requires the minimum storage // necessary to represent each possible type. // // The Go GC needs to be able to scan variables containing pointers. // As such, pointers and non-pointers cannot be intermixed. type value struct { pragma.DoNotCompare // 0B // typ stores the type of the value as a pointer to the Go type. typ unsafe.Pointer // 8B // ptr stores the data pointer for a String, Bytes, or interface value. ptr unsafe.Pointer // 8B // num stores a Bool, Int32, Int64, Uint32, Uint64, Float32, Float64, or // Enum value as a raw uint64. // // It is also used to store the length of a String or Bytes value; // the capacity is ignored. num uint64 // 8B } func valueOfString(v string) Value { return Value{typ: stringType, ptr: unsafe.Pointer(unsafe.StringData(v)), num: uint64(len(v))} } func valueOfBytes(v []byte) Value { return Value{typ: bytesType, ptr: unsafe.Pointer(unsafe.SliceData(v)), num: uint64(len(v))} } func valueOfIface(v any) Value { p := (*ifaceHeader)(unsafe.Pointer(&v)) return Value{typ: p.Type, ptr: p.Data} } func (v Value) getString() string { return unsafe.String((*byte)(v.ptr), v.num) } func (v Value) getBytes() []byte { return unsafe.Slice((*byte)(v.ptr), v.num) } func (v Value) getIface() (x any) { *(*ifaceHeader)(unsafe.Pointer(&x)) = ifaceHeader{Type: v.typ, Data: v.ptr} return x }
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/reflect/protoreflect/type.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/type.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 protoreflect // Descriptor provides a set of accessors that are common to every descriptor. // Each descriptor type wraps the equivalent google.protobuf.XXXDescriptorProto, // but provides efficient lookup and immutability. // // Each descriptor is comparable. Equality implies that the two types are // exactly identical. However, it is possible for the same semantically // identical proto type to be represented by multiple type descriptors. // // For example, suppose we have t1 and t2 which are both an [MessageDescriptor]. // If t1 == t2, then the types are definitely equal and all accessors return // the same information. However, if t1 != t2, then it is still possible that // they still represent the same proto type (e.g., t1.FullName == t2.FullName). // This can occur if a descriptor type is created dynamically, or multiple // versions of the same proto type are accidentally linked into the Go binary. type Descriptor interface { // ParentFile returns the parent file descriptor that this descriptor // is declared within. The parent file for the file descriptor is itself. // // Support for this functionality is optional and may return nil. ParentFile() FileDescriptor // Parent returns the parent containing this descriptor declaration. // The following shows the mapping from child type to possible parent types: // // ╔═════════════════════╤═══════════════════════════════════╗ // ║ Child type │ Possible parent types ║ // ╠═════════════════════╪═══════════════════════════════════╣ // ║ FileDescriptor │ nil ║ // ║ MessageDescriptor │ FileDescriptor, MessageDescriptor ║ // ║ FieldDescriptor │ FileDescriptor, MessageDescriptor ║ // ║ OneofDescriptor │ MessageDescriptor ║ // ║ EnumDescriptor │ FileDescriptor, MessageDescriptor ║ // ║ EnumValueDescriptor │ EnumDescriptor ║ // ║ ServiceDescriptor │ FileDescriptor ║ // ║ MethodDescriptor │ ServiceDescriptor ║ // ╚═════════════════════╧═══════════════════════════════════╝ // // Support for this functionality is optional and may return nil. Parent() Descriptor // Index returns the index of this descriptor within its parent. // It returns 0 if the descriptor does not have a parent or if the parent // is unknown. Index() int // Syntax is the protobuf syntax. Syntax() Syntax // e.g., Proto2 or Proto3 // Name is the short name of the declaration (i.e., FullName.Name). Name() Name // e.g., "Any" // FullName is the fully-qualified name of the declaration. // // The FullName is a concatenation of the full name of the type that this // type is declared within and the declaration name. For example, // field "foo_field" in message "proto.package.MyMessage" is // uniquely identified as "proto.package.MyMessage.foo_field". // Enum values are an exception to the rule (see EnumValueDescriptor). FullName() FullName // e.g., "google.protobuf.Any" // IsPlaceholder reports whether type information is missing since a // dependency is not resolved, in which case only name information is known. // // Placeholder types may only be returned by the following accessors // as a result of unresolved dependencies: // // ╔═══════════════════════════════════╤═════════════════════╗ // ║ Accessor │ Descriptor ║ // ╠═══════════════════════════════════╪═════════════════════╣ // ║ FileImports.FileDescriptor │ FileDescriptor ║ // ║ FieldDescriptor.Enum │ EnumDescriptor ║ // ║ FieldDescriptor.Message │ MessageDescriptor ║ // ║ FieldDescriptor.DefaultEnumValue │ EnumValueDescriptor ║ // ║ FieldDescriptor.ContainingMessage │ MessageDescriptor ║ // ║ MethodDescriptor.Input │ MessageDescriptor ║ // ║ MethodDescriptor.Output │ MessageDescriptor ║ // ╚═══════════════════════════════════╧═════════════════════╝ // // If true, only Name and FullName are valid. // For FileDescriptor, the Path is also valid. IsPlaceholder() bool // Options returns the descriptor options. The caller must not modify // the returned value. // // To avoid a dependency cycle, this function returns a proto.Message value. // The proto message type returned for each descriptor type is as follows: // ╔═════════════════════╤══════════════════════════════════════════╗ // ║ Go type │ Protobuf message type ║ // ╠═════════════════════╪══════════════════════════════════════════╣ // ║ FileDescriptor │ google.protobuf.FileOptions ║ // ║ EnumDescriptor │ google.protobuf.EnumOptions ║ // ║ EnumValueDescriptor │ google.protobuf.EnumValueOptions ║ // ║ MessageDescriptor │ google.protobuf.MessageOptions ║ // ║ FieldDescriptor │ google.protobuf.FieldOptions ║ // ║ OneofDescriptor │ google.protobuf.OneofOptions ║ // ║ ServiceDescriptor │ google.protobuf.ServiceOptions ║ // ║ MethodDescriptor │ google.protobuf.MethodOptions ║ // ╚═════════════════════╧══════════════════════════════════════════╝ // // This method returns a typed nil-pointer if no options are present. // The caller must import the descriptorpb package to use this. Options() ProtoMessage doNotImplement } // FileDescriptor describes the types in a complete proto file and // corresponds with the google.protobuf.FileDescriptorProto message. // // Top-level declarations: // [EnumDescriptor], [MessageDescriptor], [FieldDescriptor], and/or [ServiceDescriptor]. type FileDescriptor interface { Descriptor // Descriptor.FullName is identical to Package // Path returns the file name, relative to the source tree root. Path() string // e.g., "path/to/file.proto" // Package returns the protobuf package namespace. Package() FullName // e.g., "google.protobuf" // Imports is a list of imported proto files. Imports() FileImports // Enums is a list of the top-level enum declarations. Enums() EnumDescriptors // Messages is a list of the top-level message declarations. Messages() MessageDescriptors // Extensions is a list of the top-level extension declarations. Extensions() ExtensionDescriptors // Services is a list of the top-level service declarations. Services() ServiceDescriptors // SourceLocations is a list of source locations. SourceLocations() SourceLocations isFileDescriptor } type isFileDescriptor interface{ ProtoType(FileDescriptor) } // FileImports is a list of file imports. type FileImports interface { // Len reports the number of files imported by this proto file. Len() int // Get returns the ith FileImport. It panics if out of bounds. Get(i int) FileImport doNotImplement } // FileImport is the declaration for a proto file import. type FileImport struct { // FileDescriptor is the file type for the given import. // It is a placeholder descriptor if IsWeak is set or if a dependency has // not been regenerated to implement the new reflection APIs. FileDescriptor // IsPublic reports whether this is a public import, which causes this file // to alias declarations within the imported file. The intended use cases // for this feature is the ability to move proto files without breaking // existing dependencies. // // The current file and the imported file must be within proto package. IsPublic bool // Deprecated: support for weak fields has been removed. IsWeak bool } // MessageDescriptor describes a message and // corresponds with the google.protobuf.DescriptorProto message. // // Nested declarations: // [FieldDescriptor], [OneofDescriptor], [FieldDescriptor], [EnumDescriptor], // and/or [MessageDescriptor]. type MessageDescriptor interface { Descriptor // IsMapEntry indicates that this is an auto-generated message type to // represent the entry type for a map field. // // Map entry messages have only two fields: // • a "key" field with a field number of 1 // • a "value" field with a field number of 2 // The key and value types are determined by these two fields. // // If IsMapEntry is true, it implies that FieldDescriptor.IsMap is true // for some field with this message type. IsMapEntry() bool // Fields is a list of nested field declarations. Fields() FieldDescriptors // Oneofs is a list of nested oneof declarations. Oneofs() OneofDescriptors // ReservedNames is a list of reserved field names. ReservedNames() Names // ReservedRanges is a list of reserved ranges of field numbers. ReservedRanges() FieldRanges // RequiredNumbers is a list of required field numbers. // In Proto3, it is always an empty list. RequiredNumbers() FieldNumbers // ExtensionRanges is the field ranges used for extension fields. // In Proto3, it is always an empty ranges. ExtensionRanges() FieldRanges // ExtensionRangeOptions returns the ith extension range options. // // To avoid a dependency cycle, this method returns a proto.Message] value, // which always contains a google.protobuf.ExtensionRangeOptions message. // This method returns a typed nil-pointer if no options are present. // The caller must import the descriptorpb package to use this. ExtensionRangeOptions(i int) ProtoMessage // Enums is a list of nested enum declarations. Enums() EnumDescriptors // Messages is a list of nested message declarations. Messages() MessageDescriptors // Extensions is a list of nested extension declarations. Extensions() ExtensionDescriptors isMessageDescriptor } type isMessageDescriptor interface{ ProtoType(MessageDescriptor) } // MessageType encapsulates a [MessageDescriptor] with a concrete Go implementation. // It is recommended that implementations of this interface also implement the // [MessageFieldTypes] interface. type MessageType interface { // New returns a newly allocated empty message. // It may return nil for synthetic messages representing a map entry. New() Message // Zero returns an empty, read-only message. // It may return nil for synthetic messages representing a map entry. Zero() Message // Descriptor returns the message descriptor. // // Invariant: t.Descriptor() == t.New().Descriptor() Descriptor() MessageDescriptor } // MessageFieldTypes extends a [MessageType] by providing type information // regarding enums and messages referenced by the message fields. type MessageFieldTypes interface { MessageType // Enum returns the EnumType for the ith field in MessageDescriptor.Fields. // It returns nil if the ith field is not an enum kind. // It panics if out of bounds. // // Invariant: mt.Enum(i).Descriptor() == mt.Descriptor().Fields(i).Enum() Enum(i int) EnumType // Message returns the MessageType for the ith field in MessageDescriptor.Fields. // It returns nil if the ith field is not a message or group kind. // It panics if out of bounds. // // Invariant: mt.Message(i).Descriptor() == mt.Descriptor().Fields(i).Message() Message(i int) MessageType } // MessageDescriptors is a list of message declarations. type MessageDescriptors interface { // Len reports the number of messages. Len() int // Get returns the ith MessageDescriptor. It panics if out of bounds. Get(i int) MessageDescriptor // ByName returns the MessageDescriptor for a message named s. // It returns nil if not found. ByName(s Name) MessageDescriptor doNotImplement } // FieldDescriptor describes a field within a message and // corresponds with the google.protobuf.FieldDescriptorProto message. // // It is used for both normal fields defined within the parent message // (e.g., [MessageDescriptor.Fields]) and fields that extend some remote message // (e.g., [FileDescriptor.Extensions] or [MessageDescriptor.Extensions]). type FieldDescriptor interface { Descriptor // Number reports the unique number for this field. Number() FieldNumber // Cardinality reports the cardinality for this field. Cardinality() Cardinality // Kind reports the basic kind for this field. Kind() Kind // HasJSONName reports whether this field has an explicitly set JSON name. HasJSONName() bool // JSONName reports the name used for JSON serialization. // It is usually the camel-cased form of the field name. // Extension fields are represented by the full name surrounded by brackets. JSONName() string // TextName reports the name used for text serialization. // It is usually the name of the field, except that groups use the name // of the inlined message, and extension fields are represented by the // full name surrounded by brackets. TextName() string // HasPresence reports whether the field distinguishes between unpopulated // and default values. HasPresence() bool // IsExtension reports whether this is an extension field. If false, // then Parent and ContainingMessage refer to the same message. // Otherwise, ContainingMessage and Parent likely differ. IsExtension() bool // HasOptionalKeyword reports whether the "optional" keyword was explicitly // specified in the source .proto file. HasOptionalKeyword() bool // Deprecated: support for weak fields has been removed. IsWeak() bool // IsPacked reports whether repeated primitive numeric kinds should be // serialized using a packed encoding. // If true, then it implies Cardinality is Repeated. IsPacked() bool // IsList reports whether this field represents a list, // where the value type for the associated field is a List. // It is equivalent to checking whether Cardinality is Repeated and // that IsMap reports false. IsList() bool // IsMap reports whether this field represents a map, // where the value type for the associated field is a Map. // It is equivalent to checking whether Cardinality is Repeated, // that the Kind is MessageKind, and that MessageDescriptor.IsMapEntry reports true. IsMap() bool // MapKey returns the field descriptor for the key in the map entry. // It returns nil if IsMap reports false. MapKey() FieldDescriptor // MapValue returns the field descriptor for the value in the map entry. // It returns nil if IsMap reports false. MapValue() FieldDescriptor // HasDefault reports whether this field has a default value. HasDefault() bool // Default returns the default value for scalar fields. // For proto2, it is the default value as specified in the proto file, // or the zero value if unspecified. // For proto3, it is always the zero value of the scalar. // The Value type is determined by the Kind. Default() Value // DefaultEnumValue returns the enum value descriptor for the default value // of an enum field, and is nil for any other kind of field. DefaultEnumValue() EnumValueDescriptor // ContainingOneof is the containing oneof that this field belongs to, // and is nil if this field is not part of a oneof. ContainingOneof() OneofDescriptor // ContainingMessage is the containing message that this field belongs to. // For extension fields, this may not necessarily be the parent message // that the field is declared within. ContainingMessage() MessageDescriptor // Enum is the enum descriptor if Kind is EnumKind. // It returns nil for any other Kind. Enum() EnumDescriptor // Message is the message descriptor if Kind is // MessageKind or GroupKind. It returns nil for any other Kind. Message() MessageDescriptor isFieldDescriptor } type isFieldDescriptor interface{ ProtoType(FieldDescriptor) } // FieldDescriptors is a list of field declarations. type FieldDescriptors interface { // Len reports the number of fields. Len() int // Get returns the ith FieldDescriptor. It panics if out of bounds. Get(i int) FieldDescriptor // ByName returns the FieldDescriptor for a field named s. // It returns nil if not found. ByName(s Name) FieldDescriptor // ByJSONName returns the FieldDescriptor for a field with s as the JSON name. // It returns nil if not found. ByJSONName(s string) FieldDescriptor // ByTextName returns the FieldDescriptor for a field with s as the text name. // It returns nil if not found. ByTextName(s string) FieldDescriptor // ByNumber returns the FieldDescriptor for a field numbered n. // It returns nil if not found. ByNumber(n FieldNumber) FieldDescriptor doNotImplement } // OneofDescriptor describes a oneof field set within a given message and // corresponds with the google.protobuf.OneofDescriptorProto message. type OneofDescriptor interface { Descriptor // IsSynthetic reports whether this is a synthetic oneof created to support // proto3 optional semantics. If true, Fields contains exactly one field // with FieldDescriptor.HasOptionalKeyword specified. IsSynthetic() bool // Fields is a list of fields belonging to this oneof. Fields() FieldDescriptors isOneofDescriptor } type isOneofDescriptor interface{ ProtoType(OneofDescriptor) } // OneofDescriptors is a list of oneof declarations. type OneofDescriptors interface { // Len reports the number of oneof fields. Len() int // Get returns the ith OneofDescriptor. It panics if out of bounds. Get(i int) OneofDescriptor // ByName returns the OneofDescriptor for a oneof named s. // It returns nil if not found. ByName(s Name) OneofDescriptor doNotImplement } // ExtensionDescriptor is an alias of [FieldDescriptor] for documentation. type ExtensionDescriptor = FieldDescriptor // ExtensionTypeDescriptor is an [ExtensionDescriptor] with an associated [ExtensionType]. type ExtensionTypeDescriptor interface { ExtensionDescriptor // Type returns the associated ExtensionType. Type() ExtensionType // Descriptor returns the plain ExtensionDescriptor without the // associated ExtensionType. Descriptor() ExtensionDescriptor } // ExtensionDescriptors is a list of field declarations. type ExtensionDescriptors interface { // Len reports the number of fields. Len() int // Get returns the ith ExtensionDescriptor. It panics if out of bounds. Get(i int) ExtensionDescriptor // ByName returns the ExtensionDescriptor for a field named s. // It returns nil if not found. ByName(s Name) ExtensionDescriptor doNotImplement } // ExtensionType encapsulates an [ExtensionDescriptor] with a concrete // Go implementation. The nested field descriptor must be for a extension field. // // While a normal field is a member of the parent message that it is declared // within (see [Descriptor.Parent]), an extension field is a member of some other // target message (see [FieldDescriptor.ContainingMessage]) and may have no // relationship with the parent. However, the full name of an extension field is // relative to the parent that it is declared within. // // For example: // // syntax = "proto2"; // package example; // message FooMessage { // extensions 100 to max; // } // message BarMessage { // extends FooMessage { optional BarMessage bar_field = 100; } // } // // Field "bar_field" is an extension of FooMessage, but its full name is // "example.BarMessage.bar_field" instead of "example.FooMessage.bar_field". type ExtensionType interface { // New returns a new value for the field. // For scalars, this returns the default value in native Go form. New() Value // Zero returns a new value for the field. // For scalars, this returns the default value in native Go form. // For composite types, this returns an empty, read-only message, list, or map. Zero() Value // TypeDescriptor returns the extension type descriptor. TypeDescriptor() ExtensionTypeDescriptor // ValueOf wraps the input and returns it as a Value. // ValueOf panics if the input value is invalid or not the appropriate type. // // ValueOf is more extensive than protoreflect.ValueOf for a given field's // value as it has more type information available. ValueOf(any) Value // InterfaceOf completely unwraps the Value to the underlying Go type. // InterfaceOf panics if the input is nil or does not represent the // appropriate underlying Go type. For composite types, it panics if the // value is not mutable. // // InterfaceOf is able to unwrap the Value further than Value.Interface // as it has more type information available. InterfaceOf(Value) any // IsValidValue reports whether the Value is valid to assign to the field. IsValidValue(Value) bool // IsValidInterface reports whether the input is valid to assign to the field. IsValidInterface(any) bool } // EnumDescriptor describes an enum and // corresponds with the google.protobuf.EnumDescriptorProto message. // // Nested declarations: // [EnumValueDescriptor]. type EnumDescriptor interface { Descriptor // Values is a list of nested enum value declarations. Values() EnumValueDescriptors // ReservedNames is a list of reserved enum names. ReservedNames() Names // ReservedRanges is a list of reserved ranges of enum numbers. ReservedRanges() EnumRanges // IsClosed reports whether this enum uses closed semantics. // See https://protobuf.dev/programming-guides/enum/#definitions. // Note: the Go protobuf implementation is not spec compliant and treats // all enums as open enums. IsClosed() bool isEnumDescriptor } type isEnumDescriptor interface{ ProtoType(EnumDescriptor) } // EnumType encapsulates an [EnumDescriptor] with a concrete Go implementation. type EnumType interface { // New returns an instance of this enum type with its value set to n. New(n EnumNumber) Enum // Descriptor returns the enum descriptor. // // Invariant: t.Descriptor() == t.New(0).Descriptor() Descriptor() EnumDescriptor } // EnumDescriptors is a list of enum declarations. type EnumDescriptors interface { // Len reports the number of enum types. Len() int // Get returns the ith EnumDescriptor. It panics if out of bounds. Get(i int) EnumDescriptor // ByName returns the EnumDescriptor for an enum named s. // It returns nil if not found. ByName(s Name) EnumDescriptor doNotImplement } // EnumValueDescriptor describes an enum value and // corresponds with the google.protobuf.EnumValueDescriptorProto message. // // All other proto declarations are in the namespace of the parent. // However, enum values do not follow this rule and are within the namespace // of the parent's parent (i.e., they are a sibling of the containing enum). // Thus, a value named "FOO_VALUE" declared within an enum uniquely identified // as "proto.package.MyEnum" has a full name of "proto.package.FOO_VALUE". type EnumValueDescriptor interface { Descriptor // Number returns the enum value as an integer. Number() EnumNumber isEnumValueDescriptor } type isEnumValueDescriptor interface{ ProtoType(EnumValueDescriptor) } // EnumValueDescriptors is a list of enum value declarations. type EnumValueDescriptors interface { // Len reports the number of enum values. Len() int // Get returns the ith EnumValueDescriptor. It panics if out of bounds. Get(i int) EnumValueDescriptor // ByName returns the EnumValueDescriptor for the enum value named s. // It returns nil if not found. ByName(s Name) EnumValueDescriptor // ByNumber returns the EnumValueDescriptor for the enum value numbered n. // If multiple have the same number, the first one defined is returned // It returns nil if not found. ByNumber(n EnumNumber) EnumValueDescriptor doNotImplement } // ServiceDescriptor describes a service and // corresponds with the google.protobuf.ServiceDescriptorProto message. // // Nested declarations: [MethodDescriptor]. type ServiceDescriptor interface { Descriptor // Methods is a list of nested message declarations. Methods() MethodDescriptors isServiceDescriptor } type isServiceDescriptor interface{ ProtoType(ServiceDescriptor) } // ServiceDescriptors is a list of service declarations. type ServiceDescriptors interface { // Len reports the number of services. Len() int // Get returns the ith ServiceDescriptor. It panics if out of bounds. Get(i int) ServiceDescriptor // ByName returns the ServiceDescriptor for a service named s. // It returns nil if not found. ByName(s Name) ServiceDescriptor doNotImplement } // MethodDescriptor describes a method and // corresponds with the google.protobuf.MethodDescriptorProto message. type MethodDescriptor interface { Descriptor // Input is the input message descriptor. Input() MessageDescriptor // Output is the output message descriptor. Output() MessageDescriptor // IsStreamingClient reports whether the client streams multiple messages. IsStreamingClient() bool // IsStreamingServer reports whether the server streams multiple messages. IsStreamingServer() bool isMethodDescriptor } type isMethodDescriptor interface{ ProtoType(MethodDescriptor) } // MethodDescriptors is a list of method declarations. type MethodDescriptors interface { // Len reports the number of methods. Len() int // Get returns the ith MethodDescriptor. It panics if out of bounds. Get(i int) MethodDescriptor // ByName returns the MethodDescriptor for a service method named s. // It returns nil if not found. ByName(s Name) MethodDescriptor doNotImplement }
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/reflect/protoreflect/value.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/value.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 protoreflect import "google.golang.org/protobuf/encoding/protowire" // Enum is a reflection interface for a concrete enum value, // which provides type information and a getter for the enum number. // Enum does not provide a mutable API since enums are commonly backed by // Go constants, which are not addressable. type Enum interface { // Descriptor returns enum descriptor, which contains only the protobuf // type information for the enum. Descriptor() EnumDescriptor // Type returns the enum type, which encapsulates both Go and protobuf // type information. If the Go type information is not needed, // it is recommended that the enum descriptor be used instead. Type() EnumType // Number returns the enum value as an integer. Number() EnumNumber } // Message is a reflective interface for a concrete message value, // encapsulating both type and value information for the message. // // Accessor/mutators for individual fields are keyed by [FieldDescriptor]. // For non-extension fields, the descriptor must exactly match the // field known by the parent message. // For extension fields, the descriptor must implement [ExtensionTypeDescriptor], // extend the parent message (i.e., have the same message [FullName]), and // be within the parent's extension range. // // Each field [Value] can be a scalar or a composite type ([Message], [List], or [Map]). // See [Value] for the Go types associated with a [FieldDescriptor]. // Providing a [Value] that is invalid or of an incorrect type panics. type Message interface { // Descriptor returns message descriptor, which contains only the protobuf // type information for the message. Descriptor() MessageDescriptor // Type returns the message type, which encapsulates both Go and protobuf // type information. If the Go type information is not needed, // it is recommended that the message descriptor be used instead. Type() MessageType // New returns a newly allocated and mutable empty message. New() Message // Interface unwraps the message reflection interface and // returns the underlying ProtoMessage interface. Interface() ProtoMessage // Range iterates over every populated field in an undefined order, // calling f for each field descriptor and value encountered. // Range returns immediately if f returns false. // While iterating, mutating operations may only be performed // on the current field descriptor. Range(f func(FieldDescriptor, Value) bool) // Has reports whether a field is populated. // // Some fields have the property of nullability where it is possible to // distinguish between the default value of a field and whether the field // was explicitly populated with the default value. Singular message fields, // member fields of a oneof, and proto2 scalar fields are nullable. Such // fields are populated only if explicitly set. // // In other cases (aside from the nullable cases above), // a proto3 scalar field is populated if it contains a non-zero value, and // a repeated field is populated if it is non-empty. Has(FieldDescriptor) bool // Clear clears the field such that a subsequent Has call reports false. // // Clearing an extension field clears both the extension type and value // associated with the given field number. // // Clear is a mutating operation and unsafe for concurrent use. Clear(FieldDescriptor) // Get retrieves the value for a field. // // For unpopulated scalars, it returns the default value, where // the default value of a bytes scalar is guaranteed to be a copy. // For unpopulated composite types, it returns an empty, read-only view // of the value; to obtain a mutable reference, use Mutable. Get(FieldDescriptor) Value // Set stores the value for a field. // // For a field belonging to a oneof, it implicitly clears any other field // that may be currently set within the same oneof. // For extension fields, it implicitly stores the provided ExtensionType. // When setting a composite type, it is unspecified whether the stored value // aliases the source's memory in any way. If the composite value is an // empty, read-only value, then it panics. // // Set is a mutating operation and unsafe for concurrent use. Set(FieldDescriptor, Value) // Mutable returns a mutable reference to a composite type. // // If the field is unpopulated, it may allocate a composite value. // For a field belonging to a oneof, it implicitly clears any other field // that may be currently set within the same oneof. // For extension fields, it implicitly stores the provided ExtensionType // if not already stored. // It panics if the field does not contain a composite type. // // Mutable is a mutating operation and unsafe for concurrent use. Mutable(FieldDescriptor) Value // NewField returns a new value that is assignable to the field // for the given descriptor. For scalars, this returns the default value. // For lists, maps, and messages, this returns a new, empty, mutable value. NewField(FieldDescriptor) Value // WhichOneof reports which field within the oneof is populated, // returning nil if none are populated. // It panics if the oneof descriptor does not belong to this message. WhichOneof(OneofDescriptor) FieldDescriptor // GetUnknown retrieves the entire list of unknown fields. // The caller may only mutate the contents of the RawFields // if the mutated bytes are stored back into the message with SetUnknown. GetUnknown() RawFields // SetUnknown stores an entire list of unknown fields. // The raw fields must be syntactically valid according to the wire format. // An implementation may panic if this is not the case. // Once stored, the caller must not mutate the content of the RawFields. // An empty RawFields may be passed to clear the fields. // // SetUnknown is a mutating operation and unsafe for concurrent use. SetUnknown(RawFields) // IsValid reports whether the message is valid. // // An invalid message is an empty, read-only value. // // An invalid message often corresponds to a nil pointer of the concrete // message type, but the details are implementation dependent. // Validity is not part of the protobuf data model, and may not // be preserved in marshaling or other operations. IsValid() bool // ProtoMethods returns optional fast-path implementations of various operations. // This method may return nil. // // The returned methods type is identical to // [google.golang.org/protobuf/runtime/protoiface.Methods]. // Consult the protoiface package documentation for details. ProtoMethods() *methods } // RawFields is the raw bytes for an ordered sequence of fields. // Each field contains both the tag (representing field number and wire type), // and also the wire data itself. type RawFields []byte // IsValid reports whether b is syntactically correct wire format. func (b RawFields) IsValid() bool { for len(b) > 0 { _, _, n := protowire.ConsumeField(b) if n < 0 { return false } b = b[n:] } return true } // List is a zero-indexed, ordered list. // The element [Value] type is determined by [FieldDescriptor.Kind]. // Providing a [Value] that is invalid or of an incorrect type panics. type List interface { // Len reports the number of entries in the List. // Get, Set, and Truncate panic with out of bound indexes. Len() int // Get retrieves the value at the given index. // It never returns an invalid value. Get(int) Value // Set stores a value for the given index. // When setting a composite type, it is unspecified whether the set // value aliases the source's memory in any way. // // Set is a mutating operation and unsafe for concurrent use. Set(int, Value) // Append appends the provided value to the end of the list. // When appending a composite type, it is unspecified whether the appended // value aliases the source's memory in any way. // // Append is a mutating operation and unsafe for concurrent use. Append(Value) // AppendMutable appends a new, empty, mutable message value to the end // of the list and returns it. // It panics if the list does not contain a message type. AppendMutable() Value // Truncate truncates the list to a smaller length. // // Truncate is a mutating operation and unsafe for concurrent use. Truncate(int) // NewElement returns a new value for a list element. // For enums, this returns the first enum value. // For other scalars, this returns the zero value. // For messages, this returns a new, empty, mutable value. NewElement() Value // IsValid reports whether the list is valid. // // An invalid list is an empty, read-only value. // // Validity is not part of the protobuf data model, and may not // be preserved in marshaling or other operations. IsValid() bool } // Map is an unordered, associative map. // The entry [MapKey] type is determined by [FieldDescriptor.MapKey].Kind. // The entry [Value] type is determined by [FieldDescriptor.MapValue].Kind. // Providing a [MapKey] or [Value] that is invalid or of an incorrect type panics. type Map interface { // Len reports the number of elements in the map. Len() int // Range iterates over every map entry in an undefined order, // calling f for each key and value encountered. // Range calls f Len times unless f returns false, which stops iteration. // While iterating, mutating operations may only be performed // on the current map key. Range(f func(MapKey, Value) bool) // Has reports whether an entry with the given key is in the map. Has(MapKey) bool // Clear clears the entry associated with they given key. // The operation does nothing if there is no entry associated with the key. // // Clear is a mutating operation and unsafe for concurrent use. Clear(MapKey) // Get retrieves the value for an entry with the given key. // It returns an invalid value for non-existent entries. Get(MapKey) Value // Set stores the value for an entry with the given key. // It panics when given a key or value that is invalid or the wrong type. // When setting a composite type, it is unspecified whether the set // value aliases the source's memory in any way. // // Set is a mutating operation and unsafe for concurrent use. Set(MapKey, Value) // Mutable retrieves a mutable reference to the entry for the given key. // If no entry exists for the key, it creates a new, empty, mutable value // and stores it as the entry for the key. // It panics if the map value is not a message. Mutable(MapKey) Value // NewValue returns a new value assignable as a map value. // For enums, this returns the first enum value. // For other scalars, this returns the zero value. // For messages, this returns a new, empty, mutable value. NewValue() Value // IsValid reports whether the map is valid. // // An invalid map is an empty, read-only value. // // An invalid message often corresponds to a nil Go map value, // but the details are implementation dependent. // Validity is not part of the protobuf data model, and may not // be preserved in marshaling or other operations. IsValid() bool }
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/reflect/protoreflect/methods.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/methods.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 protoreflect import ( "google.golang.org/protobuf/internal/pragma" ) // The following types are used by the fast-path Message.ProtoMethods method. // // To avoid polluting the public protoreflect API with types used only by // low-level implementations, the canonical definitions of these types are // in the runtime/protoiface package. The definitions here and in protoiface // must be kept in sync. type ( methods = struct { pragma.NoUnkeyedLiterals Flags supportFlags Size func(sizeInput) sizeOutput Marshal func(marshalInput) (marshalOutput, error) Unmarshal func(unmarshalInput) (unmarshalOutput, error) Merge func(mergeInput) mergeOutput CheckInitialized func(checkInitializedInput) (checkInitializedOutput, error) Equal func(equalInput) equalOutput } supportFlags = uint64 sizeInput = struct { pragma.NoUnkeyedLiterals Message Message Flags uint8 } sizeOutput = struct { pragma.NoUnkeyedLiterals Size int } marshalInput = struct { pragma.NoUnkeyedLiterals Message Message Buf []byte Flags uint8 } marshalOutput = struct { pragma.NoUnkeyedLiterals Buf []byte } unmarshalInput = struct { pragma.NoUnkeyedLiterals Message Message Buf []byte Flags uint8 Resolver interface { FindExtensionByName(field FullName) (ExtensionType, error) FindExtensionByNumber(message FullName, field FieldNumber) (ExtensionType, error) } Depth int } unmarshalOutput = struct { pragma.NoUnkeyedLiterals Flags uint8 } mergeInput = struct { pragma.NoUnkeyedLiterals Source Message Destination Message } mergeOutput = struct { pragma.NoUnkeyedLiterals Flags uint8 } checkInitializedInput = struct { pragma.NoUnkeyedLiterals Message Message } checkInitializedOutput = struct { pragma.NoUnkeyedLiterals } equalInput = struct { pragma.NoUnkeyedLiterals MessageA Message MessageB Message } equalOutput = struct { pragma.NoUnkeyedLiterals Equal bool } )
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/reflect/protoreflect/source_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/source_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 protoreflect func (p *SourcePath) appendFileDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendSingularField(b, "package", nil) case 3: b = p.appendRepeatedField(b, "dependency", nil) case 10: b = p.appendRepeatedField(b, "public_dependency", nil) case 11: b = p.appendRepeatedField(b, "weak_dependency", nil) case 15: b = p.appendRepeatedField(b, "option_dependency", nil) case 4: b = p.appendRepeatedField(b, "message_type", (*SourcePath).appendDescriptorProto) case 5: b = p.appendRepeatedField(b, "enum_type", (*SourcePath).appendEnumDescriptorProto) case 6: b = p.appendRepeatedField(b, "service", (*SourcePath).appendServiceDescriptorProto) case 7: b = p.appendRepeatedField(b, "extension", (*SourcePath).appendFieldDescriptorProto) case 8: b = p.appendSingularField(b, "options", (*SourcePath).appendFileOptions) case 9: b = p.appendSingularField(b, "source_code_info", (*SourcePath).appendSourceCodeInfo) case 12: b = p.appendSingularField(b, "syntax", nil) case 14: b = p.appendSingularField(b, "edition", nil) } return b } func (p *SourcePath) appendDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendRepeatedField(b, "field", (*SourcePath).appendFieldDescriptorProto) case 6: b = p.appendRepeatedField(b, "extension", (*SourcePath).appendFieldDescriptorProto) case 3: b = p.appendRepeatedField(b, "nested_type", (*SourcePath).appendDescriptorProto) case 4: b = p.appendRepeatedField(b, "enum_type", (*SourcePath).appendEnumDescriptorProto) case 5: b = p.appendRepeatedField(b, "extension_range", (*SourcePath).appendDescriptorProto_ExtensionRange) case 8: b = p.appendRepeatedField(b, "oneof_decl", (*SourcePath).appendOneofDescriptorProto) case 7: b = p.appendSingularField(b, "options", (*SourcePath).appendMessageOptions) case 9: b = p.appendRepeatedField(b, "reserved_range", (*SourcePath).appendDescriptorProto_ReservedRange) case 10: b = p.appendRepeatedField(b, "reserved_name", nil) case 11: b = p.appendSingularField(b, "visibility", nil) } return b } func (p *SourcePath) appendEnumDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendRepeatedField(b, "value", (*SourcePath).appendEnumValueDescriptorProto) case 3: b = p.appendSingularField(b, "options", (*SourcePath).appendEnumOptions) case 4: b = p.appendRepeatedField(b, "reserved_range", (*SourcePath).appendEnumDescriptorProto_EnumReservedRange) case 5: b = p.appendRepeatedField(b, "reserved_name", nil) case 6: b = p.appendSingularField(b, "visibility", nil) } return b } func (p *SourcePath) appendServiceDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendRepeatedField(b, "method", (*SourcePath).appendMethodDescriptorProto) case 3: b = p.appendSingularField(b, "options", (*SourcePath).appendServiceOptions) } return b } func (p *SourcePath) appendFieldDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 3: b = p.appendSingularField(b, "number", nil) case 4: b = p.appendSingularField(b, "label", nil) case 5: b = p.appendSingularField(b, "type", nil) case 6: b = p.appendSingularField(b, "type_name", nil) case 2: b = p.appendSingularField(b, "extendee", nil) case 7: b = p.appendSingularField(b, "default_value", nil) case 9: b = p.appendSingularField(b, "oneof_index", nil) case 10: b = p.appendSingularField(b, "json_name", nil) case 8: b = p.appendSingularField(b, "options", (*SourcePath).appendFieldOptions) case 17: b = p.appendSingularField(b, "proto3_optional", nil) } return b } func (p *SourcePath) appendFileOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "java_package", nil) case 8: b = p.appendSingularField(b, "java_outer_classname", nil) case 10: b = p.appendSingularField(b, "java_multiple_files", nil) case 20: b = p.appendSingularField(b, "java_generate_equals_and_hash", nil) case 27: b = p.appendSingularField(b, "java_string_check_utf8", nil) case 9: b = p.appendSingularField(b, "optimize_for", nil) case 11: b = p.appendSingularField(b, "go_package", nil) case 16: b = p.appendSingularField(b, "cc_generic_services", nil) case 17: b = p.appendSingularField(b, "java_generic_services", nil) case 18: b = p.appendSingularField(b, "py_generic_services", nil) case 23: b = p.appendSingularField(b, "deprecated", nil) case 31: b = p.appendSingularField(b, "cc_enable_arenas", nil) case 36: b = p.appendSingularField(b, "objc_class_prefix", nil) case 37: b = p.appendSingularField(b, "csharp_namespace", nil) case 39: b = p.appendSingularField(b, "swift_prefix", nil) case 40: b = p.appendSingularField(b, "php_class_prefix", nil) case 41: b = p.appendSingularField(b, "php_namespace", nil) case 44: b = p.appendSingularField(b, "php_metadata_namespace", nil) case 45: b = p.appendSingularField(b, "ruby_package", nil) case 50: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendSourceCodeInfo(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendRepeatedField(b, "location", (*SourcePath).appendSourceCodeInfo_Location) } return b } func (p *SourcePath) appendDescriptorProto_ExtensionRange(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "start", nil) case 2: b = p.appendSingularField(b, "end", nil) case 3: b = p.appendSingularField(b, "options", (*SourcePath).appendExtensionRangeOptions) } return b } func (p *SourcePath) appendOneofDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendSingularField(b, "options", (*SourcePath).appendOneofOptions) } return b } func (p *SourcePath) appendMessageOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "message_set_wire_format", nil) case 2: b = p.appendSingularField(b, "no_standard_descriptor_accessor", nil) case 3: b = p.appendSingularField(b, "deprecated", nil) case 7: b = p.appendSingularField(b, "map_entry", nil) case 11: b = p.appendSingularField(b, "deprecated_legacy_json_field_conflicts", nil) case 12: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendDescriptorProto_ReservedRange(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "start", nil) case 2: b = p.appendSingularField(b, "end", nil) } return b } func (p *SourcePath) appendEnumValueDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendSingularField(b, "number", nil) case 3: b = p.appendSingularField(b, "options", (*SourcePath).appendEnumValueOptions) } return b } func (p *SourcePath) appendEnumOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 2: b = p.appendSingularField(b, "allow_alias", nil) case 3: b = p.appendSingularField(b, "deprecated", nil) case 6: b = p.appendSingularField(b, "deprecated_legacy_json_field_conflicts", nil) case 7: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendEnumDescriptorProto_EnumReservedRange(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "start", nil) case 2: b = p.appendSingularField(b, "end", nil) } return b } func (p *SourcePath) appendMethodDescriptorProto(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name", nil) case 2: b = p.appendSingularField(b, "input_type", nil) case 3: b = p.appendSingularField(b, "output_type", nil) case 4: b = p.appendSingularField(b, "options", (*SourcePath).appendMethodOptions) case 5: b = p.appendSingularField(b, "client_streaming", nil) case 6: b = p.appendSingularField(b, "server_streaming", nil) } return b } func (p *SourcePath) appendServiceOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 34: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 33: b = p.appendSingularField(b, "deprecated", nil) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendFieldOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "ctype", nil) case 2: b = p.appendSingularField(b, "packed", nil) case 6: b = p.appendSingularField(b, "jstype", nil) case 5: b = p.appendSingularField(b, "lazy", nil) case 15: b = p.appendSingularField(b, "unverified_lazy", nil) case 3: b = p.appendSingularField(b, "deprecated", nil) case 10: b = p.appendSingularField(b, "weak", nil) case 16: b = p.appendSingularField(b, "debug_redact", nil) case 17: b = p.appendSingularField(b, "retention", nil) case 19: b = p.appendRepeatedField(b, "targets", nil) case 20: b = p.appendRepeatedField(b, "edition_defaults", (*SourcePath).appendFieldOptions_EditionDefault) case 21: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 22: b = p.appendSingularField(b, "feature_support", (*SourcePath).appendFieldOptions_FeatureSupport) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendFeatureSet(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "field_presence", nil) case 2: b = p.appendSingularField(b, "enum_type", nil) case 3: b = p.appendSingularField(b, "repeated_field_encoding", nil) case 4: b = p.appendSingularField(b, "utf8_validation", nil) case 5: b = p.appendSingularField(b, "message_encoding", nil) case 6: b = p.appendSingularField(b, "json_format", nil) case 7: b = p.appendSingularField(b, "enforce_naming_style", nil) case 8: b = p.appendSingularField(b, "default_symbol_visibility", nil) } return b } func (p *SourcePath) appendUninterpretedOption(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 2: b = p.appendRepeatedField(b, "name", (*SourcePath).appendUninterpretedOption_NamePart) case 3: b = p.appendSingularField(b, "identifier_value", nil) case 4: b = p.appendSingularField(b, "positive_int_value", nil) case 5: b = p.appendSingularField(b, "negative_int_value", nil) case 6: b = p.appendSingularField(b, "double_value", nil) case 7: b = p.appendSingularField(b, "string_value", nil) case 8: b = p.appendSingularField(b, "aggregate_value", nil) } return b } func (p *SourcePath) appendSourceCodeInfo_Location(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendRepeatedField(b, "path", nil) case 2: b = p.appendRepeatedField(b, "span", nil) case 3: b = p.appendSingularField(b, "leading_comments", nil) case 4: b = p.appendSingularField(b, "trailing_comments", nil) case 6: b = p.appendRepeatedField(b, "leading_detached_comments", nil) } return b } func (p *SourcePath) appendExtensionRangeOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) case 2: b = p.appendRepeatedField(b, "declaration", (*SourcePath).appendExtensionRangeOptions_Declaration) case 50: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 3: b = p.appendSingularField(b, "verification", nil) } return b } func (p *SourcePath) appendOneofOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendEnumValueOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "deprecated", nil) case 2: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 3: b = p.appendSingularField(b, "debug_redact", nil) case 4: b = p.appendSingularField(b, "feature_support", (*SourcePath).appendFieldOptions_FeatureSupport) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendMethodOptions(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 33: b = p.appendSingularField(b, "deprecated", nil) case 34: b = p.appendSingularField(b, "idempotency_level", nil) case 35: b = p.appendSingularField(b, "features", (*SourcePath).appendFeatureSet) case 999: b = p.appendRepeatedField(b, "uninterpreted_option", (*SourcePath).appendUninterpretedOption) } return b } func (p *SourcePath) appendFieldOptions_EditionDefault(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 3: b = p.appendSingularField(b, "edition", nil) case 2: b = p.appendSingularField(b, "value", nil) } return b } func (p *SourcePath) appendFieldOptions_FeatureSupport(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "edition_introduced", nil) case 2: b = p.appendSingularField(b, "edition_deprecated", nil) case 3: b = p.appendSingularField(b, "deprecation_warning", nil) case 4: b = p.appendSingularField(b, "edition_removed", nil) } return b } func (p *SourcePath) appendUninterpretedOption_NamePart(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "name_part", nil) case 2: b = p.appendSingularField(b, "is_extension", nil) } return b } func (p *SourcePath) appendExtensionRangeOptions_Declaration(b []byte) []byte { if len(*p) == 0 { return b } switch (*p)[0] { case 1: b = p.appendSingularField(b, "number", nil) case 2: b = p.appendSingularField(b, "full_name", nil) case 3: b = p.appendSingularField(b, "type", nil) case 5: b = p.appendSingularField(b, "reserved", nil) case 6: b = p.appendSingularField(b, "repeated", nil) } return b }
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/reflect/protoreflect/value_equal.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protoreflect/value_equal.go
// Copyright 2022 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 protoreflect import ( "bytes" "fmt" "math" "reflect" "google.golang.org/protobuf/encoding/protowire" ) // Equal reports whether v1 and v2 are recursively equal. // // - Values of different types are always unequal. // // - Bytes values are equal if they contain identical bytes. // Empty bytes (regardless of nil-ness) are considered equal. // // - Floating point values are equal if they contain the same value. // Unlike the == operator, a NaN is equal to another NaN. // // - Enums are equal if they contain the same number. // Since [Value] does not contain an enum descriptor, // enum values do not consider the type of the enum. // // - Other scalar values are equal if they contain the same value. // // - [Message] values are equal if they belong to the same message descriptor, // have the same set of populated known and extension field values, // and the same set of unknown fields values. // // - [List] values are equal if they are the same length and // each corresponding element is equal. // // - [Map] values are equal if they have the same set of keys and // the corresponding value for each key is equal. func (v1 Value) Equal(v2 Value) bool { return equalValue(v1, v2) } func equalValue(x, y Value) bool { eqType := x.typ == y.typ switch x.typ { case nilType: return eqType case boolType: return eqType && x.Bool() == y.Bool() case int32Type, int64Type: return eqType && x.Int() == y.Int() case uint32Type, uint64Type: return eqType && x.Uint() == y.Uint() case float32Type, float64Type: return eqType && equalFloat(x.Float(), y.Float()) case stringType: return eqType && x.String() == y.String() case bytesType: return eqType && bytes.Equal(x.Bytes(), y.Bytes()) case enumType: return eqType && x.Enum() == y.Enum() default: switch x := x.Interface().(type) { case Message: y, ok := y.Interface().(Message) return ok && equalMessage(x, y) case List: y, ok := y.Interface().(List) return ok && equalList(x, y) case Map: y, ok := y.Interface().(Map) return ok && equalMap(x, y) default: panic(fmt.Sprintf("unknown type: %T", x)) } } } // equalFloat compares two floats, where NaNs are treated as equal. func equalFloat(x, y float64) bool { if math.IsNaN(x) || math.IsNaN(y) { return math.IsNaN(x) && math.IsNaN(y) } return x == y } // equalMessage compares two messages. func equalMessage(mx, my Message) bool { if mx.Descriptor() != my.Descriptor() { return false } nx := 0 equal := true mx.Range(func(fd FieldDescriptor, vx Value) bool { nx++ vy := my.Get(fd) equal = my.Has(fd) && equalValue(vx, vy) return equal }) if !equal { return false } ny := 0 my.Range(func(fd FieldDescriptor, vx Value) bool { ny++ return true }) if nx != ny { return false } return equalUnknown(mx.GetUnknown(), my.GetUnknown()) } // equalList compares two lists. func equalList(x, y List) bool { if x.Len() != y.Len() { return false } for i := x.Len() - 1; i >= 0; i-- { if !equalValue(x.Get(i), y.Get(i)) { return false } } return true } // equalMap compares two maps. func equalMap(x, y Map) bool { if x.Len() != y.Len() { return false } equal := true x.Range(func(k MapKey, vx Value) bool { vy := y.Get(k) equal = y.Has(k) && equalValue(vx, vy) return equal }) return equal } // equalUnknown compares unknown fields by direct comparison on the raw bytes // of each individual field number. func equalUnknown(x, y RawFields) bool { if len(x) != len(y) { return false } if bytes.Equal([]byte(x), []byte(y)) { return true } mx := make(map[FieldNumber]RawFields) my := make(map[FieldNumber]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:] } return reflect.DeepEqual(mx, my) }
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/reflect/protodesc/desc_init.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/desc_init.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 protodesc import ( "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/descriptorpb" ) type descsByName map[protoreflect.FullName]protoreflect.Descriptor func (r descsByName) initEnumDeclarations(eds []*descriptorpb.EnumDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (es []filedesc.Enum, err error) { es = make([]filedesc.Enum, len(eds)) // allocate up-front to ensure stable pointers for i, ed := range eds { e := &es[i] e.L2 = new(filedesc.EnumL2) if e.L0, err = r.makeBase(e, parent, ed.GetName(), i, sb); err != nil { return nil, err } if opts := ed.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.EnumOptions) e.L2.Options = func() protoreflect.ProtoMessage { return opts } } e.L1.EditionFeatures = mergeEditionFeatures(parent, ed.GetOptions().GetFeatures()) for _, s := range ed.GetReservedName() { e.L2.ReservedNames.List = append(e.L2.ReservedNames.List, protoreflect.Name(s)) } for _, rr := range ed.GetReservedRange() { e.L2.ReservedRanges.List = append(e.L2.ReservedRanges.List, [2]protoreflect.EnumNumber{ protoreflect.EnumNumber(rr.GetStart()), protoreflect.EnumNumber(rr.GetEnd()), }) } if e.L2.Values.List, err = r.initEnumValuesFromDescriptorProto(ed.GetValue(), e, sb); err != nil { return nil, err } } return es, nil } func (r descsByName) initEnumValuesFromDescriptorProto(vds []*descriptorpb.EnumValueDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (vs []filedesc.EnumValue, err error) { vs = make([]filedesc.EnumValue, len(vds)) // allocate up-front to ensure stable pointers for i, vd := range vds { v := &vs[i] if v.L0, err = r.makeBase(v, parent, vd.GetName(), i, sb); err != nil { return nil, err } if opts := vd.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.EnumValueOptions) v.L1.Options = func() protoreflect.ProtoMessage { return opts } } v.L1.Number = protoreflect.EnumNumber(vd.GetNumber()) } return vs, nil } func (r descsByName) initMessagesDeclarations(mds []*descriptorpb.DescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ms []filedesc.Message, err error) { ms = make([]filedesc.Message, len(mds)) // allocate up-front to ensure stable pointers for i, md := range mds { m := &ms[i] m.L2 = new(filedesc.MessageL2) if m.L0, err = r.makeBase(m, parent, md.GetName(), i, sb); err != nil { return nil, err } m.L1.EditionFeatures = mergeEditionFeatures(parent, md.GetOptions().GetFeatures()) if opts := md.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.MessageOptions) m.L2.Options = func() protoreflect.ProtoMessage { return opts } m.L1.IsMapEntry = opts.GetMapEntry() m.L1.IsMessageSet = opts.GetMessageSetWireFormat() } for _, s := range md.GetReservedName() { m.L2.ReservedNames.List = append(m.L2.ReservedNames.List, protoreflect.Name(s)) } for _, rr := range md.GetReservedRange() { m.L2.ReservedRanges.List = append(m.L2.ReservedRanges.List, [2]protoreflect.FieldNumber{ protoreflect.FieldNumber(rr.GetStart()), protoreflect.FieldNumber(rr.GetEnd()), }) } for _, xr := range md.GetExtensionRange() { m.L2.ExtensionRanges.List = append(m.L2.ExtensionRanges.List, [2]protoreflect.FieldNumber{ protoreflect.FieldNumber(xr.GetStart()), protoreflect.FieldNumber(xr.GetEnd()), }) var optsFunc func() protoreflect.ProtoMessage if opts := xr.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.ExtensionRangeOptions) optsFunc = func() protoreflect.ProtoMessage { return opts } } m.L2.ExtensionRangeOptions = append(m.L2.ExtensionRangeOptions, optsFunc) } if m.L2.Fields.List, err = r.initFieldsFromDescriptorProto(md.GetField(), m, sb); err != nil { return nil, err } if m.L2.Oneofs.List, err = r.initOneofsFromDescriptorProto(md.GetOneofDecl(), m, sb); err != nil { return nil, err } if m.L1.Enums.List, err = r.initEnumDeclarations(md.GetEnumType(), m, sb); err != nil { return nil, err } if m.L1.Messages.List, err = r.initMessagesDeclarations(md.GetNestedType(), m, sb); err != nil { return nil, err } if m.L1.Extensions.List, err = r.initExtensionDeclarations(md.GetExtension(), m, sb); err != nil { return nil, err } } return ms, nil } // canBePacked returns whether the field can use packed encoding: // https://protobuf.dev/programming-guides/encoding/#packed func canBePacked(fd *descriptorpb.FieldDescriptorProto) bool { if fd.GetLabel() != descriptorpb.FieldDescriptorProto_LABEL_REPEATED { return false // not a repeated field } switch protoreflect.Kind(fd.GetType()) { case protoreflect.MessageKind, protoreflect.GroupKind: return false // not a scalar type field case protoreflect.StringKind, protoreflect.BytesKind: // string and bytes can explicitly not be declared as packed, // see https://protobuf.dev/programming-guides/encoding/#packed return false default: return true } } func (r descsByName) initFieldsFromDescriptorProto(fds []*descriptorpb.FieldDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (fs []filedesc.Field, err error) { fs = make([]filedesc.Field, len(fds)) // allocate up-front to ensure stable pointers for i, fd := range fds { f := &fs[i] if f.L0, err = r.makeBase(f, parent, fd.GetName(), i, sb); err != nil { return nil, err } f.L1.EditionFeatures = mergeEditionFeatures(parent, fd.GetOptions().GetFeatures()) f.L1.IsProto3Optional = fd.GetProto3Optional() if opts := fd.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.FieldOptions) f.L1.Options = func() protoreflect.ProtoMessage { return opts } f.L1.IsLazy = opts.GetLazy() if opts.Packed != nil { f.L1.EditionFeatures.IsPacked = opts.GetPacked() } } f.L1.Number = protoreflect.FieldNumber(fd.GetNumber()) f.L1.Cardinality = protoreflect.Cardinality(fd.GetLabel()) if fd.Type != nil { f.L1.Kind = protoreflect.Kind(fd.GetType()) } if fd.JsonName != nil { f.L1.StringName.InitJSON(fd.GetJsonName()) } if f.L1.EditionFeatures.IsLegacyRequired { f.L1.Cardinality = protoreflect.Required } if f.L1.Kind == protoreflect.MessageKind && f.L1.EditionFeatures.IsDelimitedEncoded { f.L1.Kind = protoreflect.GroupKind } } return fs, nil } func (r descsByName) initOneofsFromDescriptorProto(ods []*descriptorpb.OneofDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (os []filedesc.Oneof, err error) { os = make([]filedesc.Oneof, len(ods)) // allocate up-front to ensure stable pointers for i, od := range ods { o := &os[i] if o.L0, err = r.makeBase(o, parent, od.GetName(), i, sb); err != nil { return nil, err } o.L1.EditionFeatures = mergeEditionFeatures(parent, od.GetOptions().GetFeatures()) if opts := od.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.OneofOptions) o.L1.Options = func() protoreflect.ProtoMessage { return opts } } } return os, nil } func (r descsByName) initExtensionDeclarations(xds []*descriptorpb.FieldDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (xs []filedesc.Extension, err error) { xs = make([]filedesc.Extension, len(xds)) // allocate up-front to ensure stable pointers for i, xd := range xds { x := &xs[i] x.L2 = new(filedesc.ExtensionL2) if x.L0, err = r.makeBase(x, parent, xd.GetName(), i, sb); err != nil { return nil, err } x.L1.EditionFeatures = mergeEditionFeatures(parent, xd.GetOptions().GetFeatures()) if opts := xd.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.FieldOptions) x.L2.Options = func() protoreflect.ProtoMessage { return opts } if opts.Packed != nil { x.L1.EditionFeatures.IsPacked = opts.GetPacked() } } x.L1.Number = protoreflect.FieldNumber(xd.GetNumber()) x.L1.Cardinality = protoreflect.Cardinality(xd.GetLabel()) if xd.Type != nil { x.L1.Kind = protoreflect.Kind(xd.GetType()) } if xd.JsonName != nil { x.L2.StringName.InitJSON(xd.GetJsonName()) } if x.L1.Kind == protoreflect.MessageKind && x.L1.EditionFeatures.IsDelimitedEncoded { x.L1.Kind = protoreflect.GroupKind } } return xs, nil } func (r descsByName) initServiceDeclarations(sds []*descriptorpb.ServiceDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ss []filedesc.Service, err error) { ss = make([]filedesc.Service, len(sds)) // allocate up-front to ensure stable pointers for i, sd := range sds { s := &ss[i] s.L2 = new(filedesc.ServiceL2) if s.L0, err = r.makeBase(s, parent, sd.GetName(), i, sb); err != nil { return nil, err } if opts := sd.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.ServiceOptions) s.L2.Options = func() protoreflect.ProtoMessage { return opts } } if s.L2.Methods.List, err = r.initMethodsFromDescriptorProto(sd.GetMethod(), s, sb); err != nil { return nil, err } } return ss, nil } func (r descsByName) initMethodsFromDescriptorProto(mds []*descriptorpb.MethodDescriptorProto, parent protoreflect.Descriptor, sb *strs.Builder) (ms []filedesc.Method, err error) { ms = make([]filedesc.Method, len(mds)) // allocate up-front to ensure stable pointers for i, md := range mds { m := &ms[i] if m.L0, err = r.makeBase(m, parent, md.GetName(), i, sb); err != nil { return nil, err } if opts := md.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.MethodOptions) m.L1.Options = func() protoreflect.ProtoMessage { return opts } } m.L1.IsStreamingClient = md.GetClientStreaming() m.L1.IsStreamingServer = md.GetServerStreaming() } return ms, nil } func (r descsByName) makeBase(child, parent protoreflect.Descriptor, name string, idx int, sb *strs.Builder) (filedesc.BaseL0, error) { if !protoreflect.Name(name).IsValid() { return filedesc.BaseL0{}, errors.New("descriptor %q has an invalid nested name: %q", parent.FullName(), name) } // Derive the full name of the child. // Note that enum values are a sibling to the enum parent in the namespace. var fullName protoreflect.FullName if _, ok := parent.(protoreflect.EnumDescriptor); ok { fullName = sb.AppendFullName(parent.FullName().Parent(), protoreflect.Name(name)) } else { fullName = sb.AppendFullName(parent.FullName(), protoreflect.Name(name)) } if _, ok := r[fullName]; ok { return filedesc.BaseL0{}, errors.New("descriptor %q already declared", fullName) } r[fullName] = child // TODO: Verify that the full name does not already exist in the resolver? // This is not as critical since most usages of NewFile will register // the created file back into the registry, which will perform this check. return filedesc.BaseL0{ FullName: fullName, ParentFile: parent.ParentFile().(*filedesc.File), Parent: parent, Index: idx, }, 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/reflect/protodesc/desc_resolve.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/desc_resolve.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 protodesc import ( "google.golang.org/protobuf/internal/encoding/defval" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/descriptorpb" ) // resolver is a wrapper around a local registry of declarations within the file // and the remote resolver. The remote resolver is restricted to only return // descriptors that have been imported. type resolver struct { local descsByName remote Resolver imports importSet allowUnresolvable bool } func (r *resolver) resolveMessageDependencies(ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) (err error) { for i, md := range mds { m := &ms[i] for j, fd := range md.GetField() { f := &m.L2.Fields.List[j] if f.L1.Cardinality == protoreflect.Required { m.L2.RequiredNumbers.List = append(m.L2.RequiredNumbers.List, f.L1.Number) } if fd.OneofIndex != nil { k := int(fd.GetOneofIndex()) if !(0 <= k && k < len(md.GetOneofDecl())) { return errors.New("message field %q has an invalid oneof index: %d", f.FullName(), k) } o := &m.L2.Oneofs.List[k] f.L1.ContainingOneof = o o.L1.Fields.List = append(o.L1.Fields.List, f) } if f.L1.Kind, f.L1.Enum, f.L1.Message, err = r.findTarget(f.Kind(), f.Parent().FullName(), partialName(fd.GetTypeName())); err != nil { return errors.New("message field %q cannot resolve type: %v", f.FullName(), err) } if f.L1.Kind == protoreflect.GroupKind && (f.IsMap() || f.IsMapEntry()) { // A map field might inherit delimited encoding from a file-wide default feature. // But maps never actually use delimited encoding. (At least for now...) f.L1.Kind = protoreflect.MessageKind } if fd.DefaultValue != nil { v, ev, err := unmarshalDefault(fd.GetDefaultValue(), f, r.allowUnresolvable) if err != nil { return errors.New("message field %q has invalid default: %v", f.FullName(), err) } f.L1.Default = filedesc.DefaultValue(v, ev) } } if err := r.resolveMessageDependencies(m.L1.Messages.List, md.GetNestedType()); err != nil { return err } if err := r.resolveExtensionDependencies(m.L1.Extensions.List, md.GetExtension()); err != nil { return err } } return nil } func (r *resolver) resolveExtensionDependencies(xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) (err error) { for i, xd := range xds { x := &xs[i] if x.L1.Extendee, err = r.findMessageDescriptor(x.Parent().FullName(), partialName(xd.GetExtendee())); err != nil { return errors.New("extension field %q cannot resolve extendee: %v", x.FullName(), err) } if x.L1.Kind, x.L2.Enum, x.L2.Message, err = r.findTarget(x.Kind(), x.Parent().FullName(), partialName(xd.GetTypeName())); err != nil { return errors.New("extension field %q cannot resolve type: %v", x.FullName(), err) } if xd.DefaultValue != nil { v, ev, err := unmarshalDefault(xd.GetDefaultValue(), x, r.allowUnresolvable) if err != nil { return errors.New("extension field %q has invalid default: %v", x.FullName(), err) } x.L2.Default = filedesc.DefaultValue(v, ev) } } return nil } func (r *resolver) resolveServiceDependencies(ss []filedesc.Service, sds []*descriptorpb.ServiceDescriptorProto) (err error) { for i, sd := range sds { s := &ss[i] for j, md := range sd.GetMethod() { m := &s.L2.Methods.List[j] m.L1.Input, err = r.findMessageDescriptor(m.Parent().FullName(), partialName(md.GetInputType())) if err != nil { return errors.New("service method %q cannot resolve input: %v", m.FullName(), err) } m.L1.Output, err = r.findMessageDescriptor(s.FullName(), partialName(md.GetOutputType())) if err != nil { return errors.New("service method %q cannot resolve output: %v", m.FullName(), err) } } } return nil } // findTarget finds an enum or message descriptor if k is an enum, message, // group, or unknown. If unknown, and the name could be resolved, the kind // returned kind is set based on the type of the resolved descriptor. func (r *resolver) findTarget(k protoreflect.Kind, scope protoreflect.FullName, ref partialName) (protoreflect.Kind, protoreflect.EnumDescriptor, protoreflect.MessageDescriptor, error) { switch k { case protoreflect.EnumKind: ed, err := r.findEnumDescriptor(scope, ref) if err != nil { return 0, nil, nil, err } return k, ed, nil, nil case protoreflect.MessageKind, protoreflect.GroupKind: md, err := r.findMessageDescriptor(scope, ref) if err != nil { return 0, nil, nil, err } return k, nil, md, nil case 0: // Handle unspecified kinds (possible with parsers that operate // on a per-file basis without knowledge of dependencies). d, err := r.findDescriptor(scope, ref) if err == protoregistry.NotFound && r.allowUnresolvable { return k, filedesc.PlaceholderEnum(ref.FullName()), filedesc.PlaceholderMessage(ref.FullName()), nil } else if err == protoregistry.NotFound { return 0, nil, nil, errors.New("%q not found", ref.FullName()) } else if err != nil { return 0, nil, nil, err } switch d := d.(type) { case protoreflect.EnumDescriptor: return protoreflect.EnumKind, d, nil, nil case protoreflect.MessageDescriptor: return protoreflect.MessageKind, nil, d, nil default: return 0, nil, nil, errors.New("unknown kind") } default: if ref != "" { return 0, nil, nil, errors.New("target name cannot be specified for %v", k) } if !k.IsValid() { return 0, nil, nil, errors.New("invalid kind: %d", k) } return k, nil, nil, nil } } // findDescriptor finds the descriptor by name, // which may be a relative name within some scope. // // Suppose the scope was "fizz.buzz" and the reference was "Foo.Bar", // then the following full names are searched: // - fizz.buzz.Foo.Bar // - fizz.Foo.Bar // - Foo.Bar func (r *resolver) findDescriptor(scope protoreflect.FullName, ref partialName) (protoreflect.Descriptor, error) { if !ref.IsValid() { return nil, errors.New("invalid name reference: %q", ref) } if ref.IsFull() { scope, ref = "", ref[1:] } var foundButNotImported protoreflect.Descriptor for { // Derive the full name to search. s := protoreflect.FullName(ref) if scope != "" { s = scope + "." + s } // Check the current file for the descriptor. if d, ok := r.local[s]; ok { return d, nil } // Check the remote registry for the descriptor. d, err := r.remote.FindDescriptorByName(s) if err == nil { // Only allow descriptors covered by one of the imports. if r.imports[d.ParentFile().Path()] { return d, nil } foundButNotImported = d } else if err != protoregistry.NotFound { return nil, errors.Wrap(err, "%q", s) } // Continue on at a higher level of scoping. if scope == "" { if d := foundButNotImported; d != nil { return nil, errors.New("resolved %q, but %q is not imported", d.FullName(), d.ParentFile().Path()) } return nil, protoregistry.NotFound } scope = scope.Parent() } } func (r *resolver) findEnumDescriptor(scope protoreflect.FullName, ref partialName) (protoreflect.EnumDescriptor, error) { d, err := r.findDescriptor(scope, ref) if err == protoregistry.NotFound && r.allowUnresolvable { return filedesc.PlaceholderEnum(ref.FullName()), nil } else if err == protoregistry.NotFound { return nil, errors.New("%q not found", ref.FullName()) } else if err != nil { return nil, err } ed, ok := d.(protoreflect.EnumDescriptor) if !ok { return nil, errors.New("resolved %q, but it is not an enum", d.FullName()) } return ed, nil } func (r *resolver) findMessageDescriptor(scope protoreflect.FullName, ref partialName) (protoreflect.MessageDescriptor, error) { d, err := r.findDescriptor(scope, ref) if err == protoregistry.NotFound && r.allowUnresolvable { return filedesc.PlaceholderMessage(ref.FullName()), nil } else if err == protoregistry.NotFound { return nil, errors.New("%q not found", ref.FullName()) } else if err != nil { return nil, err } md, ok := d.(protoreflect.MessageDescriptor) if !ok { return nil, errors.New("resolved %q, but it is not an message", d.FullName()) } return md, nil } // partialName is the partial name. A leading dot means that the name is full, // otherwise the name is relative to some current scope. // See google.protobuf.FieldDescriptorProto.type_name. type partialName string func (s partialName) IsFull() bool { return len(s) > 0 && s[0] == '.' } func (s partialName) IsValid() bool { if s.IsFull() { return protoreflect.FullName(s[1:]).IsValid() } return protoreflect.FullName(s).IsValid() } const unknownPrefix = "*." // FullName converts the partial name to a full name on a best-effort basis. // If relative, it creates an invalid full name, using a "*." prefix // to indicate that the start of the full name is unknown. func (s partialName) FullName() protoreflect.FullName { if s.IsFull() { return protoreflect.FullName(s[1:]) } return protoreflect.FullName(unknownPrefix + s) } func unmarshalDefault(s string, fd protoreflect.FieldDescriptor, allowUnresolvable bool) (protoreflect.Value, protoreflect.EnumValueDescriptor, error) { var evs protoreflect.EnumValueDescriptors if fd.Enum() != nil { evs = fd.Enum().Values() } v, ev, err := defval.Unmarshal(s, fd.Kind(), evs, defval.Descriptor) if err != nil && allowUnresolvable && evs != nil && protoreflect.Name(s).IsValid() { v = protoreflect.ValueOfEnum(0) if evs.Len() > 0 { v = protoreflect.ValueOfEnum(evs.Get(0).Number()) } ev = filedesc.PlaceholderEnumValue(fd.Enum().FullName().Parent().Append(protoreflect.Name(s))) } else if err != nil { return v, ev, err } if !fd.HasPresence() { return v, ev, errors.New("cannot be specified with implicit field presence") } if fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind || fd.Cardinality() == protoreflect.Repeated { return v, ev, errors.New("cannot be specified on composite types") } return v, ev, 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/reflect/protodesc/proto.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/proto.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 protodesc import ( "fmt" "strings" "google.golang.org/protobuf/internal/encoding/defval" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/descriptorpb" ) // ToFileDescriptorProto copies a [protoreflect.FileDescriptor] into a // google.protobuf.FileDescriptorProto message. func ToFileDescriptorProto(file protoreflect.FileDescriptor) *descriptorpb.FileDescriptorProto { p := &descriptorpb.FileDescriptorProto{ Name: proto.String(file.Path()), Options: proto.Clone(file.Options()).(*descriptorpb.FileOptions), } if file.Package() != "" { p.Package = proto.String(string(file.Package())) } for i, imports := 0, file.Imports(); i < imports.Len(); i++ { imp := imports.Get(i) p.Dependency = append(p.Dependency, imp.Path()) if imp.IsPublic { p.PublicDependency = append(p.PublicDependency, int32(i)) } } for i, locs := 0, file.SourceLocations(); i < locs.Len(); i++ { loc := locs.Get(i) l := &descriptorpb.SourceCodeInfo_Location{} l.Path = append(l.Path, loc.Path...) if loc.StartLine == loc.EndLine { l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndColumn)} } else { l.Span = []int32{int32(loc.StartLine), int32(loc.StartColumn), int32(loc.EndLine), int32(loc.EndColumn)} } l.LeadingDetachedComments = append([]string(nil), loc.LeadingDetachedComments...) if loc.LeadingComments != "" { l.LeadingComments = proto.String(loc.LeadingComments) } if loc.TrailingComments != "" { l.TrailingComments = proto.String(loc.TrailingComments) } if p.SourceCodeInfo == nil { p.SourceCodeInfo = &descriptorpb.SourceCodeInfo{} } p.SourceCodeInfo.Location = append(p.SourceCodeInfo.Location, l) } for i, messages := 0, file.Messages(); i < messages.Len(); i++ { p.MessageType = append(p.MessageType, ToDescriptorProto(messages.Get(i))) } for i, enums := 0, file.Enums(); i < enums.Len(); i++ { p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i))) } for i, services := 0, file.Services(); i < services.Len(); i++ { p.Service = append(p.Service, ToServiceDescriptorProto(services.Get(i))) } for i, exts := 0, file.Extensions(); i < exts.Len(); i++ { p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i))) } if syntax := file.Syntax(); syntax != protoreflect.Proto2 && syntax.IsValid() { p.Syntax = proto.String(file.Syntax().String()) } if file.Syntax() == protoreflect.Editions { desc := file if fileImportDesc, ok := file.(protoreflect.FileImport); ok { desc = fileImportDesc.FileDescriptor } if editionsInterface, ok := desc.(interface{ Edition() int32 }); ok { p.Edition = descriptorpb.Edition(editionsInterface.Edition()).Enum() } } return p } // ToDescriptorProto copies a [protoreflect.MessageDescriptor] into a // google.protobuf.DescriptorProto message. func ToDescriptorProto(message protoreflect.MessageDescriptor) *descriptorpb.DescriptorProto { p := &descriptorpb.DescriptorProto{ Name: proto.String(string(message.Name())), Options: proto.Clone(message.Options()).(*descriptorpb.MessageOptions), } for i, fields := 0, message.Fields(); i < fields.Len(); i++ { p.Field = append(p.Field, ToFieldDescriptorProto(fields.Get(i))) } for i, exts := 0, message.Extensions(); i < exts.Len(); i++ { p.Extension = append(p.Extension, ToFieldDescriptorProto(exts.Get(i))) } for i, messages := 0, message.Messages(); i < messages.Len(); i++ { p.NestedType = append(p.NestedType, ToDescriptorProto(messages.Get(i))) } for i, enums := 0, message.Enums(); i < enums.Len(); i++ { p.EnumType = append(p.EnumType, ToEnumDescriptorProto(enums.Get(i))) } for i, xranges := 0, message.ExtensionRanges(); i < xranges.Len(); i++ { xrange := xranges.Get(i) p.ExtensionRange = append(p.ExtensionRange, &descriptorpb.DescriptorProto_ExtensionRange{ Start: proto.Int32(int32(xrange[0])), End: proto.Int32(int32(xrange[1])), Options: proto.Clone(message.ExtensionRangeOptions(i)).(*descriptorpb.ExtensionRangeOptions), }) } for i, oneofs := 0, message.Oneofs(); i < oneofs.Len(); i++ { p.OneofDecl = append(p.OneofDecl, ToOneofDescriptorProto(oneofs.Get(i))) } for i, ranges := 0, message.ReservedRanges(); i < ranges.Len(); i++ { rrange := ranges.Get(i) p.ReservedRange = append(p.ReservedRange, &descriptorpb.DescriptorProto_ReservedRange{ Start: proto.Int32(int32(rrange[0])), End: proto.Int32(int32(rrange[1])), }) } for i, names := 0, message.ReservedNames(); i < names.Len(); i++ { p.ReservedName = append(p.ReservedName, string(names.Get(i))) } return p } // ToFieldDescriptorProto copies a [protoreflect.FieldDescriptor] into a // google.protobuf.FieldDescriptorProto message. func ToFieldDescriptorProto(field protoreflect.FieldDescriptor) *descriptorpb.FieldDescriptorProto { p := &descriptorpb.FieldDescriptorProto{ Name: proto.String(string(field.Name())), Number: proto.Int32(int32(field.Number())), Label: descriptorpb.FieldDescriptorProto_Label(field.Cardinality()).Enum(), Options: proto.Clone(field.Options()).(*descriptorpb.FieldOptions), } if field.IsExtension() { p.Extendee = fullNameOf(field.ContainingMessage()) } if field.Kind().IsValid() { p.Type = descriptorpb.FieldDescriptorProto_Type(field.Kind()).Enum() } if field.Enum() != nil { p.TypeName = fullNameOf(field.Enum()) } if field.Message() != nil { p.TypeName = fullNameOf(field.Message()) } if field.HasJSONName() { // A bug in older versions of protoc would always populate the // "json_name" option for extensions when it is meaningless. // When it did so, it would always use the camel-cased field name. if field.IsExtension() { p.JsonName = proto.String(strs.JSONCamelCase(string(field.Name()))) } else { p.JsonName = proto.String(field.JSONName()) } } if field.Syntax() == protoreflect.Proto3 && field.HasOptionalKeyword() { p.Proto3Optional = proto.Bool(true) } if field.Syntax() == protoreflect.Editions { // Editions have no group keyword, this type is only set so that downstream users continue // treating this as delimited encoding. if p.GetType() == descriptorpb.FieldDescriptorProto_TYPE_GROUP { p.Type = descriptorpb.FieldDescriptorProto_TYPE_MESSAGE.Enum() } // Editions have no required keyword, this label is only set so that downstream users continue // treating it as required. if p.GetLabel() == descriptorpb.FieldDescriptorProto_LABEL_REQUIRED { p.Label = descriptorpb.FieldDescriptorProto_LABEL_OPTIONAL.Enum() } } if field.HasDefault() { def, err := defval.Marshal(field.Default(), field.DefaultEnumValue(), field.Kind(), defval.Descriptor) if err != nil && field.DefaultEnumValue() != nil { def = string(field.DefaultEnumValue().Name()) // occurs for unresolved enum values } else if err != nil { panic(fmt.Sprintf("%v: %v", field.FullName(), err)) } p.DefaultValue = proto.String(def) } if oneof := field.ContainingOneof(); oneof != nil { p.OneofIndex = proto.Int32(int32(oneof.Index())) } return p } // ToOneofDescriptorProto copies a [protoreflect.OneofDescriptor] into a // google.protobuf.OneofDescriptorProto message. func ToOneofDescriptorProto(oneof protoreflect.OneofDescriptor) *descriptorpb.OneofDescriptorProto { return &descriptorpb.OneofDescriptorProto{ Name: proto.String(string(oneof.Name())), Options: proto.Clone(oneof.Options()).(*descriptorpb.OneofOptions), } } // ToEnumDescriptorProto copies a [protoreflect.EnumDescriptor] into a // google.protobuf.EnumDescriptorProto message. func ToEnumDescriptorProto(enum protoreflect.EnumDescriptor) *descriptorpb.EnumDescriptorProto { p := &descriptorpb.EnumDescriptorProto{ Name: proto.String(string(enum.Name())), Options: proto.Clone(enum.Options()).(*descriptorpb.EnumOptions), } for i, values := 0, enum.Values(); i < values.Len(); i++ { p.Value = append(p.Value, ToEnumValueDescriptorProto(values.Get(i))) } for i, ranges := 0, enum.ReservedRanges(); i < ranges.Len(); i++ { rrange := ranges.Get(i) p.ReservedRange = append(p.ReservedRange, &descriptorpb.EnumDescriptorProto_EnumReservedRange{ Start: proto.Int32(int32(rrange[0])), End: proto.Int32(int32(rrange[1])), }) } for i, names := 0, enum.ReservedNames(); i < names.Len(); i++ { p.ReservedName = append(p.ReservedName, string(names.Get(i))) } return p } // ToEnumValueDescriptorProto copies a [protoreflect.EnumValueDescriptor] into a // google.protobuf.EnumValueDescriptorProto message. func ToEnumValueDescriptorProto(value protoreflect.EnumValueDescriptor) *descriptorpb.EnumValueDescriptorProto { return &descriptorpb.EnumValueDescriptorProto{ Name: proto.String(string(value.Name())), Number: proto.Int32(int32(value.Number())), Options: proto.Clone(value.Options()).(*descriptorpb.EnumValueOptions), } } // ToServiceDescriptorProto copies a [protoreflect.ServiceDescriptor] into a // google.protobuf.ServiceDescriptorProto message. func ToServiceDescriptorProto(service protoreflect.ServiceDescriptor) *descriptorpb.ServiceDescriptorProto { p := &descriptorpb.ServiceDescriptorProto{ Name: proto.String(string(service.Name())), Options: proto.Clone(service.Options()).(*descriptorpb.ServiceOptions), } for i, methods := 0, service.Methods(); i < methods.Len(); i++ { p.Method = append(p.Method, ToMethodDescriptorProto(methods.Get(i))) } return p } // ToMethodDescriptorProto copies a [protoreflect.MethodDescriptor] into a // google.protobuf.MethodDescriptorProto message. func ToMethodDescriptorProto(method protoreflect.MethodDescriptor) *descriptorpb.MethodDescriptorProto { p := &descriptorpb.MethodDescriptorProto{ Name: proto.String(string(method.Name())), InputType: fullNameOf(method.Input()), OutputType: fullNameOf(method.Output()), Options: proto.Clone(method.Options()).(*descriptorpb.MethodOptions), } if method.IsStreamingClient() { p.ClientStreaming = proto.Bool(true) } if method.IsStreamingServer() { p.ServerStreaming = proto.Bool(true) } return p } func fullNameOf(d protoreflect.Descriptor) *string { if d == nil { return nil } if strings.HasPrefix(string(d.FullName()), unknownPrefix) { return proto.String(string(d.FullName()[len(unknownPrefix):])) } return proto.String("." + string(d.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/reflect/protodesc/editions.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/editions.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 protodesc import ( "fmt" "os" "sync" "google.golang.org/protobuf/internal/editiondefaults" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/types/descriptorpb" "google.golang.org/protobuf/types/gofeaturespb" ) var defaults = &descriptorpb.FeatureSetDefaults{} var defaultsCacheMu sync.Mutex var defaultsCache = make(map[filedesc.Edition]*descriptorpb.FeatureSet) func init() { err := proto.Unmarshal(editiondefaults.Defaults, defaults) if err != nil { fmt.Fprintf(os.Stderr, "unmarshal editions defaults: %v\n", err) os.Exit(1) } } func fromEditionProto(epb descriptorpb.Edition) filedesc.Edition { return filedesc.Edition(epb) } func toEditionProto(ed filedesc.Edition) descriptorpb.Edition { switch ed { case filedesc.EditionUnknown: return descriptorpb.Edition_EDITION_UNKNOWN case filedesc.EditionProto2: return descriptorpb.Edition_EDITION_PROTO2 case filedesc.EditionProto3: return descriptorpb.Edition_EDITION_PROTO3 case filedesc.Edition2023: return descriptorpb.Edition_EDITION_2023 case filedesc.Edition2024: return descriptorpb.Edition_EDITION_2024 default: panic(fmt.Sprintf("unknown value for edition: %v", ed)) } } func getFeatureSetFor(ed filedesc.Edition) *descriptorpb.FeatureSet { defaultsCacheMu.Lock() defer defaultsCacheMu.Unlock() if def, ok := defaultsCache[ed]; ok { return def } edpb := toEditionProto(ed) if defaults.GetMinimumEdition() > edpb || defaults.GetMaximumEdition() < edpb { // This should never happen protodesc.(FileOptions).New would fail when // initializing the file descriptor. // This most likely means the embedded defaults were not updated. fmt.Fprintf(os.Stderr, "internal error: unsupported edition %v (did you forget to update the embedded defaults (i.e. the bootstrap descriptor proto)?)\n", edpb) os.Exit(1) } fsed := defaults.GetDefaults()[0] // Using a linear search for now. // Editions are guaranteed to be sorted and thus we could use a binary search. // Given that there are only a handful of editions (with one more per year) // there is not much reason to use a binary search. for _, def := range defaults.GetDefaults() { if def.GetEdition() <= edpb { fsed = def } else { break } } fs := proto.Clone(fsed.GetFixedFeatures()).(*descriptorpb.FeatureSet) proto.Merge(fs, fsed.GetOverridableFeatures()) defaultsCache[ed] = fs return fs } // mergeEditionFeatures merges the parent and child feature sets. This function // should be used when initializing Go descriptors from descriptor protos which // is why the parent is a filedesc.EditionsFeatures (Go representation) while // the child is a descriptorproto.FeatureSet (protoc representation). // Any feature set by the child overwrites what is set by the parent. func mergeEditionFeatures(parentDesc protoreflect.Descriptor, child *descriptorpb.FeatureSet) filedesc.EditionFeatures { var parentFS filedesc.EditionFeatures switch p := parentDesc.(type) { case *filedesc.File: parentFS = p.L1.EditionFeatures case *filedesc.Message: parentFS = p.L1.EditionFeatures default: panic(fmt.Sprintf("unknown parent type %T", parentDesc)) } if child == nil { return parentFS } if fp := child.FieldPresence; fp != nil { parentFS.IsFieldPresence = *fp == descriptorpb.FeatureSet_LEGACY_REQUIRED || *fp == descriptorpb.FeatureSet_EXPLICIT parentFS.IsLegacyRequired = *fp == descriptorpb.FeatureSet_LEGACY_REQUIRED } if et := child.EnumType; et != nil { parentFS.IsOpenEnum = *et == descriptorpb.FeatureSet_OPEN } if rfe := child.RepeatedFieldEncoding; rfe != nil { parentFS.IsPacked = *rfe == descriptorpb.FeatureSet_PACKED } if utf8val := child.Utf8Validation; utf8val != nil { parentFS.IsUTF8Validated = *utf8val == descriptorpb.FeatureSet_VERIFY } if me := child.MessageEncoding; me != nil { parentFS.IsDelimitedEncoded = *me == descriptorpb.FeatureSet_DELIMITED } if jf := child.JsonFormat; jf != nil { parentFS.IsJSONCompliant = *jf == descriptorpb.FeatureSet_ALLOW } // We must not use proto.GetExtension(child, gofeaturespb.E_Go) // because that only works for messages we generated, but not for // dynamicpb messages. See golang/protobuf#1669. // // Further, we harden this code against adversarial inputs: a // service which accepts descriptors from a possibly malicious // source shouldn't crash. goFeatures := child.ProtoReflect().Get(gofeaturespb.E_Go.TypeDescriptor()) if !goFeatures.IsValid() { return parentFS } gf, ok := goFeatures.Interface().(protoreflect.Message) if !ok { return parentFS } // gf.Interface() could be *dynamicpb.Message or *gofeaturespb.GoFeatures. fields := gf.Descriptor().Fields() if fd := fields.ByNumber(genid.GoFeatures_LegacyUnmarshalJsonEnum_field_number); fd != nil && !fd.IsList() && fd.Kind() == protoreflect.BoolKind && gf.Has(fd) { parentFS.GenerateLegacyUnmarshalJSON = gf.Get(fd).Bool() } if fd := fields.ByNumber(genid.GoFeatures_StripEnumPrefix_field_number); fd != nil && !fd.IsList() && fd.Kind() == protoreflect.EnumKind && gf.Has(fd) { parentFS.StripEnumPrefix = int(gf.Get(fd).Enum()) } if fd := fields.ByNumber(genid.GoFeatures_ApiLevel_field_number); fd != nil && !fd.IsList() && fd.Kind() == protoreflect.EnumKind && gf.Has(fd) { parentFS.APILevel = int(gf.Get(fd).Enum()) } return parentFS } // initFileDescFromFeatureSet initializes editions related fields in fd based // on fs. If fs is nil it is assumed to be an empty featureset and all fields // will be initialized with the appropriate default. fd.L1.Edition must be set // before calling this function. func initFileDescFromFeatureSet(fd *filedesc.File, fs *descriptorpb.FeatureSet) { dfs := getFeatureSetFor(fd.L1.Edition) // initialize the featureset with the defaults fd.L1.EditionFeatures = mergeEditionFeatures(fd, dfs) // overwrite any options explicitly specified fd.L1.EditionFeatures = mergeEditionFeatures(fd, fs) }
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/reflect/protodesc/desc_validate.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/desc_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 protodesc import ( "strings" "unicode" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "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/types/descriptorpb" ) func validateEnumDeclarations(es []filedesc.Enum, eds []*descriptorpb.EnumDescriptorProto) error { for i, ed := range eds { e := &es[i] if err := e.L2.ReservedNames.CheckValid(); err != nil { return errors.New("enum %q reserved names has %v", e.FullName(), err) } if err := e.L2.ReservedRanges.CheckValid(); err != nil { return errors.New("enum %q reserved ranges has %v", e.FullName(), err) } if len(ed.GetValue()) == 0 { return errors.New("enum %q must contain at least one value declaration", e.FullName()) } allowAlias := ed.GetOptions().GetAllowAlias() foundAlias := false for i := 0; i < e.Values().Len(); i++ { v1 := e.Values().Get(i) if v2 := e.Values().ByNumber(v1.Number()); v1 != v2 { foundAlias = true if !allowAlias { return errors.New("enum %q has conflicting non-aliased values on number %d: %q with %q", e.FullName(), v1.Number(), v1.Name(), v2.Name()) } } } if allowAlias && !foundAlias { return errors.New("enum %q allows aliases, but none were found", e.FullName()) } if !e.IsClosed() { if v := e.Values().Get(0); v.Number() != 0 { return errors.New("enum %q using open semantics must have zero number for the first value", v.FullName()) } // Verify that value names in open enums do not conflict if the // case-insensitive prefix is removed. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:4991-5055 names := map[string]protoreflect.EnumValueDescriptor{} prefix := strings.Replace(strings.ToLower(string(e.Name())), "_", "", -1) for i := 0; i < e.Values().Len(); i++ { v1 := e.Values().Get(i) s := strs.EnumValueName(strs.TrimEnumPrefix(string(v1.Name()), prefix)) if v2, ok := names[s]; ok && v1.Number() != v2.Number() { return errors.New("enum %q using open semantics has conflict: %q with %q", e.FullName(), v1.Name(), v2.Name()) } names[s] = v1 } } for j, vd := range ed.GetValue() { v := &e.L2.Values.List[j] if vd.Number == nil { return errors.New("enum value %q must have a specified number", v.FullName()) } if e.L2.ReservedNames.Has(v.Name()) { return errors.New("enum value %q must not use reserved name", v.FullName()) } if e.L2.ReservedRanges.Has(v.Number()) { return errors.New("enum value %q must not use reserved number %d", v.FullName(), v.Number()) } } } return nil } func validateMessageDeclarations(file *filedesc.File, ms []filedesc.Message, mds []*descriptorpb.DescriptorProto) error { // There are a few limited exceptions only for proto3 isProto3 := file.L1.Edition == fromEditionProto(descriptorpb.Edition_EDITION_PROTO3) for i, md := range mds { m := &ms[i] // Handle the message descriptor itself. isMessageSet := md.GetOptions().GetMessageSetWireFormat() if err := m.L2.ReservedNames.CheckValid(); err != nil { return errors.New("message %q reserved names has %v", m.FullName(), err) } if err := m.L2.ReservedRanges.CheckValid(isMessageSet); err != nil { return errors.New("message %q reserved ranges has %v", m.FullName(), err) } if err := m.L2.ExtensionRanges.CheckValid(isMessageSet); err != nil { return errors.New("message %q extension ranges has %v", m.FullName(), err) } if err := (*filedesc.FieldRanges).CheckOverlap(&m.L2.ReservedRanges, &m.L2.ExtensionRanges); err != nil { return errors.New("message %q reserved and extension ranges has %v", m.FullName(), err) } for i := 0; i < m.Fields().Len(); i++ { f1 := m.Fields().Get(i) if f2 := m.Fields().ByNumber(f1.Number()); f1 != f2 { return errors.New("message %q has conflicting fields: %q with %q", m.FullName(), f1.Name(), f2.Name()) } } if isMessageSet && !flags.ProtoLegacy { return errors.New("message %q is a MessageSet, which is a legacy proto1 feature that is no longer supported", m.FullName()) } if isMessageSet && (isProto3 || m.Fields().Len() > 0 || m.ExtensionRanges().Len() == 0) { return errors.New("message %q is an invalid proto1 MessageSet", m.FullName()) } if isProto3 { if m.ExtensionRanges().Len() > 0 { return errors.New("message %q using proto3 semantics cannot have extension ranges", m.FullName()) } } for j, fd := range md.GetField() { f := &m.L2.Fields.List[j] if m.L2.ReservedNames.Has(f.Name()) { return errors.New("message field %q must not use reserved name", f.FullName()) } if !f.Number().IsValid() { return errors.New("message field %q has an invalid number: %d", f.FullName(), f.Number()) } if !f.Cardinality().IsValid() { return errors.New("message field %q has an invalid cardinality: %d", f.FullName(), f.Cardinality()) } if m.L2.ReservedRanges.Has(f.Number()) { return errors.New("message field %q must not use reserved number %d", f.FullName(), f.Number()) } if m.L2.ExtensionRanges.Has(f.Number()) { return errors.New("message field %q with number %d in extension range", f.FullName(), f.Number()) } if fd.Extendee != nil { return errors.New("message field %q may not have extendee: %q", f.FullName(), fd.GetExtendee()) } if f.L1.IsProto3Optional { if !isProto3 { return errors.New("message field %q under proto3 optional semantics must be specified in the proto3 syntax", f.FullName()) } if f.Cardinality() != protoreflect.Optional { return errors.New("message field %q under proto3 optional semantics must have optional cardinality", f.FullName()) } if f.ContainingOneof() != nil && f.ContainingOneof().Fields().Len() != 1 { return errors.New("message field %q under proto3 optional semantics must be within a single element oneof", f.FullName()) } } if f.IsPacked() && !isPackable(f) { return errors.New("message field %q is not packable", f.FullName()) } if err := checkValidGroup(file, f); err != nil { return errors.New("message field %q is an invalid group: %v", f.FullName(), err) } if err := checkValidMap(f); err != nil { return errors.New("message field %q is an invalid map: %v", f.FullName(), err) } if isProto3 { if f.Cardinality() == protoreflect.Required { return errors.New("message field %q using proto3 semantics cannot be required", f.FullName()) } if f.Enum() != nil && !f.Enum().IsPlaceholder() && f.Enum().IsClosed() { return errors.New("message field %q using proto3 semantics may only depend on open enums", f.FullName()) } } if f.Cardinality() == protoreflect.Optional && !f.HasPresence() && f.Enum() != nil && !f.Enum().IsPlaceholder() && f.Enum().IsClosed() { return errors.New("message field %q with implicit presence may only use open enums", f.FullName()) } } seenSynthetic := false // synthetic oneofs for proto3 optional must come after real oneofs for j := range md.GetOneofDecl() { o := &m.L2.Oneofs.List[j] if o.Fields().Len() == 0 { return errors.New("message oneof %q must contain at least one field declaration", o.FullName()) } if n := o.Fields().Len(); n-1 != (o.Fields().Get(n-1).Index() - o.Fields().Get(0).Index()) { return errors.New("message oneof %q must have consecutively declared fields", o.FullName()) } if o.IsSynthetic() { seenSynthetic = true continue } if !o.IsSynthetic() && seenSynthetic { return errors.New("message oneof %q must be declared before synthetic oneofs", o.FullName()) } for i := 0; i < o.Fields().Len(); i++ { f := o.Fields().Get(i) if f.Cardinality() != protoreflect.Optional { return errors.New("message field %q belongs in a oneof and must be optional", f.FullName()) } } } if err := validateEnumDeclarations(m.L1.Enums.List, md.GetEnumType()); err != nil { return err } if err := validateMessageDeclarations(file, m.L1.Messages.List, md.GetNestedType()); err != nil { return err } if err := validateExtensionDeclarations(file, m.L1.Extensions.List, md.GetExtension()); err != nil { return err } } return nil } func validateExtensionDeclarations(f *filedesc.File, xs []filedesc.Extension, xds []*descriptorpb.FieldDescriptorProto) error { for i, xd := range xds { x := &xs[i] // NOTE: Avoid using the IsValid method since extensions to MessageSet // may have a field number higher than normal. This check only verifies // that the number is not negative or reserved. We check again later // if we know that the extendee is definitely not a MessageSet. if n := x.Number(); n < 0 || (protowire.FirstReservedNumber <= n && n <= protowire.LastReservedNumber) { return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number()) } if !x.Cardinality().IsValid() || x.Cardinality() == protoreflect.Required { return errors.New("extension field %q has an invalid cardinality: %d", x.FullName(), x.Cardinality()) } if xd.JsonName != nil { // A bug in older versions of protoc would always populate the // "json_name" option for extensions when it is meaningless. // When it did so, it would always use the camel-cased field name. if xd.GetJsonName() != strs.JSONCamelCase(string(x.Name())) { return errors.New("extension field %q may not have an explicitly set JSON name: %q", x.FullName(), xd.GetJsonName()) } } if xd.OneofIndex != nil { return errors.New("extension field %q may not be part of a oneof", x.FullName()) } if md := x.ContainingMessage(); !md.IsPlaceholder() { if !md.ExtensionRanges().Has(x.Number()) { return errors.New("extension field %q extends %q with non-extension field number: %d", x.FullName(), md.FullName(), x.Number()) } isMessageSet := md.Options().(*descriptorpb.MessageOptions).GetMessageSetWireFormat() if isMessageSet && !isOptionalMessage(x) { return errors.New("extension field %q extends MessageSet and must be an optional message", x.FullName()) } if !isMessageSet && !x.Number().IsValid() { return errors.New("extension field %q has an invalid number: %d", x.FullName(), x.Number()) } } if x.IsPacked() && !isPackable(x) { return errors.New("extension field %q is not packable", x.FullName()) } if err := checkValidGroup(f, x); err != nil { return errors.New("extension field %q is an invalid group: %v", x.FullName(), err) } if md := x.Message(); md != nil && md.IsMapEntry() { return errors.New("extension field %q cannot be a map entry", x.FullName()) } if f.L1.Edition == fromEditionProto(descriptorpb.Edition_EDITION_PROTO3) { switch x.ContainingMessage().FullName() { case (*descriptorpb.FileOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.EnumOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.EnumValueOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.MessageOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.FieldOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.OneofOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.ExtensionRangeOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.ServiceOptions)(nil).ProtoReflect().Descriptor().FullName(): case (*descriptorpb.MethodOptions)(nil).ProtoReflect().Descriptor().FullName(): default: return errors.New("extension field %q cannot be declared in proto3 unless extended descriptor options", x.FullName()) } } } return nil } // isOptionalMessage reports whether this is an optional message. // If the kind is unknown, it is assumed to be a message. func isOptionalMessage(fd protoreflect.FieldDescriptor) bool { return (fd.Kind() == 0 || fd.Kind() == protoreflect.MessageKind) && fd.Cardinality() == protoreflect.Optional } // isPackable checks whether the pack option can be specified. func isPackable(fd protoreflect.FieldDescriptor) bool { switch fd.Kind() { case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind: return false } return fd.IsList() } // checkValidGroup reports whether fd is a valid group according to the same // rules that protoc imposes. func checkValidGroup(f *filedesc.File, fd protoreflect.FieldDescriptor) error { md := fd.Message() switch { case fd.Kind() != protoreflect.GroupKind: return nil case f.L1.Edition == fromEditionProto(descriptorpb.Edition_EDITION_PROTO3): return errors.New("invalid under proto3 semantics") case md == nil || md.IsPlaceholder(): return errors.New("message must be resolvable") } if f.L1.Edition < fromEditionProto(descriptorpb.Edition_EDITION_2023) { switch { case fd.FullName().Parent() != md.FullName().Parent(): return errors.New("message and field must be declared in the same scope") case !unicode.IsUpper(rune(md.Name()[0])): return errors.New("message name must start with an uppercase") case fd.Name() != protoreflect.Name(strings.ToLower(string(md.Name()))): return errors.New("field name must be lowercased form of the message name") } } return nil } // checkValidMap checks whether the field is a valid map according to the same // rules that protoc imposes. // See protoc v3.8.0: src/google/protobuf/descriptor.cc:6045-6115 func checkValidMap(fd protoreflect.FieldDescriptor) error { md := fd.Message() switch { case md == nil || !md.IsMapEntry(): return nil case fd.FullName().Parent() != md.FullName().Parent(): return errors.New("message and field must be declared in the same scope") case md.Name() != protoreflect.Name(strs.MapEntryName(string(fd.Name()))): return errors.New("incorrect implicit map entry name") case fd.Cardinality() != protoreflect.Repeated: return errors.New("field must be repeated") case md.Fields().Len() != 2: return errors.New("message must have exactly two fields") case md.ExtensionRanges().Len() > 0: return errors.New("message must not have any extension ranges") case md.Enums().Len()+md.Messages().Len()+md.Extensions().Len() > 0: return errors.New("message must not have any nested declarations") } kf := md.Fields().Get(0) vf := md.Fields().Get(1) switch { case kf.Name() != genid.MapEntry_Key_field_name || kf.Number() != genid.MapEntry_Key_field_number || kf.Cardinality() != protoreflect.Optional || kf.ContainingOneof() != nil || kf.HasDefault(): return errors.New("invalid key field") case vf.Name() != genid.MapEntry_Value_field_name || vf.Number() != genid.MapEntry_Value_field_number || vf.Cardinality() != protoreflect.Optional || vf.ContainingOneof() != nil || vf.HasDefault(): return errors.New("invalid value field") } switch kf.Kind() { case protoreflect.BoolKind: // bool case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: // int32 case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: // int64 case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: // uint32 case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: // uint64 case protoreflect.StringKind: // string default: return errors.New("invalid key kind: %v", kf.Kind()) } if e := vf.Enum(); e != nil && e.Values().Len() > 0 && e.Values().Get(0).Number() != 0 { return errors.New("map enum value must have zero number for the first value") } 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/reflect/protodesc/desc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/reflect/protodesc/desc.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 protodesc provides functionality for converting // FileDescriptorProto messages to/from [protoreflect.FileDescriptor] values. // // The google.protobuf.FileDescriptorProto is a protobuf message that describes // the type information for a .proto file in a form that is easily serializable. // The [protoreflect.FileDescriptor] is a more structured representation of // the FileDescriptorProto message where references and remote dependencies // can be directly followed. package protodesc import ( "strings" "google.golang.org/protobuf/internal/editionssupport" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" "google.golang.org/protobuf/types/descriptorpb" ) // Resolver is the resolver used by [NewFile] to resolve dependencies. // The enums and messages provided must belong to some parent file, // which is also registered. // // It is implemented by [protoregistry.Files]. type Resolver interface { FindFileByPath(string) (protoreflect.FileDescriptor, error) FindDescriptorByName(protoreflect.FullName) (protoreflect.Descriptor, error) } // FileOptions configures the construction of file descriptors. type FileOptions struct { pragma.NoUnkeyedLiterals // AllowUnresolvable configures New to permissively allow unresolvable // file, enum, or message dependencies. Unresolved dependencies are replaced // by placeholder equivalents. // // The following dependencies may be left unresolved: // • Resolving an imported file. // • Resolving the type for a message field or extension field. // If the kind of the field is unknown, then a placeholder is used for both // the Enum and Message accessors on the protoreflect.FieldDescriptor. // • Resolving an enum value set as the default for an optional enum field. // If unresolvable, the protoreflect.FieldDescriptor.Default is set to the // first value in the associated enum (or zero if the also enum dependency // is also unresolvable). The protoreflect.FieldDescriptor.DefaultEnumValue // is populated with a placeholder. // • Resolving the extended message type for an extension field. // • Resolving the input or output message type for a service method. // // If the unresolved dependency uses a relative name, // then the placeholder will contain an invalid FullName with a "*." prefix, // indicating that the starting prefix of the full name is unknown. AllowUnresolvable bool } // NewFile creates a new [protoreflect.FileDescriptor] from the provided // file descriptor message. See [FileOptions.New] for more information. func NewFile(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) { return FileOptions{}.New(fd, r) } // NewFiles creates a new [protoregistry.Files] from the provided // FileDescriptorSet message. See [FileOptions.NewFiles] for more information. func NewFiles(fd *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) { return FileOptions{}.NewFiles(fd) } // New creates a new [protoreflect.FileDescriptor] from the provided // file descriptor message. The file must represent a valid proto file according // to protobuf semantics. The returned descriptor is a deep copy of the input. // // Any imported files, enum types, or message types referenced in the file are // resolved using the provided registry. When looking up an import file path, // the path must be unique. The newly created file descriptor is not registered // back into the provided file registry. func (o FileOptions) New(fd *descriptorpb.FileDescriptorProto, r Resolver) (protoreflect.FileDescriptor, error) { if r == nil { r = (*protoregistry.Files)(nil) // empty resolver } // Handle the file descriptor content. f := &filedesc.File{L2: &filedesc.FileL2{}} switch fd.GetSyntax() { case "proto2", "": f.L1.Syntax = protoreflect.Proto2 f.L1.Edition = filedesc.EditionProto2 case "proto3": f.L1.Syntax = protoreflect.Proto3 f.L1.Edition = filedesc.EditionProto3 case "editions": f.L1.Syntax = protoreflect.Editions f.L1.Edition = fromEditionProto(fd.GetEdition()) default: return nil, errors.New("invalid syntax: %q", fd.GetSyntax()) } f.L1.Path = fd.GetName() if f.L1.Path == "" { return nil, errors.New("file path must be populated") } if f.L1.Syntax == protoreflect.Editions && (fd.GetEdition() < editionssupport.Minimum || fd.GetEdition() > editionssupport.Maximum) { // Allow cmd/protoc-gen-go/testdata to use any edition for easier // testing of upcoming edition features. if !strings.HasPrefix(fd.GetName(), "cmd/protoc-gen-go/testdata/") { return nil, errors.New("use of edition %v not yet supported by the Go Protobuf runtime", fd.GetEdition()) } } f.L1.Package = protoreflect.FullName(fd.GetPackage()) if !f.L1.Package.IsValid() && f.L1.Package != "" { return nil, errors.New("invalid package: %q", f.L1.Package) } if opts := fd.GetOptions(); opts != nil { opts = proto.Clone(opts).(*descriptorpb.FileOptions) f.L2.Options = func() protoreflect.ProtoMessage { return opts } } initFileDescFromFeatureSet(f, fd.GetOptions().GetFeatures()) f.L2.Imports = make(filedesc.FileImports, len(fd.GetDependency())) for _, i := range fd.GetPublicDependency() { if !(0 <= i && int(i) < len(f.L2.Imports)) || f.L2.Imports[i].IsPublic { return nil, errors.New("invalid or duplicate public import index: %d", i) } f.L2.Imports[i].IsPublic = true } imps := importSet{f.Path(): true} for i, path := range fd.GetDependency() { imp := &f.L2.Imports[i] f, err := r.FindFileByPath(path) if err == protoregistry.NotFound && o.AllowUnresolvable { f = filedesc.PlaceholderFile(path) } else if err != nil { return nil, errors.New("could not resolve import %q: %v", path, err) } imp.FileDescriptor = f if imps[imp.Path()] { return nil, errors.New("already imported %q", path) } imps[imp.Path()] = true } for i := range fd.GetDependency() { imp := &f.L2.Imports[i] imps.importPublic(imp.Imports()) } // Handle source locations. f.L2.Locations.File = f for _, loc := range fd.GetSourceCodeInfo().GetLocation() { var l protoreflect.SourceLocation // TODO: Validate that the path points to an actual declaration? l.Path = protoreflect.SourcePath(loc.GetPath()) s := loc.GetSpan() switch len(s) { case 3: l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[0]), int(s[2]) case 4: l.StartLine, l.StartColumn, l.EndLine, l.EndColumn = int(s[0]), int(s[1]), int(s[2]), int(s[3]) default: return nil, errors.New("invalid span: %v", s) } // TODO: Validate that the span information is sensible? // See https://github.com/protocolbuffers/protobuf/issues/6378. if false && (l.EndLine < l.StartLine || l.StartLine < 0 || l.StartColumn < 0 || l.EndColumn < 0 || (l.StartLine == l.EndLine && l.EndColumn <= l.StartColumn)) { return nil, errors.New("invalid span: %v", s) } l.LeadingDetachedComments = loc.GetLeadingDetachedComments() l.LeadingComments = loc.GetLeadingComments() l.TrailingComments = loc.GetTrailingComments() f.L2.Locations.List = append(f.L2.Locations.List, l) } // Step 1: Allocate and derive the names for all declarations. // This copies all fields from the descriptor proto except: // google.protobuf.FieldDescriptorProto.type_name // google.protobuf.FieldDescriptorProto.default_value // google.protobuf.FieldDescriptorProto.oneof_index // google.protobuf.FieldDescriptorProto.extendee // google.protobuf.MethodDescriptorProto.input // google.protobuf.MethodDescriptorProto.output var err error sb := new(strs.Builder) r1 := make(descsByName) if f.L1.Enums.List, err = r1.initEnumDeclarations(fd.GetEnumType(), f, sb); err != nil { return nil, err } if f.L1.Messages.List, err = r1.initMessagesDeclarations(fd.GetMessageType(), f, sb); err != nil { return nil, err } if f.L1.Extensions.List, err = r1.initExtensionDeclarations(fd.GetExtension(), f, sb); err != nil { return nil, err } if f.L1.Services.List, err = r1.initServiceDeclarations(fd.GetService(), f, sb); err != nil { return nil, err } // Step 2: Resolve every dependency reference not handled by step 1. r2 := &resolver{local: r1, remote: r, imports: imps, allowUnresolvable: o.AllowUnresolvable} if err := r2.resolveMessageDependencies(f.L1.Messages.List, fd.GetMessageType()); err != nil { return nil, err } if err := r2.resolveExtensionDependencies(f.L1.Extensions.List, fd.GetExtension()); err != nil { return nil, err } if err := r2.resolveServiceDependencies(f.L1.Services.List, fd.GetService()); err != nil { return nil, err } // Step 3: Validate every enum, message, and extension declaration. if err := validateEnumDeclarations(f.L1.Enums.List, fd.GetEnumType()); err != nil { return nil, err } if err := validateMessageDeclarations(f, f.L1.Messages.List, fd.GetMessageType()); err != nil { return nil, err } if err := validateExtensionDeclarations(f, f.L1.Extensions.List, fd.GetExtension()); err != nil { return nil, err } return f, nil } type importSet map[string]bool func (is importSet) importPublic(imps protoreflect.FileImports) { for i := 0; i < imps.Len(); i++ { if imp := imps.Get(i); imp.IsPublic { is[imp.Path()] = true is.importPublic(imp.Imports()) } } } // NewFiles creates a new [protoregistry.Files] from the provided // FileDescriptorSet message. The descriptor set must include only // valid files according to protobuf semantics. The returned descriptors // are a deep copy of the input. func (o FileOptions) NewFiles(fds *descriptorpb.FileDescriptorSet) (*protoregistry.Files, error) { files := make(map[string]*descriptorpb.FileDescriptorProto) for _, fd := range fds.File { if _, ok := files[fd.GetName()]; ok { return nil, errors.New("file appears multiple times: %q", fd.GetName()) } files[fd.GetName()] = fd } r := &protoregistry.Files{} for _, fd := range files { if err := o.addFileDeps(r, fd, files); err != nil { return nil, err } } return r, nil } func (o FileOptions) addFileDeps(r *protoregistry.Files, fd *descriptorpb.FileDescriptorProto, files map[string]*descriptorpb.FileDescriptorProto) error { // Set the entry to nil while descending into a file's dependencies to detect cycles. files[fd.GetName()] = nil for _, dep := range fd.Dependency { depfd, ok := files[dep] if depfd == nil { if ok { return errors.New("import cycle in file: %q", dep) } continue } if err := o.addFileDeps(r, depfd, files); err != nil { return err } } // Delete the entry once dependencies are processed. delete(files, fd.GetName()) f, err := o.New(fd, r) if err != nil { return err } return r.RegisterFile(f) }
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/filedesc/desc_init.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/desc_init.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 filedesc import ( "fmt" "sync" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // fileRaw is a data struct used when initializing a file descriptor from // a raw FileDescriptorProto. type fileRaw struct { builder Builder allEnums []Enum allMessages []Message allExtensions []Extension allServices []Service } func newRawFile(db Builder) *File { fd := &File{fileRaw: fileRaw{builder: db}} fd.initDecls(db.NumEnums, db.NumMessages, db.NumExtensions, db.NumServices) fd.unmarshalSeed(db.RawDescriptor) // Extended message targets are eagerly resolved since registration // needs this information at program init time. for i := range fd.allExtensions { xd := &fd.allExtensions[i] xd.L1.Extendee = fd.resolveMessageDependency(xd.L1.Extendee, listExtTargets, int32(i)) } fd.checkDecls() return fd } // initDecls pre-allocates slices for the exact number of enums, messages // (including map entries), extensions, and services declared in the proto file. // This is done to avoid regrowing the slice, which would change the address // for any previously seen declaration. // // The alloc methods "allocates" slices by pulling from the capacity. func (fd *File) initDecls(numEnums, numMessages, numExtensions, numServices int32) { fd.allEnums = make([]Enum, 0, numEnums) fd.allMessages = make([]Message, 0, numMessages) fd.allExtensions = make([]Extension, 0, numExtensions) fd.allServices = make([]Service, 0, numServices) } func (fd *File) allocEnums(n int) []Enum { total := len(fd.allEnums) es := fd.allEnums[total : total+n] fd.allEnums = fd.allEnums[:total+n] return es } func (fd *File) allocMessages(n int) []Message { total := len(fd.allMessages) ms := fd.allMessages[total : total+n] fd.allMessages = fd.allMessages[:total+n] return ms } func (fd *File) allocExtensions(n int) []Extension { total := len(fd.allExtensions) xs := fd.allExtensions[total : total+n] fd.allExtensions = fd.allExtensions[:total+n] return xs } func (fd *File) allocServices(n int) []Service { total := len(fd.allServices) xs := fd.allServices[total : total+n] fd.allServices = fd.allServices[:total+n] return xs } // checkDecls performs a sanity check that the expected number of expected // declarations matches the number that were found in the descriptor proto. func (fd *File) checkDecls() { switch { case len(fd.allEnums) != cap(fd.allEnums): case len(fd.allMessages) != cap(fd.allMessages): case len(fd.allExtensions) != cap(fd.allExtensions): case len(fd.allServices) != cap(fd.allServices): default: return } panic("mismatching cardinality") } func (fd *File) unmarshalSeed(b []byte) { sb := getBuilder() defer putBuilder(sb) var prevField protoreflect.FieldNumber var numEnums, numMessages, numExtensions, numServices int var posEnums, posMessages, posExtensions, posServices int var options []byte b0 := b for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FileDescriptorProto_Syntax_field_number: switch string(v) { case "proto2": fd.L1.Syntax = protoreflect.Proto2 fd.L1.Edition = EditionProto2 case "proto3": fd.L1.Syntax = protoreflect.Proto3 fd.L1.Edition = EditionProto3 case "editions": fd.L1.Syntax = protoreflect.Editions default: panic("invalid syntax") } case genid.FileDescriptorProto_Name_field_number: fd.L1.Path = sb.MakeString(v) case genid.FileDescriptorProto_Package_field_number: fd.L1.Package = protoreflect.FullName(sb.MakeString(v)) case genid.FileDescriptorProto_Options_field_number: options = v case genid.FileDescriptorProto_EnumType_field_number: if prevField != genid.FileDescriptorProto_EnumType_field_number { if numEnums > 0 { panic("non-contiguous repeated field") } posEnums = len(b0) - len(b) - n - m } numEnums++ case genid.FileDescriptorProto_MessageType_field_number: if prevField != genid.FileDescriptorProto_MessageType_field_number { if numMessages > 0 { panic("non-contiguous repeated field") } posMessages = len(b0) - len(b) - n - m } numMessages++ case genid.FileDescriptorProto_Extension_field_number: if prevField != genid.FileDescriptorProto_Extension_field_number { if numExtensions > 0 { panic("non-contiguous repeated field") } posExtensions = len(b0) - len(b) - n - m } numExtensions++ case genid.FileDescriptorProto_Service_field_number: if prevField != genid.FileDescriptorProto_Service_field_number { if numServices > 0 { panic("non-contiguous repeated field") } posServices = len(b0) - len(b) - n - m } numServices++ } prevField = num case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FileDescriptorProto_Edition_field_number: fd.L1.Edition = Edition(v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] prevField = -1 // ignore known field numbers of unknown wire type } } // If syntax is missing, it is assumed to be proto2. if fd.L1.Syntax == 0 { fd.L1.Syntax = protoreflect.Proto2 fd.L1.Edition = EditionProto2 } fd.L1.EditionFeatures = getFeaturesFor(fd.L1.Edition) // Parse editions features from options if any if options != nil { fd.unmarshalSeedOptions(options) } // Must allocate all declarations before parsing each descriptor type // to ensure we handled all descriptors in "flattened ordering". if numEnums > 0 { fd.L1.Enums.List = fd.allocEnums(numEnums) } if numMessages > 0 { fd.L1.Messages.List = fd.allocMessages(numMessages) } if numExtensions > 0 { fd.L1.Extensions.List = fd.allocExtensions(numExtensions) } if numServices > 0 { fd.L1.Services.List = fd.allocServices(numServices) } if numEnums > 0 { b := b0[posEnums:] for i := range fd.L1.Enums.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) fd.L1.Enums.List[i].unmarshalSeed(v, sb, fd, fd, i) b = b[n+m:] } } if numMessages > 0 { b := b0[posMessages:] for i := range fd.L1.Messages.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) fd.L1.Messages.List[i].unmarshalSeed(v, sb, fd, fd, i) b = b[n+m:] } } if numExtensions > 0 { b := b0[posExtensions:] for i := range fd.L1.Extensions.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) fd.L1.Extensions.List[i].unmarshalSeed(v, sb, fd, fd, i) b = b[n+m:] } } if numServices > 0 { b := b0[posServices:] for i := range fd.L1.Services.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) fd.L1.Services.List[i].unmarshalSeed(v, sb, fd, fd, i) b = b[n+m:] } } } func (fd *File) unmarshalSeedOptions(b []byte) { for b := b; len(b) > 0; { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FileOptions_Features_field_number: if fd.Syntax() != protoreflect.Editions { panic(fmt.Sprintf("invalid descriptor: using edition features in a proto with syntax %s", fd.Syntax())) } fd.L1.EditionFeatures = unmarshalFeatureSet(v, fd.L1.EditionFeatures) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func (ed *Enum) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { ed.L0.ParentFile = pf ed.L0.Parent = pd ed.L0.Index = i ed.L1.EditionFeatures = featuresFromParentDesc(ed.Parent()) var numValues int for b := b; len(b) > 0; { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.EnumDescriptorProto_Name_field_number: ed.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.EnumDescriptorProto_Value_field_number: numValues++ } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } // Only construct enum value descriptors for top-level enums since // they are needed for registration. if pd != pf { return } ed.L1.eagerValues = true ed.L2 = new(EnumL2) ed.L2.Values.List = make([]EnumValue, numValues) for i := 0; len(b) > 0; { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.EnumDescriptorProto_Value_field_number: ed.L2.Values.List[i].unmarshalFull(v, sb, pf, ed, i) i++ } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func (md *Message) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { md.L0.ParentFile = pf md.L0.Parent = pd md.L0.Index = i md.L1.EditionFeatures = featuresFromParentDesc(md.Parent()) var prevField protoreflect.FieldNumber var numEnums, numMessages, numExtensions int var posEnums, posMessages, posExtensions int b0 := b for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.DescriptorProto_Name_field_number: md.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.DescriptorProto_EnumType_field_number: if prevField != genid.DescriptorProto_EnumType_field_number { if numEnums > 0 { panic("non-contiguous repeated field") } posEnums = len(b0) - len(b) - n - m } numEnums++ case genid.DescriptorProto_NestedType_field_number: if prevField != genid.DescriptorProto_NestedType_field_number { if numMessages > 0 { panic("non-contiguous repeated field") } posMessages = len(b0) - len(b) - n - m } numMessages++ case genid.DescriptorProto_Extension_field_number: if prevField != genid.DescriptorProto_Extension_field_number { if numExtensions > 0 { panic("non-contiguous repeated field") } posExtensions = len(b0) - len(b) - n - m } numExtensions++ case genid.DescriptorProto_Options_field_number: md.unmarshalSeedOptions(v) } prevField = num default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] prevField = -1 // ignore known field numbers of unknown wire type } } // Must allocate all declarations before parsing each descriptor type // to ensure we handled all descriptors in "flattened ordering". if numEnums > 0 { md.L1.Enums.List = pf.allocEnums(numEnums) } if numMessages > 0 { md.L1.Messages.List = pf.allocMessages(numMessages) } if numExtensions > 0 { md.L1.Extensions.List = pf.allocExtensions(numExtensions) } if numEnums > 0 { b := b0[posEnums:] for i := range md.L1.Enums.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) md.L1.Enums.List[i].unmarshalSeed(v, sb, pf, md, i) b = b[n+m:] } } if numMessages > 0 { b := b0[posMessages:] for i := range md.L1.Messages.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) md.L1.Messages.List[i].unmarshalSeed(v, sb, pf, md, i) b = b[n+m:] } } if numExtensions > 0 { b := b0[posExtensions:] for i := range md.L1.Extensions.List { _, n := protowire.ConsumeVarint(b) v, m := protowire.ConsumeBytes(b[n:]) md.L1.Extensions.List[i].unmarshalSeed(v, sb, pf, md, i) b = b[n+m:] } } } func (md *Message) unmarshalSeedOptions(b []byte) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.MessageOptions_MapEntry_field_number: md.L1.IsMapEntry = protowire.DecodeBool(v) case genid.MessageOptions_MessageSetWireFormat_field_number: md.L1.IsMessageSet = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.MessageOptions_Features_field_number: md.L1.EditionFeatures = unmarshalFeatureSet(v, md.L1.EditionFeatures) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func (xd *Extension) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { xd.L0.ParentFile = pf xd.L0.Parent = pd xd.L0.Index = i xd.L1.EditionFeatures = featuresFromParentDesc(pd) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FieldDescriptorProto_Number_field_number: xd.L1.Number = protoreflect.FieldNumber(v) case genid.FieldDescriptorProto_Label_field_number: xd.L1.Cardinality = protoreflect.Cardinality(v) case genid.FieldDescriptorProto_Type_field_number: xd.L1.Kind = protoreflect.Kind(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FieldDescriptorProto_Name_field_number: xd.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.FieldDescriptorProto_Extendee_field_number: xd.L1.Extendee = PlaceholderMessage(makeFullName(sb, v)) case genid.FieldDescriptorProto_Options_field_number: xd.unmarshalOptions(v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if xd.L1.Kind == protoreflect.MessageKind && xd.L1.EditionFeatures.IsDelimitedEncoded { xd.L1.Kind = protoreflect.GroupKind } } func (xd *Extension) unmarshalOptions(b []byte) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FieldOptions_Packed_field_number: xd.L1.EditionFeatures.IsPacked = protowire.DecodeBool(v) case genid.FieldOptions_Lazy_field_number: xd.L1.IsLazy = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FieldOptions_Features_field_number: xd.L1.EditionFeatures = unmarshalFeatureSet(v, xd.L1.EditionFeatures) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func (sd *Service) unmarshalSeed(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { sd.L0.ParentFile = pf sd.L0.Parent = pd sd.L0.Index = i for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.ServiceDescriptorProto_Name_field_number: sd.L0.FullName = appendFullName(sb, pd.FullName(), v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } var nameBuilderPool = sync.Pool{ New: func() any { return new(strs.Builder) }, } func getBuilder() *strs.Builder { return nameBuilderPool.Get().(*strs.Builder) } func putBuilder(b *strs.Builder) { nameBuilderPool.Put(b) } // makeFullName converts b to a protoreflect.FullName, // where b must start with a leading dot. func makeFullName(sb *strs.Builder, b []byte) protoreflect.FullName { if len(b) == 0 || b[0] != '.' { panic("name reference must be fully qualified") } return protoreflect.FullName(sb.MakeString(b[1:])) } func appendFullName(sb *strs.Builder, prefix protoreflect.FullName, suffix []byte) protoreflect.FullName { return sb.AppendFullName(prefix, protoreflect.Name(strs.UnsafeString(suffix))) }
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/filedesc/desc_list.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/desc_list.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 filedesc import ( "fmt" "math" "sort" "sync" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/descfmt" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) type FileImports []protoreflect.FileImport func (p *FileImports) Len() int { return len(*p) } func (p *FileImports) Get(i int) protoreflect.FileImport { return (*p)[i] } func (p *FileImports) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *FileImports) ProtoInternal(pragma.DoNotImplement) {} type Names struct { List []protoreflect.Name once sync.Once has map[protoreflect.Name]int // protected by once } func (p *Names) Len() int { return len(p.List) } func (p *Names) Get(i int) protoreflect.Name { return p.List[i] } func (p *Names) Has(s protoreflect.Name) bool { return p.lazyInit().has[s] > 0 } func (p *Names) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Names) ProtoInternal(pragma.DoNotImplement) {} func (p *Names) lazyInit() *Names { p.once.Do(func() { if len(p.List) > 0 { p.has = make(map[protoreflect.Name]int, len(p.List)) for _, s := range p.List { p.has[s] = p.has[s] + 1 } } }) return p } // CheckValid reports any errors with the set of names with an error message // that completes the sentence: "ranges is invalid because it has ..." func (p *Names) CheckValid() error { for s, n := range p.lazyInit().has { switch { case n > 1: return errors.New("duplicate name: %q", s) case false && !s.IsValid(): // NOTE: The C++ implementation does not validate the identifier. // See https://github.com/protocolbuffers/protobuf/issues/6335. return errors.New("invalid name: %q", s) } } return nil } type EnumRanges struct { List [][2]protoreflect.EnumNumber // start inclusive; end inclusive once sync.Once sorted [][2]protoreflect.EnumNumber // protected by once } func (p *EnumRanges) Len() int { return len(p.List) } func (p *EnumRanges) Get(i int) [2]protoreflect.EnumNumber { return p.List[i] } func (p *EnumRanges) Has(n protoreflect.EnumNumber) bool { for ls := p.lazyInit().sorted; len(ls) > 0; { i := len(ls) / 2 switch r := enumRange(ls[i]); { case n < r.Start(): ls = ls[:i] // search lower case n > r.End(): ls = ls[i+1:] // search upper default: return true } } return false } func (p *EnumRanges) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *EnumRanges) ProtoInternal(pragma.DoNotImplement) {} func (p *EnumRanges) lazyInit() *EnumRanges { p.once.Do(func() { p.sorted = append(p.sorted, p.List...) sort.Slice(p.sorted, func(i, j int) bool { return p.sorted[i][0] < p.sorted[j][0] }) }) return p } // CheckValid reports any errors with the set of names with an error message // that completes the sentence: "ranges is invalid because it has ..." func (p *EnumRanges) CheckValid() error { var rp enumRange for i, r := range p.lazyInit().sorted { r := enumRange(r) switch { case !(r.Start() <= r.End()): return errors.New("invalid range: %v", r) case !(rp.End() < r.Start()) && i > 0: return errors.New("overlapping ranges: %v with %v", rp, r) } rp = r } return nil } type enumRange [2]protoreflect.EnumNumber func (r enumRange) Start() protoreflect.EnumNumber { return r[0] } // inclusive func (r enumRange) End() protoreflect.EnumNumber { return r[1] } // inclusive func (r enumRange) String() string { if r.Start() == r.End() { return fmt.Sprintf("%d", r.Start()) } return fmt.Sprintf("%d to %d", r.Start(), r.End()) } type FieldRanges struct { List [][2]protoreflect.FieldNumber // start inclusive; end exclusive once sync.Once sorted [][2]protoreflect.FieldNumber // protected by once } func (p *FieldRanges) Len() int { return len(p.List) } func (p *FieldRanges) Get(i int) [2]protoreflect.FieldNumber { return p.List[i] } func (p *FieldRanges) Has(n protoreflect.FieldNumber) bool { for ls := p.lazyInit().sorted; len(ls) > 0; { i := len(ls) / 2 switch r := fieldRange(ls[i]); { case n < r.Start(): ls = ls[:i] // search lower case n > r.End(): ls = ls[i+1:] // search upper default: return true } } return false } func (p *FieldRanges) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *FieldRanges) ProtoInternal(pragma.DoNotImplement) {} func (p *FieldRanges) lazyInit() *FieldRanges { p.once.Do(func() { p.sorted = append(p.sorted, p.List...) sort.Slice(p.sorted, func(i, j int) bool { return p.sorted[i][0] < p.sorted[j][0] }) }) return p } // CheckValid reports any errors with the set of ranges with an error message // that completes the sentence: "ranges is invalid because it has ..." func (p *FieldRanges) CheckValid(isMessageSet bool) error { var rp fieldRange for i, r := range p.lazyInit().sorted { r := fieldRange(r) switch { case !isValidFieldNumber(r.Start(), isMessageSet): return errors.New("invalid field number: %d", r.Start()) case !isValidFieldNumber(r.End(), isMessageSet): return errors.New("invalid field number: %d", r.End()) case !(r.Start() <= r.End()): return errors.New("invalid range: %v", r) case !(rp.End() < r.Start()) && i > 0: return errors.New("overlapping ranges: %v with %v", rp, r) } rp = r } return nil } // isValidFieldNumber reports whether the field number is valid. // Unlike the FieldNumber.IsValid method, it allows ranges that cover the // reserved number range. func isValidFieldNumber(n protoreflect.FieldNumber, isMessageSet bool) bool { return protowire.MinValidNumber <= n && (n <= protowire.MaxValidNumber || isMessageSet) } // CheckOverlap reports an error if p and q overlap. func (p *FieldRanges) CheckOverlap(q *FieldRanges) error { rps := p.lazyInit().sorted rqs := q.lazyInit().sorted for pi, qi := 0, 0; pi < len(rps) && qi < len(rqs); { rp := fieldRange(rps[pi]) rq := fieldRange(rqs[qi]) if !(rp.End() < rq.Start() || rq.End() < rp.Start()) { return errors.New("overlapping ranges: %v with %v", rp, rq) } if rp.Start() < rq.Start() { pi++ } else { qi++ } } return nil } type fieldRange [2]protoreflect.FieldNumber func (r fieldRange) Start() protoreflect.FieldNumber { return r[0] } // inclusive func (r fieldRange) End() protoreflect.FieldNumber { return r[1] - 1 } // inclusive func (r fieldRange) String() string { if r.Start() == r.End() { return fmt.Sprintf("%d", r.Start()) } return fmt.Sprintf("%d to %d", r.Start(), r.End()) } type FieldNumbers struct { List []protoreflect.FieldNumber once sync.Once has map[protoreflect.FieldNumber]struct{} // protected by once } func (p *FieldNumbers) Len() int { return len(p.List) } func (p *FieldNumbers) Get(i int) protoreflect.FieldNumber { return p.List[i] } func (p *FieldNumbers) Has(n protoreflect.FieldNumber) bool { p.once.Do(func() { if len(p.List) > 0 { p.has = make(map[protoreflect.FieldNumber]struct{}, len(p.List)) for _, n := range p.List { p.has[n] = struct{}{} } } }) _, ok := p.has[n] return ok } func (p *FieldNumbers) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *FieldNumbers) ProtoInternal(pragma.DoNotImplement) {} type OneofFields struct { List []protoreflect.FieldDescriptor once sync.Once byName map[protoreflect.Name]protoreflect.FieldDescriptor // protected by once byJSON map[string]protoreflect.FieldDescriptor // protected by once byText map[string]protoreflect.FieldDescriptor // protected by once byNum map[protoreflect.FieldNumber]protoreflect.FieldDescriptor // protected by once } func (p *OneofFields) Len() int { return len(p.List) } func (p *OneofFields) Get(i int) protoreflect.FieldDescriptor { return p.List[i] } func (p *OneofFields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor { return p.lazyInit().byName[s] } func (p *OneofFields) ByJSONName(s string) protoreflect.FieldDescriptor { return p.lazyInit().byJSON[s] } func (p *OneofFields) ByTextName(s string) protoreflect.FieldDescriptor { return p.lazyInit().byText[s] } func (p *OneofFields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor { return p.lazyInit().byNum[n] } func (p *OneofFields) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *OneofFields) ProtoInternal(pragma.DoNotImplement) {} func (p *OneofFields) lazyInit() *OneofFields { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]protoreflect.FieldDescriptor, len(p.List)) p.byJSON = make(map[string]protoreflect.FieldDescriptor, len(p.List)) p.byText = make(map[string]protoreflect.FieldDescriptor, len(p.List)) p.byNum = make(map[protoreflect.FieldNumber]protoreflect.FieldDescriptor, len(p.List)) for _, f := range p.List { // Field names and numbers are guaranteed to be unique. p.byName[f.Name()] = f p.byJSON[f.JSONName()] = f p.byText[f.TextName()] = f p.byNum[f.Number()] = f } } }) return p } type SourceLocations struct { // List is a list of SourceLocations. // The SourceLocation.Next field does not need to be populated // as it will be lazily populated upon first need. List []protoreflect.SourceLocation // File is the parent file descriptor that these locations are relative to. // If non-nil, ByDescriptor verifies that the provided descriptor // is a child of this file descriptor. File protoreflect.FileDescriptor once sync.Once byPath map[pathKey]int } func (p *SourceLocations) Len() int { return len(p.List) } func (p *SourceLocations) Get(i int) protoreflect.SourceLocation { return p.lazyInit().List[i] } func (p *SourceLocations) byKey(k pathKey) protoreflect.SourceLocation { if i, ok := p.lazyInit().byPath[k]; ok { return p.List[i] } return protoreflect.SourceLocation{} } func (p *SourceLocations) ByPath(path protoreflect.SourcePath) protoreflect.SourceLocation { return p.byKey(newPathKey(path)) } func (p *SourceLocations) ByDescriptor(desc protoreflect.Descriptor) protoreflect.SourceLocation { if p.File != nil && desc != nil && p.File != desc.ParentFile() { return protoreflect.SourceLocation{} // mismatching parent files } var pathArr [16]int32 path := pathArr[:0] for { switch desc.(type) { case protoreflect.FileDescriptor: // Reverse the path since it was constructed in reverse. for i, j := 0, len(path)-1; i < j; i, j = i+1, j-1 { path[i], path[j] = path[j], path[i] } return p.byKey(newPathKey(path)) case protoreflect.MessageDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.FileDescriptor: path = append(path, int32(genid.FileDescriptorProto_MessageType_field_number)) case protoreflect.MessageDescriptor: path = append(path, int32(genid.DescriptorProto_NestedType_field_number)) default: return protoreflect.SourceLocation{} } case protoreflect.FieldDescriptor: isExtension := desc.(protoreflect.FieldDescriptor).IsExtension() path = append(path, int32(desc.Index())) desc = desc.Parent() if isExtension { switch desc.(type) { case protoreflect.FileDescriptor: path = append(path, int32(genid.FileDescriptorProto_Extension_field_number)) case protoreflect.MessageDescriptor: path = append(path, int32(genid.DescriptorProto_Extension_field_number)) default: return protoreflect.SourceLocation{} } } else { switch desc.(type) { case protoreflect.MessageDescriptor: path = append(path, int32(genid.DescriptorProto_Field_field_number)) default: return protoreflect.SourceLocation{} } } case protoreflect.OneofDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.MessageDescriptor: path = append(path, int32(genid.DescriptorProto_OneofDecl_field_number)) default: return protoreflect.SourceLocation{} } case protoreflect.EnumDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.FileDescriptor: path = append(path, int32(genid.FileDescriptorProto_EnumType_field_number)) case protoreflect.MessageDescriptor: path = append(path, int32(genid.DescriptorProto_EnumType_field_number)) default: return protoreflect.SourceLocation{} } case protoreflect.EnumValueDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.EnumDescriptor: path = append(path, int32(genid.EnumDescriptorProto_Value_field_number)) default: return protoreflect.SourceLocation{} } case protoreflect.ServiceDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.FileDescriptor: path = append(path, int32(genid.FileDescriptorProto_Service_field_number)) default: return protoreflect.SourceLocation{} } case protoreflect.MethodDescriptor: path = append(path, int32(desc.Index())) desc = desc.Parent() switch desc.(type) { case protoreflect.ServiceDescriptor: path = append(path, int32(genid.ServiceDescriptorProto_Method_field_number)) default: return protoreflect.SourceLocation{} } default: return protoreflect.SourceLocation{} } } } func (p *SourceLocations) lazyInit() *SourceLocations { p.once.Do(func() { if len(p.List) > 0 { // Collect all the indexes for a given path. pathIdxs := make(map[pathKey][]int, len(p.List)) for i, l := range p.List { k := newPathKey(l.Path) pathIdxs[k] = append(pathIdxs[k], i) } // Update the next index for all locations. p.byPath = make(map[pathKey]int, len(p.List)) for k, idxs := range pathIdxs { for i := 0; i < len(idxs)-1; i++ { p.List[idxs[i]].Next = idxs[i+1] } p.List[idxs[len(idxs)-1]].Next = 0 p.byPath[k] = idxs[0] // record the first location for this path } } }) return p } func (p *SourceLocations) ProtoInternal(pragma.DoNotImplement) {} // pathKey is a comparable representation of protoreflect.SourcePath. type pathKey struct { arr [16]uint8 // first n-1 path segments; last element is the length str string // used if the path does not fit in arr } func newPathKey(p protoreflect.SourcePath) (k pathKey) { if len(p) < len(k.arr) { for i, ps := range p { if ps < 0 || math.MaxUint8 <= ps { return pathKey{str: p.String()} } k.arr[i] = uint8(ps) } k.arr[len(k.arr)-1] = uint8(len(p)) return k } return pathKey{str: p.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/filedesc/placeholder.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/placeholder.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 filedesc import ( "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) var ( emptyNames = new(Names) emptyEnumRanges = new(EnumRanges) emptyFieldRanges = new(FieldRanges) emptyFieldNumbers = new(FieldNumbers) emptySourceLocations = new(SourceLocations) emptyFiles = new(FileImports) emptyMessages = new(Messages) emptyFields = new(Fields) emptyOneofs = new(Oneofs) emptyEnums = new(Enums) emptyEnumValues = new(EnumValues) emptyExtensions = new(Extensions) emptyServices = new(Services) ) // PlaceholderFile is a placeholder, representing only the file path. type PlaceholderFile string func (f PlaceholderFile) ParentFile() protoreflect.FileDescriptor { return f } func (f PlaceholderFile) Parent() protoreflect.Descriptor { return nil } func (f PlaceholderFile) Index() int { return 0 } func (f PlaceholderFile) Syntax() protoreflect.Syntax { return 0 } func (f PlaceholderFile) Name() protoreflect.Name { return "" } func (f PlaceholderFile) FullName() protoreflect.FullName { return "" } func (f PlaceholderFile) IsPlaceholder() bool { return true } func (f PlaceholderFile) Options() protoreflect.ProtoMessage { return descopts.File } func (f PlaceholderFile) Path() string { return string(f) } func (f PlaceholderFile) Package() protoreflect.FullName { return "" } func (f PlaceholderFile) Imports() protoreflect.FileImports { return emptyFiles } func (f PlaceholderFile) Messages() protoreflect.MessageDescriptors { return emptyMessages } func (f PlaceholderFile) Enums() protoreflect.EnumDescriptors { return emptyEnums } func (f PlaceholderFile) Extensions() protoreflect.ExtensionDescriptors { return emptyExtensions } func (f PlaceholderFile) Services() protoreflect.ServiceDescriptors { return emptyServices } func (f PlaceholderFile) SourceLocations() protoreflect.SourceLocations { return emptySourceLocations } func (f PlaceholderFile) ProtoType(protoreflect.FileDescriptor) { return } func (f PlaceholderFile) ProtoInternal(pragma.DoNotImplement) { return } // PlaceholderEnum is a placeholder, representing only the full name. type PlaceholderEnum protoreflect.FullName func (e PlaceholderEnum) ParentFile() protoreflect.FileDescriptor { return nil } func (e PlaceholderEnum) Parent() protoreflect.Descriptor { return nil } func (e PlaceholderEnum) Index() int { return 0 } func (e PlaceholderEnum) Syntax() protoreflect.Syntax { return 0 } func (e PlaceholderEnum) Name() protoreflect.Name { return protoreflect.FullName(e).Name() } func (e PlaceholderEnum) FullName() protoreflect.FullName { return protoreflect.FullName(e) } func (e PlaceholderEnum) IsPlaceholder() bool { return true } func (e PlaceholderEnum) Options() protoreflect.ProtoMessage { return descopts.Enum } func (e PlaceholderEnum) Values() protoreflect.EnumValueDescriptors { return emptyEnumValues } func (e PlaceholderEnum) ReservedNames() protoreflect.Names { return emptyNames } func (e PlaceholderEnum) ReservedRanges() protoreflect.EnumRanges { return emptyEnumRanges } func (e PlaceholderEnum) IsClosed() bool { return false } func (e PlaceholderEnum) ProtoType(protoreflect.EnumDescriptor) { return } func (e PlaceholderEnum) ProtoInternal(pragma.DoNotImplement) { return } // PlaceholderEnumValue is a placeholder, representing only the full name. type PlaceholderEnumValue protoreflect.FullName func (e PlaceholderEnumValue) ParentFile() protoreflect.FileDescriptor { return nil } func (e PlaceholderEnumValue) Parent() protoreflect.Descriptor { return nil } func (e PlaceholderEnumValue) Index() int { return 0 } func (e PlaceholderEnumValue) Syntax() protoreflect.Syntax { return 0 } func (e PlaceholderEnumValue) Name() protoreflect.Name { return protoreflect.FullName(e).Name() } func (e PlaceholderEnumValue) FullName() protoreflect.FullName { return protoreflect.FullName(e) } func (e PlaceholderEnumValue) IsPlaceholder() bool { return true } func (e PlaceholderEnumValue) Options() protoreflect.ProtoMessage { return descopts.EnumValue } func (e PlaceholderEnumValue) Number() protoreflect.EnumNumber { return 0 } func (e PlaceholderEnumValue) ProtoType(protoreflect.EnumValueDescriptor) { return } func (e PlaceholderEnumValue) ProtoInternal(pragma.DoNotImplement) { return } // PlaceholderMessage is a placeholder, representing only the full name. type PlaceholderMessage protoreflect.FullName func (m PlaceholderMessage) ParentFile() protoreflect.FileDescriptor { return nil } func (m PlaceholderMessage) Parent() protoreflect.Descriptor { return nil } func (m PlaceholderMessage) Index() int { return 0 } func (m PlaceholderMessage) Syntax() protoreflect.Syntax { return 0 } func (m PlaceholderMessage) Name() protoreflect.Name { return protoreflect.FullName(m).Name() } func (m PlaceholderMessage) FullName() protoreflect.FullName { return protoreflect.FullName(m) } func (m PlaceholderMessage) IsPlaceholder() bool { return true } func (m PlaceholderMessage) Options() protoreflect.ProtoMessage { return descopts.Message } func (m PlaceholderMessage) IsMapEntry() bool { return false } func (m PlaceholderMessage) Fields() protoreflect.FieldDescriptors { return emptyFields } func (m PlaceholderMessage) Oneofs() protoreflect.OneofDescriptors { return emptyOneofs } func (m PlaceholderMessage) ReservedNames() protoreflect.Names { return emptyNames } func (m PlaceholderMessage) ReservedRanges() protoreflect.FieldRanges { return emptyFieldRanges } func (m PlaceholderMessage) RequiredNumbers() protoreflect.FieldNumbers { return emptyFieldNumbers } func (m PlaceholderMessage) ExtensionRanges() protoreflect.FieldRanges { return emptyFieldRanges } func (m PlaceholderMessage) ExtensionRangeOptions(int) protoreflect.ProtoMessage { panic("index out of range") } func (m PlaceholderMessage) Messages() protoreflect.MessageDescriptors { return emptyMessages } func (m PlaceholderMessage) Enums() protoreflect.EnumDescriptors { return emptyEnums } func (m PlaceholderMessage) Extensions() protoreflect.ExtensionDescriptors { return emptyExtensions } func (m PlaceholderMessage) ProtoType(protoreflect.MessageDescriptor) { return } func (m PlaceholderMessage) 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/filedesc/desc_lazy.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/desc_lazy.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 filedesc import ( "reflect" "sync" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/reflect/protoreflect" ) func (fd *File) lazyRawInit() { fd.unmarshalFull(fd.builder.RawDescriptor) fd.resolveMessages() fd.resolveExtensions() fd.resolveServices() } func (file *File) resolveMessages() { var depIdx int32 for i := range file.allMessages { md := &file.allMessages[i] // Resolve message field dependencies. for j := range md.L2.Fields.List { fd := &md.L2.Fields.List[j] // Resolve message field dependency. switch fd.L1.Kind { case protoreflect.EnumKind: fd.L1.Enum = file.resolveEnumDependency(fd.L1.Enum, listFieldDeps, depIdx) depIdx++ case protoreflect.MessageKind, protoreflect.GroupKind: fd.L1.Message = file.resolveMessageDependency(fd.L1.Message, listFieldDeps, depIdx) depIdx++ if fd.L1.Kind == protoreflect.GroupKind && (fd.IsMap() || fd.IsMapEntry()) { // A map field might inherit delimited encoding from a file-wide default feature. // But maps never actually use delimited encoding. (At least for now...) fd.L1.Kind = protoreflect.MessageKind } } // Default is resolved here since it depends on Enum being resolved. if v := fd.L1.Default.val; v.IsValid() { fd.L1.Default = unmarshalDefault(v.Bytes(), fd.L1.Kind, file, fd.L1.Enum) } } } } func (file *File) resolveExtensions() { var depIdx int32 for i := range file.allExtensions { xd := &file.allExtensions[i] // Resolve extension field dependency. switch xd.L1.Kind { case protoreflect.EnumKind: xd.L2.Enum = file.resolveEnumDependency(xd.L2.Enum, listExtDeps, depIdx) depIdx++ case protoreflect.MessageKind, protoreflect.GroupKind: xd.L2.Message = file.resolveMessageDependency(xd.L2.Message, listExtDeps, depIdx) depIdx++ } // Default is resolved here since it depends on Enum being resolved. if v := xd.L2.Default.val; v.IsValid() { xd.L2.Default = unmarshalDefault(v.Bytes(), xd.L1.Kind, file, xd.L2.Enum) } } } func (file *File) resolveServices() { var depIdx int32 for i := range file.allServices { sd := &file.allServices[i] // Resolve method dependencies. for j := range sd.L2.Methods.List { md := &sd.L2.Methods.List[j] md.L1.Input = file.resolveMessageDependency(md.L1.Input, listMethInDeps, depIdx) md.L1.Output = file.resolveMessageDependency(md.L1.Output, listMethOutDeps, depIdx) depIdx++ } } } func (file *File) resolveEnumDependency(ed protoreflect.EnumDescriptor, i, j int32) protoreflect.EnumDescriptor { r := file.builder.FileRegistry if r, ok := r.(resolverByIndex); ok { if ed2 := r.FindEnumByIndex(i, j, file.allEnums, file.allMessages); ed2 != nil { return ed2 } } for i := range file.allEnums { if ed2 := &file.allEnums[i]; ed2.L0.FullName == ed.FullName() { return ed2 } } if d, _ := r.FindDescriptorByName(ed.FullName()); d != nil { return d.(protoreflect.EnumDescriptor) } return ed } func (file *File) resolveMessageDependency(md protoreflect.MessageDescriptor, i, j int32) protoreflect.MessageDescriptor { r := file.builder.FileRegistry if r, ok := r.(resolverByIndex); ok { if md2 := r.FindMessageByIndex(i, j, file.allEnums, file.allMessages); md2 != nil { return md2 } } for i := range file.allMessages { if md2 := &file.allMessages[i]; md2.L0.FullName == md.FullName() { return md2 } } if d, _ := r.FindDescriptorByName(md.FullName()); d != nil { return d.(protoreflect.MessageDescriptor) } return md } func (fd *File) unmarshalFull(b []byte) { sb := getBuilder() defer putBuilder(sb) var enumIdx, messageIdx, extensionIdx, serviceIdx int var rawOptions []byte fd.L2 = new(FileL2) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FileDescriptorProto_PublicDependency_field_number: fd.L2.Imports[v].IsPublic = true } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FileDescriptorProto_Dependency_field_number: path := sb.MakeString(v) imp, _ := fd.builder.FileRegistry.FindFileByPath(path) if imp == nil { imp = PlaceholderFile(path) } fd.L2.Imports = append(fd.L2.Imports, protoreflect.FileImport{FileDescriptor: imp}) case genid.FileDescriptorProto_EnumType_field_number: fd.L1.Enums.List[enumIdx].unmarshalFull(v, sb) enumIdx++ case genid.FileDescriptorProto_MessageType_field_number: fd.L1.Messages.List[messageIdx].unmarshalFull(v, sb) messageIdx++ case genid.FileDescriptorProto_Extension_field_number: fd.L1.Extensions.List[extensionIdx].unmarshalFull(v, sb) extensionIdx++ case genid.FileDescriptorProto_Service_field_number: fd.L1.Services.List[serviceIdx].unmarshalFull(v, sb) serviceIdx++ case genid.FileDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } fd.L2.Options = fd.builder.optionsUnmarshaler(&descopts.File, rawOptions) } func (ed *Enum) unmarshalFull(b []byte, sb *strs.Builder) { var rawValues [][]byte var rawOptions []byte if !ed.L1.eagerValues { ed.L2 = new(EnumL2) } for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.EnumDescriptorProto_Value_field_number: rawValues = append(rawValues, v) case genid.EnumDescriptorProto_ReservedName_field_number: ed.L2.ReservedNames.List = append(ed.L2.ReservedNames.List, protoreflect.Name(sb.MakeString(v))) case genid.EnumDescriptorProto_ReservedRange_field_number: ed.L2.ReservedRanges.List = append(ed.L2.ReservedRanges.List, unmarshalEnumReservedRange(v)) case genid.EnumDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if !ed.L1.eagerValues && len(rawValues) > 0 { ed.L2.Values.List = make([]EnumValue, len(rawValues)) for i, b := range rawValues { ed.L2.Values.List[i].unmarshalFull(b, sb, ed.L0.ParentFile, ed, i) } } ed.L2.Options = ed.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Enum, rawOptions) } func unmarshalEnumReservedRange(b []byte) (r [2]protoreflect.EnumNumber) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.EnumDescriptorProto_EnumReservedRange_Start_field_number: r[0] = protoreflect.EnumNumber(v) case genid.EnumDescriptorProto_EnumReservedRange_End_field_number: r[1] = protoreflect.EnumNumber(v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } return r } func (vd *EnumValue) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { vd.L0.ParentFile = pf vd.L0.Parent = pd vd.L0.Index = i var rawOptions []byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.EnumValueDescriptorProto_Number_field_number: vd.L1.Number = protoreflect.EnumNumber(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.EnumValueDescriptorProto_Name_field_number: // NOTE: Enum values are in the same scope as the enum parent. vd.L0.FullName = appendFullName(sb, pd.Parent().FullName(), v) case genid.EnumValueDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } vd.L1.Options = pf.builder.optionsUnmarshaler(&descopts.EnumValue, rawOptions) } func (md *Message) unmarshalFull(b []byte, sb *strs.Builder) { var rawFields, rawOneofs [][]byte var enumIdx, messageIdx, extensionIdx int var rawOptions []byte md.L2 = new(MessageL2) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.DescriptorProto_Field_field_number: rawFields = append(rawFields, v) case genid.DescriptorProto_OneofDecl_field_number: rawOneofs = append(rawOneofs, v) case genid.DescriptorProto_ReservedName_field_number: md.L2.ReservedNames.List = append(md.L2.ReservedNames.List, protoreflect.Name(sb.MakeString(v))) case genid.DescriptorProto_ReservedRange_field_number: md.L2.ReservedRanges.List = append(md.L2.ReservedRanges.List, unmarshalMessageReservedRange(v)) case genid.DescriptorProto_ExtensionRange_field_number: r, rawOptions := unmarshalMessageExtensionRange(v) opts := md.L0.ParentFile.builder.optionsUnmarshaler(&descopts.ExtensionRange, rawOptions) md.L2.ExtensionRanges.List = append(md.L2.ExtensionRanges.List, r) md.L2.ExtensionRangeOptions = append(md.L2.ExtensionRangeOptions, opts) case genid.DescriptorProto_EnumType_field_number: md.L1.Enums.List[enumIdx].unmarshalFull(v, sb) enumIdx++ case genid.DescriptorProto_NestedType_field_number: md.L1.Messages.List[messageIdx].unmarshalFull(v, sb) messageIdx++ case genid.DescriptorProto_Extension_field_number: md.L1.Extensions.List[extensionIdx].unmarshalFull(v, sb) extensionIdx++ case genid.DescriptorProto_Options_field_number: md.unmarshalOptions(v) rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if len(rawFields) > 0 || len(rawOneofs) > 0 { md.L2.Fields.List = make([]Field, len(rawFields)) md.L2.Oneofs.List = make([]Oneof, len(rawOneofs)) for i, b := range rawFields { fd := &md.L2.Fields.List[i] fd.unmarshalFull(b, sb, md.L0.ParentFile, md, i) if fd.L1.Cardinality == protoreflect.Required { md.L2.RequiredNumbers.List = append(md.L2.RequiredNumbers.List, fd.L1.Number) } } for i, b := range rawOneofs { od := &md.L2.Oneofs.List[i] od.unmarshalFull(b, sb, md.L0.ParentFile, md, i) } } md.L2.Options = md.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Message, rawOptions) } func (md *Message) unmarshalOptions(b []byte) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.MessageOptions_MapEntry_field_number: md.L1.IsMapEntry = protowire.DecodeBool(v) case genid.MessageOptions_MessageSetWireFormat_field_number: md.L1.IsMessageSet = protowire.DecodeBool(v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func unmarshalMessageReservedRange(b []byte) (r [2]protoreflect.FieldNumber) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.DescriptorProto_ReservedRange_Start_field_number: r[0] = protoreflect.FieldNumber(v) case genid.DescriptorProto_ReservedRange_End_field_number: r[1] = protoreflect.FieldNumber(v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } return r } func unmarshalMessageExtensionRange(b []byte) (r [2]protoreflect.FieldNumber, rawOptions []byte) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.DescriptorProto_ExtensionRange_Start_field_number: r[0] = protoreflect.FieldNumber(v) case genid.DescriptorProto_ExtensionRange_End_field_number: r[1] = protoreflect.FieldNumber(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.DescriptorProto_ExtensionRange_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } return r, rawOptions } func (fd *Field) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { fd.L0.ParentFile = pf fd.L0.Parent = pd fd.L0.Index = i fd.L1.EditionFeatures = featuresFromParentDesc(fd.Parent()) var rawTypeName []byte var rawOptions []byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FieldDescriptorProto_Number_field_number: fd.L1.Number = protoreflect.FieldNumber(v) case genid.FieldDescriptorProto_Label_field_number: fd.L1.Cardinality = protoreflect.Cardinality(v) case genid.FieldDescriptorProto_Type_field_number: fd.L1.Kind = protoreflect.Kind(v) case genid.FieldDescriptorProto_OneofIndex_field_number: // In Message.unmarshalFull, we allocate slices for both // the field and oneof descriptors before unmarshaling either // of them. This ensures pointers to slice elements are stable. od := &pd.(*Message).L2.Oneofs.List[v] od.L1.Fields.List = append(od.L1.Fields.List, fd) if fd.L1.ContainingOneof != nil { panic("oneof type already set") } fd.L1.ContainingOneof = od case genid.FieldDescriptorProto_Proto3Optional_field_number: fd.L1.IsProto3Optional = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FieldDescriptorProto_Name_field_number: fd.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.FieldDescriptorProto_JsonName_field_number: fd.L1.StringName.InitJSON(sb.MakeString(v)) case genid.FieldDescriptorProto_DefaultValue_field_number: fd.L1.Default.val = protoreflect.ValueOfBytes(v) // temporarily store as bytes; later resolved in resolveMessages case genid.FieldDescriptorProto_TypeName_field_number: rawTypeName = v case genid.FieldDescriptorProto_Options_field_number: fd.unmarshalOptions(v) rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if fd.L1.Kind == protoreflect.MessageKind && fd.L1.EditionFeatures.IsDelimitedEncoded { fd.L1.Kind = protoreflect.GroupKind } if fd.L1.EditionFeatures.IsLegacyRequired { fd.L1.Cardinality = protoreflect.Required } if rawTypeName != nil { name := makeFullName(sb, rawTypeName) switch fd.L1.Kind { case protoreflect.EnumKind: fd.L1.Enum = PlaceholderEnum(name) case protoreflect.MessageKind, protoreflect.GroupKind: fd.L1.Message = PlaceholderMessage(name) } } fd.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Field, rawOptions) } func (fd *Field) unmarshalOptions(b []byte) { const FieldOptions_EnforceUTF8 = 13 for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FieldOptions_Packed_field_number: fd.L1.EditionFeatures.IsPacked = protowire.DecodeBool(v) case genid.FieldOptions_Lazy_field_number: fd.L1.IsLazy = protowire.DecodeBool(v) case FieldOptions_EnforceUTF8: fd.L1.EditionFeatures.IsUTF8Validated = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FieldOptions_Features_field_number: fd.L1.EditionFeatures = unmarshalFeatureSet(v, fd.L1.EditionFeatures) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } } func (od *Oneof) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { od.L0.ParentFile = pf od.L0.Parent = pd od.L0.Index = i var rawOptions []byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.OneofDescriptorProto_Name_field_number: od.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.OneofDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } od.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Oneof, rawOptions) } func (xd *Extension) unmarshalFull(b []byte, sb *strs.Builder) { var rawTypeName []byte var rawOptions []byte xd.L2 = new(ExtensionL2) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FieldDescriptorProto_Proto3Optional_field_number: xd.L2.IsProto3Optional = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FieldDescriptorProto_JsonName_field_number: xd.L2.StringName.InitJSON(sb.MakeString(v)) case genid.FieldDescriptorProto_DefaultValue_field_number: xd.L2.Default.val = protoreflect.ValueOfBytes(v) // temporarily store as bytes; later resolved in resolveExtensions case genid.FieldDescriptorProto_TypeName_field_number: rawTypeName = v case genid.FieldDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if rawTypeName != nil { name := makeFullName(sb, rawTypeName) switch xd.L1.Kind { case protoreflect.EnumKind: xd.L2.Enum = PlaceholderEnum(name) case protoreflect.MessageKind, protoreflect.GroupKind: xd.L2.Message = PlaceholderMessage(name) } } xd.L2.Options = xd.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Field, rawOptions) } func (sd *Service) unmarshalFull(b []byte, sb *strs.Builder) { var rawMethods [][]byte var rawOptions []byte sd.L2 = new(ServiceL2) for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.ServiceDescriptorProto_Method_field_number: rawMethods = append(rawMethods, v) case genid.ServiceDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } if len(rawMethods) > 0 { sd.L2.Methods.List = make([]Method, len(rawMethods)) for i, b := range rawMethods { sd.L2.Methods.List[i].unmarshalFull(b, sb, sd.L0.ParentFile, sd, i) } } sd.L2.Options = sd.L0.ParentFile.builder.optionsUnmarshaler(&descopts.Service, rawOptions) } func (md *Method) unmarshalFull(b []byte, sb *strs.Builder, pf *File, pd protoreflect.Descriptor, i int) { md.L0.ParentFile = pf md.L0.Parent = pd md.L0.Index = i var rawOptions []byte for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.MethodDescriptorProto_ClientStreaming_field_number: md.L1.IsStreamingClient = protowire.DecodeBool(v) case genid.MethodDescriptorProto_ServerStreaming_field_number: md.L1.IsStreamingServer = protowire.DecodeBool(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.MethodDescriptorProto_Name_field_number: md.L0.FullName = appendFullName(sb, pd.FullName(), v) case genid.MethodDescriptorProto_InputType_field_number: md.L1.Input = PlaceholderMessage(makeFullName(sb, v)) case genid.MethodDescriptorProto_OutputType_field_number: md.L1.Output = PlaceholderMessage(makeFullName(sb, v)) case genid.MethodDescriptorProto_Options_field_number: rawOptions = appendOptions(rawOptions, v) } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[m:] } } md.L1.Options = pf.builder.optionsUnmarshaler(&descopts.Method, rawOptions) } // appendOptions appends src to dst, where the returned slice is never nil. // This is necessary to distinguish between empty and unpopulated options. func appendOptions(dst, src []byte) []byte { if dst == nil { dst = []byte{} } return append(dst, src...) } // optionsUnmarshaler constructs a lazy unmarshal function for an options message. // // The type of message to unmarshal to is passed as a pointer since the // vars in descopts may not yet be populated at the time this function is called. func (db *Builder) optionsUnmarshaler(p *protoreflect.ProtoMessage, b []byte) func() protoreflect.ProtoMessage { if b == nil { return nil } var opts protoreflect.ProtoMessage var once sync.Once return func() protoreflect.ProtoMessage { once.Do(func() { if *p == nil { panic("Descriptor.Options called without importing the descriptor package") } opts = reflect.New(reflect.TypeOf(*p).Elem()).Interface().(protoreflect.ProtoMessage) if err := (proto.UnmarshalOptions{ AllowPartial: true, Resolver: db.TypeResolver, }).Unmarshal(b, opts); err != nil { panic(err) } }) return opts } }
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/filedesc/editions.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/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 filedesc import ( "fmt" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/editiondefaults" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/reflect/protoreflect" ) var defaultsCache = make(map[Edition]EditionFeatures) var defaultsKeys = []Edition{} func init() { unmarshalEditionDefaults(editiondefaults.Defaults) SurrogateProto2.L1.EditionFeatures = getFeaturesFor(EditionProto2) SurrogateProto3.L1.EditionFeatures = getFeaturesFor(EditionProto3) SurrogateEdition2023.L1.EditionFeatures = getFeaturesFor(Edition2023) } func unmarshalGoFeature(b []byte, parent EditionFeatures) EditionFeatures { for len(b) > 0 { num, _, n := protowire.ConsumeTag(b) b = b[n:] switch num { case genid.GoFeatures_LegacyUnmarshalJsonEnum_field_number: v, m := protowire.ConsumeVarint(b) b = b[m:] parent.GenerateLegacyUnmarshalJSON = protowire.DecodeBool(v) case genid.GoFeatures_ApiLevel_field_number: v, m := protowire.ConsumeVarint(b) b = b[m:] parent.APILevel = int(v) case genid.GoFeatures_StripEnumPrefix_field_number: v, m := protowire.ConsumeVarint(b) b = b[m:] parent.StripEnumPrefix = int(v) default: panic(fmt.Sprintf("unkown field number %d while unmarshalling GoFeatures", num)) } } return parent } func unmarshalFeatureSet(b []byte, parent EditionFeatures) EditionFeatures { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FeatureSet_FieldPresence_field_number: parent.IsFieldPresence = v == genid.FeatureSet_EXPLICIT_enum_value || v == genid.FeatureSet_LEGACY_REQUIRED_enum_value parent.IsLegacyRequired = v == genid.FeatureSet_LEGACY_REQUIRED_enum_value case genid.FeatureSet_EnumType_field_number: parent.IsOpenEnum = v == genid.FeatureSet_OPEN_enum_value case genid.FeatureSet_RepeatedFieldEncoding_field_number: parent.IsPacked = v == genid.FeatureSet_PACKED_enum_value case genid.FeatureSet_Utf8Validation_field_number: parent.IsUTF8Validated = v == genid.FeatureSet_VERIFY_enum_value case genid.FeatureSet_MessageEncoding_field_number: parent.IsDelimitedEncoded = v == genid.FeatureSet_DELIMITED_enum_value case genid.FeatureSet_JsonFormat_field_number: parent.IsJSONCompliant = v == genid.FeatureSet_ALLOW_enum_value case genid.FeatureSet_EnforceNamingStyle_field_number: // EnforceNamingStyle is enforced in protoc, languages other than C++ // are not supposed to do anything with this feature. case genid.FeatureSet_DefaultSymbolVisibility_field_number: // DefaultSymbolVisibility is enforced in protoc, runtimes should not // inspect this value. default: panic(fmt.Sprintf("unkown field number %d while unmarshalling FeatureSet", num)) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FeatureSet_Go_ext_number: parent = unmarshalGoFeature(v, parent) } } } return parent } func featuresFromParentDesc(parentDesc protoreflect.Descriptor) EditionFeatures { var parentFS EditionFeatures switch p := parentDesc.(type) { case *File: parentFS = p.L1.EditionFeatures case *Message: parentFS = p.L1.EditionFeatures default: panic(fmt.Sprintf("unknown parent type %T", parentDesc)) } return parentFS } func unmarshalEditionDefault(b []byte) { var ed Edition var fs EditionFeatures for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.VarintType: v, m := protowire.ConsumeVarint(b) b = b[m:] switch num { case genid.FeatureSetDefaults_FeatureSetEditionDefault_Edition_field_number: ed = Edition(v) } case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] switch num { case genid.FeatureSetDefaults_FeatureSetEditionDefault_FixedFeatures_field_number: fs = unmarshalFeatureSet(v, fs) case genid.FeatureSetDefaults_FeatureSetEditionDefault_OverridableFeatures_field_number: fs = unmarshalFeatureSet(v, fs) } } } defaultsCache[ed] = fs defaultsKeys = append(defaultsKeys, ed) } func unmarshalEditionDefaults(b []byte) { for len(b) > 0 { num, _, n := protowire.ConsumeTag(b) b = b[n:] switch num { case genid.FeatureSetDefaults_Defaults_field_number: def, m := protowire.ConsumeBytes(b) b = b[m:] unmarshalEditionDefault(def) case genid.FeatureSetDefaults_MinimumEdition_field_number, genid.FeatureSetDefaults_MaximumEdition_field_number: // We don't care about the minimum and maximum editions. If the // edition we are looking for later on is not in the cache we know // it is outside of the range between minimum and maximum edition. _, m := protowire.ConsumeVarint(b) b = b[m:] default: panic(fmt.Sprintf("unkown field number %d while unmarshalling EditionDefault", num)) } } } func getFeaturesFor(ed Edition) EditionFeatures { match := EditionUnknown for _, key := range defaultsKeys { if key > ed { break } match = key } if match == EditionUnknown { panic(fmt.Sprintf("unsupported edition: %v", ed)) } return defaultsCache[match] }
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/filedesc/build.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/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 filedesc provides functionality for constructing descriptors. // // The types in this package implement interfaces in the protoreflect package // related to protobuf descripriptors. package filedesc import ( "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/reflect/protoreflect" "google.golang.org/protobuf/reflect/protoregistry" ) // Builder construct a protoreflect.FileDescriptor from the raw descriptor. type Builder struct { // GoPackagePath is the Go package path that is invoking this builder. GoPackagePath string // RawDescriptor is the wire-encoded bytes of FileDescriptorProto // and must be populated. RawDescriptor []byte // NumEnums is the total number of enums declared in the file. NumEnums int32 // NumMessages is the total number of messages declared in the file. // It includes the implicit message declarations for map entries. NumMessages int32 // NumExtensions is the total number of extensions declared in the file. NumExtensions int32 // NumServices is the total number of services declared in the file. NumServices int32 // TypeResolver resolves extension field types for descriptor options. // If nil, it uses protoregistry.GlobalTypes. TypeResolver interface { protoregistry.ExtensionTypeResolver } // FileRegistry is use to lookup file, enum, and message dependencies. // Once constructed, the file descriptor is registered here. // If nil, it uses protoregistry.GlobalFiles. FileRegistry interface { FindFileByPath(string) (protoreflect.FileDescriptor, error) FindDescriptorByName(protoreflect.FullName) (protoreflect.Descriptor, error) RegisterFile(protoreflect.FileDescriptor) error } } // resolverByIndex is an interface Builder.FileRegistry may implement. // If so, it permits looking up an enum or message dependency based on the // sub-list and element index into filetype.Builder.DependencyIndexes. type resolverByIndex interface { FindEnumByIndex(int32, int32, []Enum, []Message) protoreflect.EnumDescriptor FindMessageByIndex(int32, int32, []Enum, []Message) protoreflect.MessageDescriptor } // Indexes of each sub-list in filetype.Builder.DependencyIndexes. const ( listFieldDeps int32 = iota listExtTargets listExtDeps listMethInDeps listMethOutDeps ) // Out is the output of the Builder. type Out struct { File protoreflect.FileDescriptor // Enums is all enum descriptors in "flattened ordering". Enums []Enum // Messages is all message descriptors in "flattened ordering". // It includes the implicit message declarations for map entries. Messages []Message // Extensions is all extension descriptors in "flattened ordering". Extensions []Extension // Service is all service descriptors in "flattened ordering". Services []Service } // Build constructs a FileDescriptor given the parameters set in Builder. // It assumes that the inputs are well-formed and panics if any inconsistencies // are encountered. // // If NumEnums+NumMessages+NumExtensions+NumServices is zero, // then Build automatically derives them from the raw descriptor. func (db Builder) Build() (out Out) { // Populate the counts if uninitialized. if db.NumEnums+db.NumMessages+db.NumExtensions+db.NumServices == 0 { db.unmarshalCounts(db.RawDescriptor, true) } // Initialize resolvers and registries if unpopulated. if db.TypeResolver == nil { db.TypeResolver = protoregistry.GlobalTypes } if db.FileRegistry == nil { db.FileRegistry = protoregistry.GlobalFiles } fd := newRawFile(db) out.File = fd out.Enums = fd.allEnums out.Messages = fd.allMessages out.Extensions = fd.allExtensions out.Services = fd.allServices if err := db.FileRegistry.RegisterFile(fd); err != nil { panic(err) } return out } // unmarshalCounts counts the number of enum, message, extension, and service // declarations in the raw message, which is either a FileDescriptorProto // or a MessageDescriptorProto depending on whether isFile is set. func (db *Builder) unmarshalCounts(b []byte, isFile bool) { for len(b) > 0 { num, typ, n := protowire.ConsumeTag(b) b = b[n:] switch typ { case protowire.BytesType: v, m := protowire.ConsumeBytes(b) b = b[m:] if isFile { switch num { case genid.FileDescriptorProto_EnumType_field_number: db.NumEnums++ case genid.FileDescriptorProto_MessageType_field_number: db.unmarshalCounts(v, false) db.NumMessages++ case genid.FileDescriptorProto_Extension_field_number: db.NumExtensions++ case genid.FileDescriptorProto_Service_field_number: db.NumServices++ } } else { switch num { case genid.DescriptorProto_EnumType_field_number: db.NumEnums++ case genid.DescriptorProto_NestedType_field_number: db.unmarshalCounts(v, false) db.NumMessages++ case genid.DescriptorProto_Extension_field_number: db.NumExtensions++ } } default: m := protowire.ConsumeFieldValue(num, typ, b) b = b[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/filedesc/presence.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/presence.go
// Copyright 2025 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 filedesc import "google.golang.org/protobuf/reflect/protoreflect" // UsePresenceForField reports whether the presence bitmap should be used for // the specified field. func UsePresenceForField(fd protoreflect.FieldDescriptor) (usePresence, canBeLazy bool) { switch { case fd.ContainingOneof() != nil && !fd.ContainingOneof().IsSynthetic(): // Oneof fields never use the presence bitmap. // // Synthetic oneofs are an exception: Those are used to implement proto3 // optional fields and hence should follow non-oneof field semantics. return false, false case fd.IsMap(): // Map-typed fields never use the presence bitmap. return false, false case fd.Kind() == protoreflect.MessageKind || fd.Kind() == protoreflect.GroupKind: // Lazy fields always use the presence bitmap (only messages can be lazy). isLazy := fd.(interface{ IsLazy() bool }).IsLazy() return isLazy, isLazy default: // If the field has presence, use the presence bitmap. return fd.HasPresence(), 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/filedesc/desc_list_gen.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/desc_list_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 filedesc import ( "fmt" "strings" "sync" "google.golang.org/protobuf/internal/descfmt" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/reflect/protoreflect" ) type Enums struct { List []Enum once sync.Once byName map[protoreflect.Name]*Enum // protected by once } func (p *Enums) Len() int { return len(p.List) } func (p *Enums) Get(i int) protoreflect.EnumDescriptor { return &p.List[i] } func (p *Enums) ByName(s protoreflect.Name) protoreflect.EnumDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Enums) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Enums) ProtoInternal(pragma.DoNotImplement) {} func (p *Enums) lazyInit() *Enums { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Enum, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return p } type EnumValues struct { List []EnumValue once sync.Once byName map[protoreflect.Name]*EnumValue // protected by once byNum map[protoreflect.EnumNumber]*EnumValue // protected by once } func (p *EnumValues) Len() int { return len(p.List) } func (p *EnumValues) Get(i int) protoreflect.EnumValueDescriptor { return &p.List[i] } func (p *EnumValues) ByName(s protoreflect.Name) protoreflect.EnumValueDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *EnumValues) ByNumber(n protoreflect.EnumNumber) protoreflect.EnumValueDescriptor { if d := p.lazyInit().byNum[n]; d != nil { return d } return nil } func (p *EnumValues) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *EnumValues) ProtoInternal(pragma.DoNotImplement) {} func (p *EnumValues) lazyInit() *EnumValues { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*EnumValue, len(p.List)) p.byNum = make(map[protoreflect.EnumNumber]*EnumValue, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } if _, ok := p.byNum[d.Number()]; !ok { p.byNum[d.Number()] = d } } } }) return p } type Messages struct { List []Message once sync.Once byName map[protoreflect.Name]*Message // protected by once } func (p *Messages) Len() int { return len(p.List) } func (p *Messages) Get(i int) protoreflect.MessageDescriptor { return &p.List[i] } func (p *Messages) ByName(s protoreflect.Name) protoreflect.MessageDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Messages) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Messages) ProtoInternal(pragma.DoNotImplement) {} func (p *Messages) lazyInit() *Messages { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Message, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return p } type Fields struct { List []Field once sync.Once byName map[protoreflect.Name]*Field // protected by once byJSON map[string]*Field // protected by once byText map[string]*Field // protected by once byNum map[protoreflect.FieldNumber]*Field // protected by once } func (p *Fields) Len() int { return len(p.List) } func (p *Fields) Get(i int) protoreflect.FieldDescriptor { return &p.List[i] } func (p *Fields) ByName(s protoreflect.Name) protoreflect.FieldDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Fields) ByJSONName(s string) protoreflect.FieldDescriptor { if d := p.lazyInit().byJSON[s]; d != nil { return d } return nil } func (p *Fields) ByTextName(s string) protoreflect.FieldDescriptor { if d := p.lazyInit().byText[s]; d != nil { return d } return nil } func (p *Fields) ByNumber(n protoreflect.FieldNumber) protoreflect.FieldDescriptor { if d := p.lazyInit().byNum[n]; d != nil { return d } return nil } func (p *Fields) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Fields) ProtoInternal(pragma.DoNotImplement) {} func (p *Fields) lazyInit() *Fields { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Field, len(p.List)) p.byJSON = make(map[string]*Field, len(p.List)) p.byText = make(map[string]*Field, len(p.List)) p.byNum = make(map[protoreflect.FieldNumber]*Field, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } if _, ok := p.byJSON[d.JSONName()]; !ok { p.byJSON[d.JSONName()] = d } if _, ok := p.byText[d.TextName()]; !ok { p.byText[d.TextName()] = d } if isGroupLike(d) { lowerJSONName := strings.ToLower(d.JSONName()) if _, ok := p.byJSON[lowerJSONName]; !ok { p.byJSON[lowerJSONName] = d } lowerTextName := strings.ToLower(d.TextName()) if _, ok := p.byText[lowerTextName]; !ok { p.byText[lowerTextName] = d } } if _, ok := p.byNum[d.Number()]; !ok { p.byNum[d.Number()] = d } } } }) return p } type Oneofs struct { List []Oneof once sync.Once byName map[protoreflect.Name]*Oneof // protected by once } func (p *Oneofs) Len() int { return len(p.List) } func (p *Oneofs) Get(i int) protoreflect.OneofDescriptor { return &p.List[i] } func (p *Oneofs) ByName(s protoreflect.Name) protoreflect.OneofDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Oneofs) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Oneofs) ProtoInternal(pragma.DoNotImplement) {} func (p *Oneofs) lazyInit() *Oneofs { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Oneof, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return p } type Extensions struct { List []Extension once sync.Once byName map[protoreflect.Name]*Extension // protected by once } func (p *Extensions) Len() int { return len(p.List) } func (p *Extensions) Get(i int) protoreflect.ExtensionDescriptor { return &p.List[i] } func (p *Extensions) ByName(s protoreflect.Name) protoreflect.ExtensionDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Extensions) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Extensions) ProtoInternal(pragma.DoNotImplement) {} func (p *Extensions) lazyInit() *Extensions { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Extension, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return p } type Services struct { List []Service once sync.Once byName map[protoreflect.Name]*Service // protected by once } func (p *Services) Len() int { return len(p.List) } func (p *Services) Get(i int) protoreflect.ServiceDescriptor { return &p.List[i] } func (p *Services) ByName(s protoreflect.Name) protoreflect.ServiceDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Services) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Services) ProtoInternal(pragma.DoNotImplement) {} func (p *Services) lazyInit() *Services { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Service, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return p } type Methods struct { List []Method once sync.Once byName map[protoreflect.Name]*Method // protected by once } func (p *Methods) Len() int { return len(p.List) } func (p *Methods) Get(i int) protoreflect.MethodDescriptor { return &p.List[i] } func (p *Methods) ByName(s protoreflect.Name) protoreflect.MethodDescriptor { if d := p.lazyInit().byName[s]; d != nil { return d } return nil } func (p *Methods) Format(s fmt.State, r rune) { descfmt.FormatList(s, r, p) } func (p *Methods) ProtoInternal(pragma.DoNotImplement) {} func (p *Methods) lazyInit() *Methods { p.once.Do(func() { if len(p.List) > 0 { p.byName = make(map[protoreflect.Name]*Method, len(p.List)) for i := range p.List { d := &p.List[i] if _, ok := p.byName[d.Name()]; !ok { p.byName[d.Name()] = d } } } }) return 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/filedesc/desc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/filedesc/desc.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 filedesc import ( "bytes" "fmt" "strings" "sync" "sync/atomic" "google.golang.org/protobuf/internal/descfmt" "google.golang.org/protobuf/internal/descopts" "google.golang.org/protobuf/internal/encoding/defval" "google.golang.org/protobuf/internal/encoding/messageset" "google.golang.org/protobuf/internal/genid" "google.golang.org/protobuf/internal/pragma" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) // Edition is an Enum for proto2.Edition type Edition int32 // These values align with the value of Enum in descriptor.proto which allows // direct conversion between the proto enum and this enum. const ( EditionUnknown Edition = 0 EditionProto2 Edition = 998 EditionProto3 Edition = 999 Edition2023 Edition = 1000 Edition2024 Edition = 1001 EditionUnsupported Edition = 100000 ) // The types in this file may have a suffix: // • L0: Contains fields common to all descriptors (except File) and // must be initialized up front. // • L1: Contains fields specific to a descriptor and // must be initialized up front. If the associated proto uses Editions, the // Editions features must always be resolved. If not explicitly set, the // appropriate default must be resolved and set. // • L2: Contains fields that are lazily initialized when constructing // from the raw file descriptor. When constructing as a literal, the L2 // fields must be initialized up front. // // The types are exported so that packages like reflect/protodesc can // directly construct descriptors. type ( File struct { fileRaw L1 FileL1 once uint32 // atomically set if L2 is valid mu sync.Mutex // protects L2 L2 *FileL2 } FileL1 struct { Syntax protoreflect.Syntax Edition Edition // Only used if Syntax == Editions Path string Package protoreflect.FullName Enums Enums Messages Messages Extensions Extensions Services Services EditionFeatures EditionFeatures } FileL2 struct { Options func() protoreflect.ProtoMessage Imports FileImports Locations SourceLocations } // EditionFeatures is a frequently-instantiated struct, so please take care // to minimize padding when adding new fields to this struct (add them in // the right place/order). EditionFeatures struct { // StripEnumPrefix determines if the plugin generates enum value // constants as-is, with their prefix stripped, or both variants. StripEnumPrefix int // IsFieldPresence is true if field_presence is EXPLICIT // https://protobuf.dev/editions/features/#field_presence IsFieldPresence bool // IsFieldPresence is true if field_presence is LEGACY_REQUIRED // https://protobuf.dev/editions/features/#field_presence IsLegacyRequired bool // IsOpenEnum is true if enum_type is OPEN // https://protobuf.dev/editions/features/#enum_type IsOpenEnum bool // IsPacked is true if repeated_field_encoding is PACKED // https://protobuf.dev/editions/features/#repeated_field_encoding IsPacked bool // IsUTF8Validated is true if utf_validation is VERIFY // https://protobuf.dev/editions/features/#utf8_validation IsUTF8Validated bool // IsDelimitedEncoded is true if message_encoding is DELIMITED // https://protobuf.dev/editions/features/#message_encoding IsDelimitedEncoded bool // IsJSONCompliant is true if json_format is ALLOW // https://protobuf.dev/editions/features/#json_format IsJSONCompliant bool // GenerateLegacyUnmarshalJSON determines if the plugin generates the // UnmarshalJSON([]byte) error method for enums. GenerateLegacyUnmarshalJSON bool // APILevel controls which API (Open, Hybrid or Opaque) should be used // for generated code (.pb.go files). APILevel int } ) func (fd *File) ParentFile() protoreflect.FileDescriptor { return fd } func (fd *File) Parent() protoreflect.Descriptor { return nil } func (fd *File) Index() int { return 0 } func (fd *File) Syntax() protoreflect.Syntax { return fd.L1.Syntax } // Not exported and just used to reconstruct the original FileDescriptor proto func (fd *File) Edition() int32 { return int32(fd.L1.Edition) } func (fd *File) Name() protoreflect.Name { return fd.L1.Package.Name() } func (fd *File) FullName() protoreflect.FullName { return fd.L1.Package } func (fd *File) IsPlaceholder() bool { return false } func (fd *File) Options() protoreflect.ProtoMessage { if f := fd.lazyInit().Options; f != nil { return f() } return descopts.File } func (fd *File) Path() string { return fd.L1.Path } func (fd *File) Package() protoreflect.FullName { return fd.L1.Package } func (fd *File) Imports() protoreflect.FileImports { return &fd.lazyInit().Imports } func (fd *File) Enums() protoreflect.EnumDescriptors { return &fd.L1.Enums } func (fd *File) Messages() protoreflect.MessageDescriptors { return &fd.L1.Messages } func (fd *File) Extensions() protoreflect.ExtensionDescriptors { return &fd.L1.Extensions } func (fd *File) Services() protoreflect.ServiceDescriptors { return &fd.L1.Services } func (fd *File) SourceLocations() protoreflect.SourceLocations { return &fd.lazyInit().Locations } func (fd *File) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) } func (fd *File) ProtoType(protoreflect.FileDescriptor) {} func (fd *File) ProtoInternal(pragma.DoNotImplement) {} func (fd *File) lazyInit() *FileL2 { if atomic.LoadUint32(&fd.once) == 0 { fd.lazyInitOnce() } return fd.L2 } func (fd *File) lazyInitOnce() { fd.mu.Lock() if fd.L2 == nil { fd.lazyRawInit() // recursively initializes all L2 structures } atomic.StoreUint32(&fd.once, 1) fd.mu.Unlock() } // GoPackagePath is a pseudo-internal API for determining the Go package path // that this file descriptor is declared in. // // WARNING: This method is exempt from the compatibility promise and may be // removed in the future without warning. func (fd *File) GoPackagePath() string { return fd.builder.GoPackagePath } type ( Enum struct { Base L1 EnumL1 L2 *EnumL2 // protected by fileDesc.once } EnumL1 struct { eagerValues bool // controls whether EnumL2.Values is already populated EditionFeatures EditionFeatures } EnumL2 struct { Options func() protoreflect.ProtoMessage Values EnumValues ReservedNames Names ReservedRanges EnumRanges } EnumValue struct { Base L1 EnumValueL1 } EnumValueL1 struct { Options func() protoreflect.ProtoMessage Number protoreflect.EnumNumber } ) func (ed *Enum) Options() protoreflect.ProtoMessage { if f := ed.lazyInit().Options; f != nil { return f() } return descopts.Enum } func (ed *Enum) Values() protoreflect.EnumValueDescriptors { if ed.L1.eagerValues { return &ed.L2.Values } return &ed.lazyInit().Values } func (ed *Enum) ReservedNames() protoreflect.Names { return &ed.lazyInit().ReservedNames } func (ed *Enum) ReservedRanges() protoreflect.EnumRanges { return &ed.lazyInit().ReservedRanges } func (ed *Enum) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) } func (ed *Enum) ProtoType(protoreflect.EnumDescriptor) {} func (ed *Enum) lazyInit() *EnumL2 { ed.L0.ParentFile.lazyInit() // implicitly initializes L2 return ed.L2 } func (ed *Enum) IsClosed() bool { return !ed.L1.EditionFeatures.IsOpenEnum } func (ed *EnumValue) Options() protoreflect.ProtoMessage { if f := ed.L1.Options; f != nil { return f() } return descopts.EnumValue } func (ed *EnumValue) Number() protoreflect.EnumNumber { return ed.L1.Number } func (ed *EnumValue) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, ed) } func (ed *EnumValue) ProtoType(protoreflect.EnumValueDescriptor) {} type ( Message struct { Base L1 MessageL1 L2 *MessageL2 // protected by fileDesc.once } MessageL1 struct { Enums Enums Messages Messages Extensions Extensions IsMapEntry bool // promoted from google.protobuf.MessageOptions IsMessageSet bool // promoted from google.protobuf.MessageOptions EditionFeatures EditionFeatures } MessageL2 struct { Options func() protoreflect.ProtoMessage Fields Fields Oneofs Oneofs ReservedNames Names ReservedRanges FieldRanges RequiredNumbers FieldNumbers // must be consistent with Fields.Cardinality ExtensionRanges FieldRanges ExtensionRangeOptions []func() protoreflect.ProtoMessage // must be same length as ExtensionRanges } Field struct { Base L1 FieldL1 } FieldL1 struct { Options func() protoreflect.ProtoMessage Number protoreflect.FieldNumber Cardinality protoreflect.Cardinality // must be consistent with Message.RequiredNumbers Kind protoreflect.Kind StringName stringName IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto IsLazy bool // promoted from google.protobuf.FieldOptions Default defaultValue ContainingOneof protoreflect.OneofDescriptor // must be consistent with Message.Oneofs.Fields Enum protoreflect.EnumDescriptor Message protoreflect.MessageDescriptor EditionFeatures EditionFeatures } Oneof struct { Base L1 OneofL1 } OneofL1 struct { Options func() protoreflect.ProtoMessage Fields OneofFields // must be consistent with Message.Fields.ContainingOneof EditionFeatures EditionFeatures } ) func (md *Message) Options() protoreflect.ProtoMessage { if f := md.lazyInit().Options; f != nil { return f() } return descopts.Message } func (md *Message) IsMapEntry() bool { return md.L1.IsMapEntry } func (md *Message) Fields() protoreflect.FieldDescriptors { return &md.lazyInit().Fields } func (md *Message) Oneofs() protoreflect.OneofDescriptors { return &md.lazyInit().Oneofs } func (md *Message) ReservedNames() protoreflect.Names { return &md.lazyInit().ReservedNames } func (md *Message) ReservedRanges() protoreflect.FieldRanges { return &md.lazyInit().ReservedRanges } func (md *Message) RequiredNumbers() protoreflect.FieldNumbers { return &md.lazyInit().RequiredNumbers } func (md *Message) ExtensionRanges() protoreflect.FieldRanges { return &md.lazyInit().ExtensionRanges } func (md *Message) ExtensionRangeOptions(i int) protoreflect.ProtoMessage { if f := md.lazyInit().ExtensionRangeOptions[i]; f != nil { return f() } return descopts.ExtensionRange } func (md *Message) Enums() protoreflect.EnumDescriptors { return &md.L1.Enums } func (md *Message) Messages() protoreflect.MessageDescriptors { return &md.L1.Messages } func (md *Message) Extensions() protoreflect.ExtensionDescriptors { return &md.L1.Extensions } func (md *Message) ProtoType(protoreflect.MessageDescriptor) {} func (md *Message) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) } func (md *Message) lazyInit() *MessageL2 { md.L0.ParentFile.lazyInit() // implicitly initializes L2 return md.L2 } // IsMessageSet is a pseudo-internal API for checking whether a message // should serialize in the proto1 message format. // // WARNING: This method is exempt from the compatibility promise and may be // removed in the future without warning. func (md *Message) IsMessageSet() bool { return md.L1.IsMessageSet } func (fd *Field) Options() protoreflect.ProtoMessage { if f := fd.L1.Options; f != nil { return f() } return descopts.Field } func (fd *Field) Number() protoreflect.FieldNumber { return fd.L1.Number } func (fd *Field) Cardinality() protoreflect.Cardinality { return fd.L1.Cardinality } func (fd *Field) Kind() protoreflect.Kind { return fd.L1.Kind } func (fd *Field) HasJSONName() bool { return fd.L1.StringName.hasJSON } func (fd *Field) JSONName() string { return fd.L1.StringName.getJSON(fd) } func (fd *Field) TextName() string { return fd.L1.StringName.getText(fd) } func (fd *Field) HasPresence() bool { if fd.L1.Cardinality == protoreflect.Repeated { return false } return fd.IsExtension() || fd.L1.EditionFeatures.IsFieldPresence || fd.L1.Message != nil || fd.L1.ContainingOneof != nil } func (fd *Field) HasOptionalKeyword() bool { return (fd.L0.ParentFile.L1.Syntax == protoreflect.Proto2 && fd.L1.Cardinality == protoreflect.Optional && fd.L1.ContainingOneof == nil) || fd.L1.IsProto3Optional } func (fd *Field) IsPacked() bool { if fd.L1.Cardinality != protoreflect.Repeated { return false } switch fd.L1.Kind { case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind: return false } return fd.L1.EditionFeatures.IsPacked } func (fd *Field) IsExtension() bool { return false } func (fd *Field) IsWeak() bool { return false } func (fd *Field) IsLazy() bool { return fd.L1.IsLazy } func (fd *Field) IsList() bool { return fd.Cardinality() == protoreflect.Repeated && !fd.IsMap() } func (fd *Field) IsMap() bool { return fd.Message() != nil && fd.Message().IsMapEntry() } func (fd *Field) MapKey() protoreflect.FieldDescriptor { if !fd.IsMap() { return nil } return fd.Message().Fields().ByNumber(genid.MapEntry_Key_field_number) } func (fd *Field) MapValue() protoreflect.FieldDescriptor { if !fd.IsMap() { return nil } return fd.Message().Fields().ByNumber(genid.MapEntry_Value_field_number) } func (fd *Field) HasDefault() bool { return fd.L1.Default.has } func (fd *Field) Default() protoreflect.Value { return fd.L1.Default.get(fd) } func (fd *Field) DefaultEnumValue() protoreflect.EnumValueDescriptor { return fd.L1.Default.enum } func (fd *Field) ContainingOneof() protoreflect.OneofDescriptor { return fd.L1.ContainingOneof } func (fd *Field) ContainingMessage() protoreflect.MessageDescriptor { return fd.L0.Parent.(protoreflect.MessageDescriptor) } func (fd *Field) Enum() protoreflect.EnumDescriptor { return fd.L1.Enum } func (fd *Field) Message() protoreflect.MessageDescriptor { return fd.L1.Message } func (fd *Field) IsMapEntry() bool { parent, ok := fd.L0.Parent.(protoreflect.MessageDescriptor) return ok && parent.IsMapEntry() } func (fd *Field) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, fd) } func (fd *Field) ProtoType(protoreflect.FieldDescriptor) {} // EnforceUTF8 is a pseudo-internal API to determine whether to enforce UTF-8 // validation for the string field. This exists for Google-internal use only // since proto3 did not enforce UTF-8 validity prior to the open-source release. // If this method does not exist, the default is to enforce valid UTF-8. // // WARNING: This method is exempt from the compatibility promise and may be // removed in the future without warning. func (fd *Field) EnforceUTF8() bool { return fd.L1.EditionFeatures.IsUTF8Validated } func (od *Oneof) IsSynthetic() bool { return od.L0.ParentFile.L1.Syntax == protoreflect.Proto3 && len(od.L1.Fields.List) == 1 && od.L1.Fields.List[0].HasOptionalKeyword() } func (od *Oneof) Options() protoreflect.ProtoMessage { if f := od.L1.Options; f != nil { return f() } return descopts.Oneof } func (od *Oneof) Fields() protoreflect.FieldDescriptors { return &od.L1.Fields } func (od *Oneof) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, od) } func (od *Oneof) ProtoType(protoreflect.OneofDescriptor) {} type ( Extension struct { Base L1 ExtensionL1 L2 *ExtensionL2 // protected by fileDesc.once } ExtensionL1 struct { Number protoreflect.FieldNumber Extendee protoreflect.MessageDescriptor Cardinality protoreflect.Cardinality Kind protoreflect.Kind IsLazy bool EditionFeatures EditionFeatures } ExtensionL2 struct { Options func() protoreflect.ProtoMessage StringName stringName IsProto3Optional bool // promoted from google.protobuf.FieldDescriptorProto Default defaultValue Enum protoreflect.EnumDescriptor Message protoreflect.MessageDescriptor } ) func (xd *Extension) Options() protoreflect.ProtoMessage { if f := xd.lazyInit().Options; f != nil { return f() } return descopts.Field } func (xd *Extension) Number() protoreflect.FieldNumber { return xd.L1.Number } func (xd *Extension) Cardinality() protoreflect.Cardinality { return xd.L1.Cardinality } func (xd *Extension) Kind() protoreflect.Kind { return xd.L1.Kind } func (xd *Extension) HasJSONName() bool { return xd.lazyInit().StringName.hasJSON } func (xd *Extension) JSONName() string { return xd.lazyInit().StringName.getJSON(xd) } func (xd *Extension) TextName() string { return xd.lazyInit().StringName.getText(xd) } func (xd *Extension) HasPresence() bool { return xd.L1.Cardinality != protoreflect.Repeated } func (xd *Extension) HasOptionalKeyword() bool { return (xd.L0.ParentFile.L1.Syntax == protoreflect.Proto2 && xd.L1.Cardinality == protoreflect.Optional) || xd.lazyInit().IsProto3Optional } func (xd *Extension) IsPacked() bool { if xd.L1.Cardinality != protoreflect.Repeated { return false } switch xd.L1.Kind { case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind, protoreflect.GroupKind: return false } return xd.L1.EditionFeatures.IsPacked } func (xd *Extension) IsExtension() bool { return true } func (xd *Extension) IsWeak() bool { return false } func (xd *Extension) IsLazy() bool { return xd.L1.IsLazy } func (xd *Extension) IsList() bool { return xd.Cardinality() == protoreflect.Repeated } func (xd *Extension) IsMap() bool { return false } func (xd *Extension) MapKey() protoreflect.FieldDescriptor { return nil } func (xd *Extension) MapValue() protoreflect.FieldDescriptor { return nil } func (xd *Extension) HasDefault() bool { return xd.lazyInit().Default.has } func (xd *Extension) Default() protoreflect.Value { return xd.lazyInit().Default.get(xd) } func (xd *Extension) DefaultEnumValue() protoreflect.EnumValueDescriptor { return xd.lazyInit().Default.enum } func (xd *Extension) ContainingOneof() protoreflect.OneofDescriptor { return nil } func (xd *Extension) ContainingMessage() protoreflect.MessageDescriptor { return xd.L1.Extendee } func (xd *Extension) Enum() protoreflect.EnumDescriptor { return xd.lazyInit().Enum } func (xd *Extension) Message() protoreflect.MessageDescriptor { return xd.lazyInit().Message } func (xd *Extension) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, xd) } func (xd *Extension) ProtoType(protoreflect.FieldDescriptor) {} func (xd *Extension) ProtoInternal(pragma.DoNotImplement) {} func (xd *Extension) lazyInit() *ExtensionL2 { xd.L0.ParentFile.lazyInit() // implicitly initializes L2 return xd.L2 } type ( Service struct { Base L1 ServiceL1 L2 *ServiceL2 // protected by fileDesc.once } ServiceL1 struct{} ServiceL2 struct { Options func() protoreflect.ProtoMessage Methods Methods } Method struct { Base L1 MethodL1 } MethodL1 struct { Options func() protoreflect.ProtoMessage Input protoreflect.MessageDescriptor Output protoreflect.MessageDescriptor IsStreamingClient bool IsStreamingServer bool } ) func (sd *Service) Options() protoreflect.ProtoMessage { if f := sd.lazyInit().Options; f != nil { return f() } return descopts.Service } func (sd *Service) Methods() protoreflect.MethodDescriptors { return &sd.lazyInit().Methods } func (sd *Service) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, sd) } func (sd *Service) ProtoType(protoreflect.ServiceDescriptor) {} func (sd *Service) ProtoInternal(pragma.DoNotImplement) {} func (sd *Service) lazyInit() *ServiceL2 { sd.L0.ParentFile.lazyInit() // implicitly initializes L2 return sd.L2 } func (md *Method) Options() protoreflect.ProtoMessage { if f := md.L1.Options; f != nil { return f() } return descopts.Method } func (md *Method) Input() protoreflect.MessageDescriptor { return md.L1.Input } func (md *Method) Output() protoreflect.MessageDescriptor { return md.L1.Output } func (md *Method) IsStreamingClient() bool { return md.L1.IsStreamingClient } func (md *Method) IsStreamingServer() bool { return md.L1.IsStreamingServer } func (md *Method) Format(s fmt.State, r rune) { descfmt.FormatDesc(s, r, md) } func (md *Method) ProtoType(protoreflect.MethodDescriptor) {} func (md *Method) ProtoInternal(pragma.DoNotImplement) {} // Surrogate files are can be used to create standalone descriptors // where the syntax is only information derived from the parent file. var ( SurrogateProto2 = &File{L1: FileL1{Syntax: protoreflect.Proto2}, L2: &FileL2{}} SurrogateProto3 = &File{L1: FileL1{Syntax: protoreflect.Proto3}, L2: &FileL2{}} SurrogateEdition2023 = &File{L1: FileL1{Syntax: protoreflect.Editions, Edition: Edition2023}, L2: &FileL2{}} ) type ( Base struct { L0 BaseL0 } BaseL0 struct { FullName protoreflect.FullName // must be populated ParentFile *File // must be populated Parent protoreflect.Descriptor Index int } ) func (d *Base) Name() protoreflect.Name { return d.L0.FullName.Name() } func (d *Base) FullName() protoreflect.FullName { return d.L0.FullName } func (d *Base) ParentFile() protoreflect.FileDescriptor { if d.L0.ParentFile == SurrogateProto2 || d.L0.ParentFile == SurrogateProto3 { return nil // surrogate files are not real parents } return d.L0.ParentFile } func (d *Base) Parent() protoreflect.Descriptor { return d.L0.Parent } func (d *Base) Index() int { return d.L0.Index } func (d *Base) Syntax() protoreflect.Syntax { return d.L0.ParentFile.Syntax() } func (d *Base) IsPlaceholder() bool { return false } func (d *Base) ProtoInternal(pragma.DoNotImplement) {} type stringName struct { hasJSON bool once sync.Once nameJSON string nameText string } // InitJSON initializes the name. It is exported for use by other internal packages. func (s *stringName) InitJSON(name string) { s.hasJSON = true s.nameJSON = name } // Returns true if this field is structured like the synthetic field of a proto2 // group. This allows us to expand our treatment of delimited fields without // breaking proto2 files that have been upgraded to editions. func isGroupLike(fd protoreflect.FieldDescriptor) bool { // Groups are always group types. if fd.Kind() != protoreflect.GroupKind { return false } // Group fields are always the lowercase type name. if strings.ToLower(string(fd.Message().Name())) != string(fd.Name()) { return false } // Groups could only be defined in the same file they're used. if fd.Message().ParentFile() != fd.ParentFile() { return false } // Group messages are always defined in the same scope as the field. File // level extensions will compare NULL == NULL here, which is why the file // comparison above is necessary to ensure both come from the same file. if fd.IsExtension() { return fd.Parent() == fd.Message().Parent() } return fd.ContainingMessage() == fd.Message().Parent() } func (s *stringName) lazyInit(fd protoreflect.FieldDescriptor) *stringName { s.once.Do(func() { if fd.IsExtension() { // For extensions, JSON and text are formatted the same way. var name string if messageset.IsMessageSetExtension(fd) { name = string("[" + fd.FullName().Parent() + "]") } else { name = string("[" + fd.FullName() + "]") } s.nameJSON = name s.nameText = name } else { // Format the JSON name. if !s.hasJSON { s.nameJSON = strs.JSONCamelCase(string(fd.Name())) } // Format the text name. s.nameText = string(fd.Name()) if isGroupLike(fd) { s.nameText = string(fd.Message().Name()) } } }) return s } func (s *stringName) getJSON(fd protoreflect.FieldDescriptor) string { return s.lazyInit(fd).nameJSON } func (s *stringName) getText(fd protoreflect.FieldDescriptor) string { return s.lazyInit(fd).nameText } func DefaultValue(v protoreflect.Value, ev protoreflect.EnumValueDescriptor) defaultValue { dv := defaultValue{has: v.IsValid(), val: v, enum: ev} if b, ok := v.Interface().([]byte); ok { // Store a copy of the default bytes, so that we can detect // accidental mutations of the original value. dv.bytes = append([]byte(nil), b...) } return dv } func unmarshalDefault(b []byte, k protoreflect.Kind, pf *File, ed protoreflect.EnumDescriptor) defaultValue { var evs protoreflect.EnumValueDescriptors if k == protoreflect.EnumKind { // If the enum is declared within the same file, be careful not to // blindly call the Values method, lest we bind ourselves in a deadlock. if e, ok := ed.(*Enum); ok && e.L0.ParentFile == pf { evs = &e.L2.Values } else { evs = ed.Values() } // If we are unable to resolve the enum dependency, use a placeholder // enum value since we will not be able to parse the default value. if ed.IsPlaceholder() && protoreflect.Name(b).IsValid() { v := protoreflect.ValueOfEnum(0) ev := PlaceholderEnumValue(ed.FullName().Parent().Append(protoreflect.Name(b))) return DefaultValue(v, ev) } } v, ev, err := defval.Unmarshal(string(b), k, evs, defval.Descriptor) if err != nil { panic(err) } return DefaultValue(v, ev) } type defaultValue struct { has bool val protoreflect.Value enum protoreflect.EnumValueDescriptor bytes []byte } func (dv *defaultValue) get(fd protoreflect.FieldDescriptor) protoreflect.Value { // Return the zero value as the default if unpopulated. if !dv.has { if fd.Cardinality() == protoreflect.Repeated { return protoreflect.Value{} } switch fd.Kind() { case protoreflect.BoolKind: return protoreflect.ValueOfBool(false) case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: return protoreflect.ValueOfInt32(0) case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: return protoreflect.ValueOfInt64(0) case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: return protoreflect.ValueOfUint32(0) case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: return protoreflect.ValueOfUint64(0) case protoreflect.FloatKind: return protoreflect.ValueOfFloat32(0) case protoreflect.DoubleKind: return protoreflect.ValueOfFloat64(0) case protoreflect.StringKind: return protoreflect.ValueOfString("") case protoreflect.BytesKind: return protoreflect.ValueOfBytes(nil) case protoreflect.EnumKind: if evs := fd.Enum().Values(); evs.Len() > 0 { return protoreflect.ValueOfEnum(evs.Get(0).Number()) } return protoreflect.ValueOfEnum(0) } } if len(dv.bytes) > 0 && !bytes.Equal(dv.bytes, dv.val.Bytes()) { // TODO: Avoid panic if we're running with the race detector // and instead spawn a goroutine that periodically resets // this value back to the original to induce a race. panic(fmt.Sprintf("detected mutation on the default bytes for %v", fd.FullName())) } return dv.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/encoding/defval/default.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/defval/default.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 defval marshals and unmarshals textual forms of default values. // // This package handles both the form historically used in Go struct field tags // and also the form used by google.protobuf.FieldDescriptorProto.default_value // since they differ in superficial ways. package defval import ( "fmt" "math" "strconv" ptext "google.golang.org/protobuf/internal/encoding/text" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) // Format is the serialization format used to represent the default value. type Format int const ( _ Format = iota // Descriptor uses the serialization format that protoc uses with the // google.protobuf.FieldDescriptorProto.default_value field. Descriptor // GoTag uses the historical serialization format in Go struct field tags. GoTag ) // Unmarshal deserializes the default string s according to the given kind k. // When k is an enum, a list of enum value descriptors must be provided. func Unmarshal(s string, k protoreflect.Kind, evs protoreflect.EnumValueDescriptors, f Format) (protoreflect.Value, protoreflect.EnumValueDescriptor, error) { switch k { case protoreflect.BoolKind: if f == GoTag { switch s { case "1": return protoreflect.ValueOfBool(true), nil, nil case "0": return protoreflect.ValueOfBool(false), nil, nil } } else { switch s { case "true": return protoreflect.ValueOfBool(true), nil, nil case "false": return protoreflect.ValueOfBool(false), nil, nil } } case protoreflect.EnumKind: if f == GoTag { // Go tags use the numeric form of the enum value. if n, err := strconv.ParseInt(s, 10, 32); err == nil { if ev := evs.ByNumber(protoreflect.EnumNumber(n)); ev != nil { return protoreflect.ValueOfEnum(ev.Number()), ev, nil } } } else { // Descriptor default_value use the enum identifier. ev := evs.ByName(protoreflect.Name(s)) if ev != nil { return protoreflect.ValueOfEnum(ev.Number()), ev, nil } } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: if v, err := strconv.ParseInt(s, 10, 32); err == nil { return protoreflect.ValueOfInt32(int32(v)), nil, nil } case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: if v, err := strconv.ParseInt(s, 10, 64); err == nil { return protoreflect.ValueOfInt64(int64(v)), nil, nil } case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: if v, err := strconv.ParseUint(s, 10, 32); err == nil { return protoreflect.ValueOfUint32(uint32(v)), nil, nil } case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: if v, err := strconv.ParseUint(s, 10, 64); err == nil { return protoreflect.ValueOfUint64(uint64(v)), nil, nil } case protoreflect.FloatKind, protoreflect.DoubleKind: var v float64 var err error switch s { case "-inf": v = math.Inf(-1) case "inf": v = math.Inf(+1) case "nan": v = math.NaN() default: v, err = strconv.ParseFloat(s, 64) } if err == nil { if k == protoreflect.FloatKind { return protoreflect.ValueOfFloat32(float32(v)), nil, nil } else { return protoreflect.ValueOfFloat64(float64(v)), nil, nil } } case protoreflect.StringKind: // String values are already unescaped and can be used as is. return protoreflect.ValueOfString(s), nil, nil case protoreflect.BytesKind: if b, ok := unmarshalBytes(s); ok { return protoreflect.ValueOfBytes(b), nil, nil } } return protoreflect.Value{}, nil, errors.New("could not parse value for %v: %q", k, s) } // Marshal serializes v as the default string according to the given kind k. // When specifying the Descriptor format for an enum kind, the associated // enum value descriptor must be provided. func Marshal(v protoreflect.Value, ev protoreflect.EnumValueDescriptor, k protoreflect.Kind, f Format) (string, error) { switch k { case protoreflect.BoolKind: if f == GoTag { if v.Bool() { return "1", nil } else { return "0", nil } } else { if v.Bool() { return "true", nil } else { return "false", nil } } case protoreflect.EnumKind: if f == GoTag { return strconv.FormatInt(int64(v.Enum()), 10), nil } else { return string(ev.Name()), nil } case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: return strconv.FormatInt(v.Int(), 10), nil case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: return strconv.FormatUint(v.Uint(), 10), nil case protoreflect.FloatKind, protoreflect.DoubleKind: f := v.Float() switch { case math.IsInf(f, -1): return "-inf", nil case math.IsInf(f, +1): return "inf", nil case math.IsNaN(f): return "nan", nil default: if k == protoreflect.FloatKind { return strconv.FormatFloat(f, 'g', -1, 32), nil } else { return strconv.FormatFloat(f, 'g', -1, 64), nil } } case protoreflect.StringKind: // String values are serialized as is without any escaping. return v.String(), nil case protoreflect.BytesKind: if s, ok := marshalBytes(v.Bytes()); ok { return s, nil } } return "", errors.New("could not format value for %v: %v", k, v) } // unmarshalBytes deserializes bytes by applying C unescaping. func unmarshalBytes(s string) ([]byte, bool) { // Bytes values use the same escaping as the text format, // however they lack the surrounding double quotes. v, err := ptext.UnmarshalString(`"` + s + `"`) if err != nil { return nil, false } return []byte(v), true } // marshalBytes serializes bytes by using C escaping. // To match the exact output of protoc, this is identical to the // CEscape function in strutil.cc of the protoc source code. func marshalBytes(b []byte) (string, bool) { var s []byte for _, c := range b { switch c { case '\n': s = append(s, `\n`...) case '\r': s = append(s, `\r`...) case '\t': s = append(s, `\t`...) case '"': s = append(s, `\"`...) case '\'': s = append(s, `\'`...) case '\\': s = append(s, `\\`...) default: if printableASCII := c >= 0x20 && c <= 0x7e; printableASCII { s = append(s, c) } else { s = append(s, fmt.Sprintf(`\%03o`, c)...) } } } return string(s), 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/encoding/json/decode_number.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/json/decode_number.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 json import ( "bytes" "strconv" ) // parseNumber reads the given []byte for a valid JSON number. If it is valid, // it returns the number of bytes. Parsing logic follows the definition in // https://tools.ietf.org/html/rfc7159#section-6, and is based off // encoding/json.isValidNumber function. func parseNumber(input []byte) (int, bool) { var n int s := input if len(s) == 0 { return 0, false } // Optional - if s[0] == '-' { s = s[1:] n++ if len(s) == 0 { return 0, false } } // Digits switch { case s[0] == '0': s = s[1:] n++ case '1' <= s[0] && s[0] <= '9': s = s[1:] n++ for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } default: return 0, false } // . followed by 1 or more digits. if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { s = s[2:] n += 2 for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } } // e or E followed by an optional - or + and // 1 or more digits. if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { s = s[1:] n++ if s[0] == '+' || s[0] == '-' { s = s[1:] n++ if len(s) == 0 { return 0, false } } for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } } // Check that next byte is a delimiter or it is at the end. if n < len(input) && isNotDelim(input[n]) { return 0, false } return n, true } // numberParts is the result of parsing out a valid JSON number. It contains // the parts of a number. The parts are used for integer conversion. type numberParts struct { neg bool intp []byte frac []byte exp []byte } // parseNumber constructs numberParts from given []byte. The logic here is // similar to consumeNumber above with the difference of having to construct // numberParts. The slice fields in numberParts are subslices of the input. func parseNumberParts(input []byte) (numberParts, bool) { var neg bool var intp []byte var frac []byte var exp []byte s := input if len(s) == 0 { return numberParts{}, false } // Optional - if s[0] == '-' { neg = true s = s[1:] if len(s) == 0 { return numberParts{}, false } } // Digits switch { case s[0] == '0': // Skip first 0 and no need to store. s = s[1:] case '1' <= s[0] && s[0] <= '9': intp = s n := 1 s = s[1:] for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } intp = intp[:n] default: return numberParts{}, false } // . followed by 1 or more digits. if len(s) >= 2 && s[0] == '.' && '0' <= s[1] && s[1] <= '9' { frac = s[1:] n := 1 s = s[2:] for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } frac = frac[:n] } // e or E followed by an optional - or + and // 1 or more digits. if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { s = s[1:] exp = s n := 0 if s[0] == '+' || s[0] == '-' { s = s[1:] n++ if len(s) == 0 { return numberParts{}, false } } for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } exp = exp[:n] } return numberParts{ neg: neg, intp: intp, frac: bytes.TrimRight(frac, "0"), // Remove unnecessary 0s to the right. exp: exp, }, true } // normalizeToIntString returns an integer string in normal form without the // E-notation for given numberParts. It will return false if it is not an // integer or if the exponent exceeds than max/min int value. func normalizeToIntString(n numberParts) (string, bool) { intpSize := len(n.intp) fracSize := len(n.frac) if intpSize == 0 && fracSize == 0 { return "0", true } var exp int if len(n.exp) > 0 { i, err := strconv.ParseInt(string(n.exp), 10, 32) if err != nil { return "", false } exp = int(i) } var num []byte if exp >= 0 { // For positive E, shift fraction digits into integer part and also pad // with zeroes as needed. // If there are more digits in fraction than the E value, then the // number is not an integer. if fracSize > exp { return "", false } // Make sure resulting digits are within max value limit to avoid // unnecessarily constructing a large byte slice that may simply fail // later on. const maxDigits = 20 // Max uint64 value has 20 decimal digits. if intpSize+exp > maxDigits { return "", false } // Set cap to make a copy of integer part when appended. num = n.intp[:len(n.intp):len(n.intp)] num = append(num, n.frac...) for i := 0; i < exp-fracSize; i++ { num = append(num, '0') } } else { // For negative E, shift digits in integer part out. // If there are fractions, then the number is not an integer. if fracSize > 0 { return "", false } // index is where the decimal point will be after adjusting for negative // exponent. index := intpSize + exp if index < 0 { return "", false } num = n.intp // If any of the digits being shifted to the right of the decimal point // is non-zero, then the number is not an integer. for i := index; i < intpSize; i++ { if num[i] != '0' { return "", false } } num = num[:index] } if n.neg { return "-" + string(num), true } return string(num), 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/encoding/json/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/json/encode.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 json import ( "math" "math/bits" "strconv" "strings" "unicode/utf8" "google.golang.org/protobuf/internal/detrand" "google.golang.org/protobuf/internal/errors" ) // kind represents an encoding type. type kind uint8 const ( _ kind = (1 << iota) / 2 name scalar objectOpen objectClose arrayOpen arrayClose ) // Encoder provides methods to write out JSON constructs and values. The user is // responsible for producing valid sequences of JSON constructs and values. type Encoder struct { indent string lastKind kind indents []byte out []byte } // NewEncoder returns an Encoder. // // If indent is a non-empty string, it causes every entry for an Array or Object // to be preceded by the indent and trailed by a newline. func NewEncoder(buf []byte, indent string) (*Encoder, error) { e := &Encoder{ out: buf, } if len(indent) > 0 { if strings.Trim(indent, " \t") != "" { return nil, errors.New("indent may only be composed of space or tab characters") } e.indent = indent } return e, nil } // Bytes returns the content of the written bytes. func (e *Encoder) Bytes() []byte { return e.out } // WriteNull writes out the null value. func (e *Encoder) WriteNull() { e.prepareNext(scalar) e.out = append(e.out, "null"...) } // WriteBool writes out the given boolean value. func (e *Encoder) WriteBool(b bool) { e.prepareNext(scalar) if b { e.out = append(e.out, "true"...) } else { e.out = append(e.out, "false"...) } } // WriteString writes out the given string in JSON string value. Returns error // if input string contains invalid UTF-8. func (e *Encoder) WriteString(s string) error { e.prepareNext(scalar) var err error if e.out, err = appendString(e.out, s); err != nil { return err } return nil } // Sentinel error used for indicating invalid UTF-8. var errInvalidUTF8 = errors.New("invalid UTF-8") func appendString(out []byte, in string) ([]byte, error) { out = append(out, '"') i := indexNeedEscapeInString(in) in, out = in[i:], append(out, in[:i]...) for len(in) > 0 { switch r, n := utf8.DecodeRuneInString(in); { case r == utf8.RuneError && n == 1: return out, errInvalidUTF8 case r < ' ' || r == '"' || r == '\\': out = append(out, '\\') switch r { case '"', '\\': out = append(out, byte(r)) case '\b': out = append(out, 'b') case '\f': out = append(out, 'f') case '\n': out = append(out, 'n') case '\r': out = append(out, 'r') case '\t': out = append(out, 't') default: out = append(out, 'u') out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...) out = strconv.AppendUint(out, uint64(r), 16) } in = in[n:] default: i := indexNeedEscapeInString(in[n:]) in, out = in[n+i:], append(out, in[:n+i]...) } } out = append(out, '"') return out, nil } // indexNeedEscapeInString returns the index of the character that needs // escaping. If no characters need escaping, this returns the input length. func indexNeedEscapeInString(s string) int { for i, r := range s { if r < ' ' || r == '\\' || r == '"' || r == utf8.RuneError { return i } } return len(s) } // WriteFloat writes out the given float and bitSize in JSON number value. func (e *Encoder) WriteFloat(n float64, bitSize int) { e.prepareNext(scalar) e.out = appendFloat(e.out, n, bitSize) } // appendFloat formats given float in bitSize, and appends to the given []byte. func appendFloat(out []byte, n float64, bitSize int) []byte { switch { case math.IsNaN(n): return append(out, `"NaN"`...) case math.IsInf(n, +1): return append(out, `"Infinity"`...) case math.IsInf(n, -1): return append(out, `"-Infinity"`...) } // JSON number formatting logic based on encoding/json. // See floatEncoder.encode for reference. fmt := byte('f') if abs := math.Abs(n); abs != 0 { if bitSize == 64 && (abs < 1e-6 || abs >= 1e21) || bitSize == 32 && (float32(abs) < 1e-6 || float32(abs) >= 1e21) { fmt = 'e' } } out = strconv.AppendFloat(out, n, fmt, -1, bitSize) if fmt == 'e' { n := len(out) if n >= 4 && out[n-4] == 'e' && out[n-3] == '-' && out[n-2] == '0' { out[n-2] = out[n-1] out = out[:n-1] } } return out } // WriteInt writes out the given signed integer in JSON number value. func (e *Encoder) WriteInt(n int64) { e.prepareNext(scalar) e.out = strconv.AppendInt(e.out, n, 10) } // WriteUint writes out the given unsigned integer in JSON number value. func (e *Encoder) WriteUint(n uint64) { e.prepareNext(scalar) e.out = strconv.AppendUint(e.out, n, 10) } // StartObject writes out the '{' symbol. func (e *Encoder) StartObject() { e.prepareNext(objectOpen) e.out = append(e.out, '{') } // EndObject writes out the '}' symbol. func (e *Encoder) EndObject() { e.prepareNext(objectClose) e.out = append(e.out, '}') } // WriteName writes out the given string in JSON string value and the name // separator ':'. Returns error if input string contains invalid UTF-8, which // should not be likely as protobuf field names should be valid. func (e *Encoder) WriteName(s string) error { e.prepareNext(name) var err error // Append to output regardless of error. e.out, err = appendString(e.out, s) e.out = append(e.out, ':') return err } // StartArray writes out the '[' symbol. func (e *Encoder) StartArray() { e.prepareNext(arrayOpen) e.out = append(e.out, '[') } // EndArray writes out the ']' symbol. func (e *Encoder) EndArray() { e.prepareNext(arrayClose) e.out = append(e.out, ']') } // prepareNext adds possible comma and indentation for the next value based // on last type and indent option. It also updates lastKind to next. func (e *Encoder) prepareNext(next kind) { defer func() { // Set lastKind to next. e.lastKind = next }() if len(e.indent) == 0 { // Need to add comma on the following condition. if e.lastKind&(scalar|objectClose|arrayClose) != 0 && next&(name|scalar|objectOpen|arrayOpen) != 0 { e.out = append(e.out, ',') // For single-line output, add a random extra space after each // comma to make output unstable. if detrand.Bool() { e.out = append(e.out, ' ') } } return } switch { case e.lastKind&(objectOpen|arrayOpen) != 0: // If next type is NOT closing, add indent and newline. if next&(objectClose|arrayClose) == 0 { e.indents = append(e.indents, e.indent...) e.out = append(e.out, '\n') e.out = append(e.out, e.indents...) } case e.lastKind&(scalar|objectClose|arrayClose) != 0: switch { // If next type is either a value or name, add comma and newline. case next&(name|scalar|objectOpen|arrayOpen) != 0: e.out = append(e.out, ',', '\n') // If next type is a closing object or array, adjust indentation. case next&(objectClose|arrayClose) != 0: e.indents = e.indents[:len(e.indents)-len(e.indent)] e.out = append(e.out, '\n') } e.out = append(e.out, e.indents...) case e.lastKind&name != 0: e.out = append(e.out, ' ') // For multi-line output, add a random extra space after key: to make // output unstable. if detrand.Bool() { e.out = append(e.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/encoding/json/decode_token.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/json/decode_token.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 json import ( "bytes" "fmt" "strconv" ) // Kind represents a token kind expressible in the JSON format. type Kind uint16 const ( Invalid Kind = (1 << iota) / 2 EOF Null Bool Number String Name ObjectOpen ObjectClose ArrayOpen ArrayClose // comma is only for parsing in between tokens and // does not need to be exported. comma ) func (k Kind) String() string { switch k { case EOF: return "eof" case Null: return "null" case Bool: return "bool" case Number: return "number" case String: return "string" case ObjectOpen: return "{" case ObjectClose: return "}" case Name: return "name" case ArrayOpen: return "[" case ArrayClose: return "]" case comma: return "," } return "<invalid>" } // Token provides a parsed token kind and value. // // Values are provided by the difference accessor methods. The accessor methods // Name, Bool, and ParsedString will panic if called on the wrong kind. There // are different accessor methods for the Number kind for converting to the // appropriate Go numeric type and those methods have the ok return value. type Token struct { // Token kind. kind Kind // pos provides the position of the token in the original input. pos int // raw bytes of the serialized token. // This is a subslice into the original input. raw []byte // boo is parsed boolean value. boo bool // str is parsed string value. str string } // Kind returns the token kind. func (t Token) Kind() Kind { return t.kind } // RawString returns the read value in string. func (t Token) RawString() string { return string(t.raw) } // Pos returns the token position from the input. func (t Token) Pos() int { return t.pos } // Name returns the object name if token is Name, else it panics. func (t Token) Name() string { if t.kind == Name { return t.str } panic(fmt.Sprintf("Token is not a Name: %v", t.RawString())) } // Bool returns the bool value if token kind is Bool, else it panics. func (t Token) Bool() bool { if t.kind == Bool { return t.boo } panic(fmt.Sprintf("Token is not a Bool: %v", t.RawString())) } // ParsedString returns the string value for a JSON string token or the read // value in string if token is not a string. func (t Token) ParsedString() string { if t.kind == String { return t.str } panic(fmt.Sprintf("Token is not a String: %v", t.RawString())) } // Float returns the floating-point number if token kind is Number. // // The floating-point precision is specified by the bitSize parameter: 32 for // float32 or 64 for float64. If bitSize=32, the result still has type float64, // but it will be convertible to float32 without changing its value. It will // return false if the number exceeds the floating point limits for given // bitSize. func (t Token) Float(bitSize int) (float64, bool) { if t.kind != Number { return 0, false } f, err := strconv.ParseFloat(t.RawString(), bitSize) if err != nil { return 0, false } return f, true } // Int returns the signed integer number if token is Number. // // The given bitSize specifies the integer type that the result must fit into. // It returns false if the number is not an integer value or if the result // exceeds the limits for given bitSize. func (t Token) Int(bitSize int) (int64, bool) { s, ok := t.getIntStr() if !ok { return 0, false } n, err := strconv.ParseInt(s, 10, bitSize) if err != nil { return 0, false } return n, true } // Uint returns the signed integer number if token is Number. // // The given bitSize specifies the unsigned integer type that the result must // fit into. It returns false if the number is not an unsigned integer value // or if the result exceeds the limits for given bitSize. func (t Token) Uint(bitSize int) (uint64, bool) { s, ok := t.getIntStr() if !ok { return 0, false } n, err := strconv.ParseUint(s, 10, bitSize) if err != nil { return 0, false } return n, true } func (t Token) getIntStr() (string, bool) { if t.kind != Number { return "", false } parts, ok := parseNumberParts(t.raw) if !ok { return "", false } return normalizeToIntString(parts) } // TokenEquals returns true if given Tokens are equal, else false. func TokenEquals(x, y Token) bool { return x.kind == y.kind && x.pos == y.pos && bytes.Equal(x.raw, y.raw) && x.boo == y.boo && x.str == y.str }
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/encoding/json/decode_string.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/json/decode_string.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 json import ( "strconv" "unicode" "unicode/utf16" "unicode/utf8" "google.golang.org/protobuf/internal/strs" ) func (d *Decoder) parseString(in []byte) (string, int, error) { in0 := in if len(in) == 0 { return "", 0, ErrUnexpectedEOF } if in[0] != '"' { return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q at start of string", in[0]) } in = in[1:] i := indexNeedEscapeInBytes(in) in, out := in[i:], in[:i:i] // set cap to prevent mutations for len(in) > 0 { switch r, n := utf8.DecodeRune(in); { case r == utf8.RuneError && n == 1: return "", 0, d.newSyntaxError(d.currPos(), "invalid UTF-8 in string") case r < ' ': return "", 0, d.newSyntaxError(d.currPos(), "invalid character %q in string", r) case r == '"': in = in[1:] n := len(in0) - len(in) return string(out), n, nil case r == '\\': if len(in) < 2 { return "", 0, ErrUnexpectedEOF } switch r := in[1]; r { case '"', '\\', '/': in, out = in[2:], append(out, r) case 'b': in, out = in[2:], append(out, '\b') case 'f': in, out = in[2:], append(out, '\f') case 'n': in, out = in[2:], append(out, '\n') case 'r': in, out = in[2:], append(out, '\r') case 't': in, out = in[2:], append(out, '\t') case 'u': if len(in) < 6 { return "", 0, ErrUnexpectedEOF } v, err := strconv.ParseUint(string(in[2:6]), 16, 16) if err != nil { return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) } in = in[6:] r := rune(v) if utf16.IsSurrogate(r) { if len(in) < 6 { return "", 0, ErrUnexpectedEOF } v, err := strconv.ParseUint(string(in[2:6]), 16, 16) r = utf16.DecodeRune(r, rune(v)) if in[0] != '\\' || in[1] != 'u' || r == unicode.ReplacementChar || err != nil { return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:6]) } in = in[6:] } out = append(out, string(r)...) default: return "", 0, d.newSyntaxError(d.currPos(), "invalid escape code %q in string", in[:2]) } default: i := indexNeedEscapeInBytes(in[n:]) in, out = in[n+i:], append(out, in[:n+i]...) } } return "", 0, ErrUnexpectedEOF } // indexNeedEscapeInBytes returns the index of the character that needs // escaping. If no characters need escaping, this returns the input length. func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) }
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/encoding/json/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/json/decode.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 json import ( "bytes" "fmt" "io" "regexp" "unicode/utf8" "google.golang.org/protobuf/internal/errors" ) // call specifies which Decoder method was invoked. type call uint8 const ( readCall call = iota peekCall ) const unexpectedFmt = "unexpected token %s" // ErrUnexpectedEOF means that EOF was encountered in the middle of the input. var ErrUnexpectedEOF = errors.New("%v", io.ErrUnexpectedEOF) // Decoder is a token-based JSON decoder. type Decoder struct { // lastCall is last method called, either readCall or peekCall. // Initial value is readCall. lastCall call // lastToken contains the last read token. lastToken Token // lastErr contains the last read error. lastErr error // openStack is a stack containing ObjectOpen and ArrayOpen values. The // top of stack represents the object or the array the current value is // directly located in. openStack []Kind // orig is used in reporting line and column. orig []byte // in contains the unconsumed input. in []byte } // NewDecoder returns a Decoder to read the given []byte. func NewDecoder(b []byte) *Decoder { return &Decoder{orig: b, in: b} } // Peek looks ahead and returns the next token kind without advancing a read. func (d *Decoder) Peek() (Token, error) { defer func() { d.lastCall = peekCall }() if d.lastCall == readCall { d.lastToken, d.lastErr = d.Read() } return d.lastToken, d.lastErr } // Read returns the next JSON token. // It will return an error if there is no valid token. func (d *Decoder) Read() (Token, error) { const scalar = Null | Bool | Number | String defer func() { d.lastCall = readCall }() if d.lastCall == peekCall { return d.lastToken, d.lastErr } tok, err := d.parseNext() if err != nil { return Token{}, err } switch tok.kind { case EOF: if len(d.openStack) != 0 || d.lastToken.kind&scalar|ObjectClose|ArrayClose == 0 { return Token{}, ErrUnexpectedEOF } case Null: if !d.isValueNext() { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } case Bool, Number: if !d.isValueNext() { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } case String: if d.isValueNext() { break } // This string token should only be for a field name. if d.lastToken.kind&(ObjectOpen|comma) == 0 { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } if len(d.in) == 0 { return Token{}, ErrUnexpectedEOF } if c := d.in[0]; c != ':' { return Token{}, d.newSyntaxError(d.currPos(), `unexpected character %s, missing ":" after field name`, string(c)) } tok.kind = Name d.consume(1) case ObjectOpen, ArrayOpen: if !d.isValueNext() { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } d.openStack = append(d.openStack, tok.kind) case ObjectClose: if len(d.openStack) == 0 || d.lastToken.kind&(Name|comma) != 0 || d.openStack[len(d.openStack)-1] != ObjectOpen { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } d.openStack = d.openStack[:len(d.openStack)-1] case ArrayClose: if len(d.openStack) == 0 || d.lastToken.kind == comma || d.openStack[len(d.openStack)-1] != ArrayOpen { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } d.openStack = d.openStack[:len(d.openStack)-1] case comma: if len(d.openStack) == 0 || d.lastToken.kind&(scalar|ObjectClose|ArrayClose) == 0 { return Token{}, d.newSyntaxError(tok.pos, unexpectedFmt, tok.RawString()) } } // Update d.lastToken only after validating token to be in the right sequence. d.lastToken = tok if d.lastToken.kind == comma { return d.Read() } return tok, nil } // Any sequence that looks like a non-delimiter (for error reporting). var errRegexp = regexp.MustCompile(`^([-+._a-zA-Z0-9]{1,32}|.)`) // parseNext parses for the next JSON token. It returns a Token object for // different types, except for Name. It does not handle whether the next token // is in a valid sequence or not. func (d *Decoder) parseNext() (Token, error) { // Trim leading spaces. d.consume(0) in := d.in if len(in) == 0 { return d.consumeToken(EOF, 0), nil } switch in[0] { case 'n': if n := matchWithDelim("null", in); n != 0 { return d.consumeToken(Null, n), nil } case 't': if n := matchWithDelim("true", in); n != 0 { return d.consumeBoolToken(true, n), nil } case 'f': if n := matchWithDelim("false", in); n != 0 { return d.consumeBoolToken(false, n), nil } case '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9': if n, ok := parseNumber(in); ok { return d.consumeToken(Number, n), nil } case '"': s, n, err := d.parseString(in) if err != nil { return Token{}, err } return d.consumeStringToken(s, n), nil case '{': return d.consumeToken(ObjectOpen, 1), nil case '}': return d.consumeToken(ObjectClose, 1), nil case '[': return d.consumeToken(ArrayOpen, 1), nil case ']': return d.consumeToken(ArrayClose, 1), nil case ',': return d.consumeToken(comma, 1), nil } return Token{}, d.newSyntaxError(d.currPos(), "invalid value %s", errRegexp.Find(in)) } // newSyntaxError returns an error with line and column information useful for // syntax errors. func (d *Decoder) newSyntaxError(pos int, f string, x ...any) error { e := errors.New(f, x...) line, column := d.Position(pos) return errors.New("syntax error (line %d:%d): %v", line, column, e) } // Position returns line and column number of given index of the original input. // It will panic if index is out of range. func (d *Decoder) Position(idx int) (line int, column int) { b := d.orig[:idx] line = bytes.Count(b, []byte("\n")) + 1 if i := bytes.LastIndexByte(b, '\n'); i >= 0 { b = b[i+1:] } column = utf8.RuneCount(b) + 1 // ignore multi-rune characters return line, column } // currPos returns the current index position of d.in from d.orig. func (d *Decoder) currPos() int { return len(d.orig) - len(d.in) } // matchWithDelim matches s with the input b and verifies that the match // terminates with a delimiter of some form (e.g., r"[^-+_.a-zA-Z0-9]"). // As a special case, EOF is considered a delimiter. It returns the length of s // if there is a match, else 0. func matchWithDelim(s string, b []byte) int { if !bytes.HasPrefix(b, []byte(s)) { return 0 } n := len(s) if n < len(b) && isNotDelim(b[n]) { return 0 } return n } // isNotDelim returns true if given byte is a not delimiter character. func isNotDelim(c byte) bool { return (c == '-' || c == '+' || c == '.' || c == '_' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9')) } // consume consumes n bytes of input and any subsequent whitespace. func (d *Decoder) consume(n int) { d.in = d.in[n:] for len(d.in) > 0 { switch d.in[0] { case ' ', '\n', '\r', '\t': d.in = d.in[1:] default: return } } } // isValueNext returns true if next type should be a JSON value: Null, // Number, String or Bool. func (d *Decoder) isValueNext() bool { if len(d.openStack) == 0 { return d.lastToken.kind == 0 } start := d.openStack[len(d.openStack)-1] switch start { case ObjectOpen: return d.lastToken.kind&Name != 0 case ArrayOpen: return d.lastToken.kind&(ArrayOpen|comma) != 0 } panic(fmt.Sprintf( "unreachable logic in Decoder.isValueNext, lastToken.kind: %v, openStack: %v", d.lastToken.kind, start)) } // consumeToken constructs a Token for given Kind with raw value derived from // current d.in and given size, and consumes the given size-length of it. func (d *Decoder) consumeToken(kind Kind, size int) Token { tok := Token{ kind: kind, raw: d.in[:size], pos: len(d.orig) - len(d.in), } d.consume(size) return tok } // consumeBoolToken constructs a Token for a Bool kind with raw value derived from // current d.in and given size. func (d *Decoder) consumeBoolToken(b bool, size int) Token { tok := Token{ kind: Bool, raw: d.in[:size], pos: len(d.orig) - len(d.in), boo: b, } d.consume(size) return tok } // consumeStringToken constructs a Token for a String kind with raw value derived // from current d.in and given size. func (d *Decoder) consumeStringToken(s string, size int) Token { tok := Token{ kind: String, raw: d.in[:size], pos: len(d.orig) - len(d.in), str: s, } d.consume(size) return tok } // Clone returns a copy of the Decoder for use in reading ahead the next JSON // object, array or other values without affecting current Decoder. func (d *Decoder) Clone() *Decoder { ret := *d ret.openStack = append([]Kind(nil), ret.openStack...) return &ret }
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/encoding/messageset/messageset.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/messageset/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 messageset encodes and decodes the obsolete MessageSet wire format. package messageset import ( "math" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/reflect/protoreflect" ) // The MessageSet wire format is equivalent to a message defined as follows, // where each Item defines an extension field with a field number of 'type_id' // and content of 'message'. MessageSet extensions must be non-repeated message // fields. // // message MessageSet { // repeated group Item = 1 { // required int32 type_id = 2; // required string message = 3; // } // } const ( FieldItem = protowire.Number(1) FieldTypeID = protowire.Number(2) FieldMessage = protowire.Number(3) ) // ExtensionName is the field name for extensions of MessageSet. // // A valid MessageSet extension must be of the form: // // message MyMessage { // extend proto2.bridge.MessageSet { // optional MyMessage message_set_extension = 1234; // } // ... // } const ExtensionName = "message_set_extension" // IsMessageSet returns whether the message uses the MessageSet wire format. func IsMessageSet(md protoreflect.MessageDescriptor) bool { xmd, ok := md.(interface{ IsMessageSet() bool }) return ok && xmd.IsMessageSet() } // IsMessageSetExtension reports this field properly extends a MessageSet. func IsMessageSetExtension(fd protoreflect.FieldDescriptor) bool { switch { case fd.Name() != ExtensionName: return false case !IsMessageSet(fd.ContainingMessage()): return false case fd.FullName().Parent() != fd.Message().FullName(): return false } return true } // SizeField returns the size of a MessageSet item field containing an extension // with the given field number, not counting the contents of the message subfield. func SizeField(num protowire.Number) int { return 2*protowire.SizeTag(FieldItem) + protowire.SizeTag(FieldTypeID) + protowire.SizeVarint(uint64(num)) } // Unmarshal parses a MessageSet. // // It calls fn with the type ID and value of each item in the MessageSet. // Unknown fields are discarded. // // If wantLen is true, the item values include the varint length prefix. // This is ugly, but simplifies the fast-path decoder in internal/impl. func Unmarshal(b []byte, wantLen bool, fn func(typeID protowire.Number, value []byte) error) error { for len(b) > 0 { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return protowire.ParseError(n) } b = b[n:] if num != FieldItem || wtyp != protowire.StartGroupType { n := protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return protowire.ParseError(n) } b = b[n:] continue } typeID, value, n, err := ConsumeFieldValue(b, wantLen) if err != nil { return err } b = b[n:] if typeID == 0 { continue } if err := fn(typeID, value); err != nil { return err } } return nil } // ConsumeFieldValue parses b as a MessageSet item field value until and including // the trailing end group marker. It assumes the start group tag has already been parsed. // It returns the contents of the type_id and message subfields and the total // item length. // // If wantLen is true, the returned message value includes the length prefix. func ConsumeFieldValue(b []byte, wantLen bool) (typeid protowire.Number, message []byte, n int, err error) { ilen := len(b) for { num, wtyp, n := protowire.ConsumeTag(b) if n < 0 { return 0, nil, 0, protowire.ParseError(n) } b = b[n:] switch { case num == FieldItem && wtyp == protowire.EndGroupType: if wantLen && len(message) == 0 { // The message field was missing, which should never happen. // Be prepared for this case anyway. message = protowire.AppendVarint(message, 0) } return typeid, message, ilen - len(b), nil case num == FieldTypeID && wtyp == protowire.VarintType: v, n := protowire.ConsumeVarint(b) if n < 0 { return 0, nil, 0, protowire.ParseError(n) } b = b[n:] if v < 1 || v > math.MaxInt32 { return 0, nil, 0, errors.New("invalid type_id in message set") } typeid = protowire.Number(v) case num == FieldMessage && wtyp == protowire.BytesType: m, n := protowire.ConsumeBytes(b) if n < 0 { return 0, nil, 0, protowire.ParseError(n) } if message == nil { if wantLen { message = b[:n:n] } else { message = m[:len(m):len(m)] } } else { // This case should never happen in practice, but handle it for // correctness: The MessageSet item contains multiple message // fields, which need to be merged. // // In the case where we're returning the length, this becomes // quite inefficient since we need to strip the length off // the existing data and reconstruct it with the combined length. if wantLen { _, nn := protowire.ConsumeVarint(message) m0 := message[nn:] message = nil message = protowire.AppendVarint(message, uint64(len(m0)+len(m))) message = append(message, m0...) message = append(message, m...) } else { message = append(message, m...) } } b = b[n:] default: // We have no place to put it, so we just ignore unknown fields. n := protowire.ConsumeFieldValue(num, wtyp, b) if n < 0 { return 0, nil, 0, protowire.ParseError(n) } b = b[n:] } } } // AppendFieldStart appends the start of a MessageSet item field containing // an extension with the given number. The caller must add the message // subfield (including the tag). func AppendFieldStart(b []byte, num protowire.Number) []byte { b = protowire.AppendTag(b, FieldItem, protowire.StartGroupType) b = protowire.AppendTag(b, FieldTypeID, protowire.VarintType) b = protowire.AppendVarint(b, uint64(num)) return b } // AppendFieldEnd appends the trailing end group marker for a MessageSet item field. func AppendFieldEnd(b []byte) []byte { return protowire.AppendTag(b, FieldItem, protowire.EndGroupType) } // SizeUnknown returns the size of an unknown fields section in MessageSet format. // // See AppendUnknown. func SizeUnknown(unknown []byte) (size int) { for len(unknown) > 0 { num, typ, n := protowire.ConsumeTag(unknown) if n < 0 || typ != protowire.BytesType { return 0 } unknown = unknown[n:] _, n = protowire.ConsumeBytes(unknown) if n < 0 { return 0 } unknown = unknown[n:] size += SizeField(num) + protowire.SizeTag(FieldMessage) + n } return size } // AppendUnknown appends unknown fields to b in MessageSet format. // // For historic reasons, unresolved items in a MessageSet are stored in a // message's unknown fields section in non-MessageSet format. That is, an // unknown item with typeID T and value V appears in the unknown fields as // a field with number T and value V. // // This function converts the unknown fields back into MessageSet form. func AppendUnknown(b, unknown []byte) ([]byte, error) { for len(unknown) > 0 { num, typ, n := protowire.ConsumeTag(unknown) if n < 0 || typ != protowire.BytesType { return nil, errors.New("invalid data in message set unknown fields") } unknown = unknown[n:] _, n = protowire.ConsumeBytes(unknown) if n < 0 { return nil, errors.New("invalid data in message set unknown fields") } b = AppendFieldStart(b, num) b = protowire.AppendTag(b, FieldMessage, protowire.BytesType) b = append(b, unknown[:n]...) b = AppendFieldEnd(b) unknown = unknown[n:] } 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/encoding/tag/tag.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/tag/tag.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 tag marshals and unmarshals the legacy struct tags as generated // by historical versions of protoc-gen-go. package tag import ( "reflect" "strconv" "strings" "google.golang.org/protobuf/internal/encoding/defval" "google.golang.org/protobuf/internal/filedesc" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) var byteType = reflect.TypeOf(byte(0)) // Unmarshal decodes the tag into a prototype.Field. // // The goType is needed to determine the original protoreflect.Kind since the // tag does not record sufficient information to determine that. // The type is the underlying field type (e.g., a repeated field may be // represented by []T, but the Go type passed in is just T). // A list of enum value descriptors must be provided for enum fields. // This does not populate the Enum or Message. // // This function is a best effort attempt; parsing errors are ignored. func Unmarshal(tag string, goType reflect.Type, evs protoreflect.EnumValueDescriptors) protoreflect.FieldDescriptor { f := new(filedesc.Field) f.L0.ParentFile = filedesc.SurrogateProto2 f.L1.EditionFeatures = f.L0.ParentFile.L1.EditionFeatures for len(tag) > 0 { i := strings.IndexByte(tag, ',') if i < 0 { i = len(tag) } switch s := tag[:i]; { case strings.HasPrefix(s, "name="): f.L0.FullName = protoreflect.FullName(s[len("name="):]) case strings.Trim(s, "0123456789") == "": n, _ := strconv.ParseUint(s, 10, 32) f.L1.Number = protoreflect.FieldNumber(n) case s == "opt": f.L1.Cardinality = protoreflect.Optional case s == "req": f.L1.Cardinality = protoreflect.Required case s == "rep": f.L1.Cardinality = protoreflect.Repeated case s == "varint": switch goType.Kind() { case reflect.Bool: f.L1.Kind = protoreflect.BoolKind case reflect.Int32: f.L1.Kind = protoreflect.Int32Kind case reflect.Int64: f.L1.Kind = protoreflect.Int64Kind case reflect.Uint32: f.L1.Kind = protoreflect.Uint32Kind case reflect.Uint64: f.L1.Kind = protoreflect.Uint64Kind } case s == "zigzag32": if goType.Kind() == reflect.Int32 { f.L1.Kind = protoreflect.Sint32Kind } case s == "zigzag64": if goType.Kind() == reflect.Int64 { f.L1.Kind = protoreflect.Sint64Kind } case s == "fixed32": switch goType.Kind() { case reflect.Int32: f.L1.Kind = protoreflect.Sfixed32Kind case reflect.Uint32: f.L1.Kind = protoreflect.Fixed32Kind case reflect.Float32: f.L1.Kind = protoreflect.FloatKind } case s == "fixed64": switch goType.Kind() { case reflect.Int64: f.L1.Kind = protoreflect.Sfixed64Kind case reflect.Uint64: f.L1.Kind = protoreflect.Fixed64Kind case reflect.Float64: f.L1.Kind = protoreflect.DoubleKind } case s == "bytes": switch { case goType.Kind() == reflect.String: f.L1.Kind = protoreflect.StringKind case goType.Kind() == reflect.Slice && goType.Elem() == byteType: f.L1.Kind = protoreflect.BytesKind default: f.L1.Kind = protoreflect.MessageKind } case s == "group": f.L1.Kind = protoreflect.GroupKind case strings.HasPrefix(s, "enum="): f.L1.Kind = protoreflect.EnumKind case strings.HasPrefix(s, "json="): jsonName := s[len("json="):] if jsonName != strs.JSONCamelCase(string(f.L0.FullName.Name())) { f.L1.StringName.InitJSON(jsonName) } case s == "packed": f.L1.EditionFeatures.IsPacked = true case strings.HasPrefix(s, "def="): // The default tag is special in that everything afterwards is the // default regardless of the presence of commas. s, i = tag[len("def="):], len(tag) v, ev, _ := defval.Unmarshal(s, f.L1.Kind, evs, defval.GoTag) f.L1.Default = filedesc.DefaultValue(v, ev) case s == "proto3": f.L0.ParentFile = filedesc.SurrogateProto3 } tag = strings.TrimPrefix(tag[i:], ",") } // The generator uses the group message name instead of the field name. // We obtain the real field name by lowercasing the group name. if f.L1.Kind == protoreflect.GroupKind { f.L0.FullName = protoreflect.FullName(strings.ToLower(string(f.L0.FullName))) } return f } // Marshal encodes the protoreflect.FieldDescriptor as a tag. // // The enumName must be provided if the kind is an enum. // Historically, the formulation of the enum "name" was the proto package // dot-concatenated with the generated Go identifier for the enum type. // Depending on the context on how Marshal is called, there are different ways // through which that information is determined. As such it is the caller's // responsibility to provide a function to obtain that information. func Marshal(fd protoreflect.FieldDescriptor, enumName string) string { var tag []string switch fd.Kind() { case protoreflect.BoolKind, protoreflect.EnumKind, protoreflect.Int32Kind, protoreflect.Uint32Kind, protoreflect.Int64Kind, protoreflect.Uint64Kind: tag = append(tag, "varint") case protoreflect.Sint32Kind: tag = append(tag, "zigzag32") case protoreflect.Sint64Kind: tag = append(tag, "zigzag64") case protoreflect.Sfixed32Kind, protoreflect.Fixed32Kind, protoreflect.FloatKind: tag = append(tag, "fixed32") case protoreflect.Sfixed64Kind, protoreflect.Fixed64Kind, protoreflect.DoubleKind: tag = append(tag, "fixed64") case protoreflect.StringKind, protoreflect.BytesKind, protoreflect.MessageKind: tag = append(tag, "bytes") case protoreflect.GroupKind: tag = append(tag, "group") } tag = append(tag, strconv.Itoa(int(fd.Number()))) switch fd.Cardinality() { case protoreflect.Optional: tag = append(tag, "opt") case protoreflect.Required: tag = append(tag, "req") case protoreflect.Repeated: tag = append(tag, "rep") } if fd.IsPacked() { tag = append(tag, "packed") } name := string(fd.Name()) if fd.Kind() == protoreflect.GroupKind { // The name of the FieldDescriptor for a group field is // lowercased. To find the original capitalization, we // look in the field's MessageType. name = string(fd.Message().Name()) } tag = append(tag, "name="+name) if jsonName := fd.JSONName(); jsonName != "" && jsonName != name && !fd.IsExtension() { // NOTE: The jsonName != name condition is suspect, but it preserve // the exact same semantics from the previous generator. tag = append(tag, "json="+jsonName) } // The previous implementation does not tag extension fields as proto3, // even when the field is defined in a proto3 file. Match that behavior // for consistency. if fd.Syntax() == protoreflect.Proto3 && !fd.IsExtension() { tag = append(tag, "proto3") } if fd.Kind() == protoreflect.EnumKind && enumName != "" { tag = append(tag, "enum="+enumName) } if fd.ContainingOneof() != nil { tag = append(tag, "oneof") } // This must appear last in the tag, since commas in strings aren't escaped. if fd.HasDefault() { def, _ := defval.Marshal(fd.Default(), fd.DefaultEnumValue(), fd.Kind(), defval.GoTag) tag = append(tag, "def="+def) } return strings.Join(tag, ",") }
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/encoding/text/decode_number.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/decode_number.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 text // parseNumberValue parses a number from the input and returns a Token object. func (d *Decoder) parseNumberValue() (Token, bool) { in := d.in num := parseNumber(in) if num.size == 0 { return Token{}, false } numAttrs := num.kind if num.neg { numAttrs |= isNegative } tok := Token{ kind: Scalar, attrs: numberValue, pos: len(d.orig) - len(d.in), raw: d.in[:num.size], str: num.string(d.in), numAttrs: numAttrs, } d.consume(num.size) return tok, true } const ( numDec uint8 = (1 << iota) / 2 numHex numOct numFloat ) // number is the result of parsing out a valid number from parseNumber. It // contains data for doing float or integer conversion via the strconv package // in conjunction with the input bytes. type number struct { kind uint8 neg bool size int // if neg, this is the length of whitespace and comments between // the minus sign and the rest fo the number literal sep int } func (num number) string(data []byte) string { strSize := num.size last := num.size - 1 if num.kind == numFloat && (data[last] == 'f' || data[last] == 'F') { strSize = last } if num.neg && num.sep > 0 { // strip whitespace/comments between negative sign and the rest strLen := strSize - num.sep str := make([]byte, strLen) str[0] = data[0] copy(str[1:], data[num.sep+1:strSize]) return string(str) } return string(data[:strSize]) } // parseNumber constructs a number object from given input. It allows for the // following patterns: // // integer: ^-?([1-9][0-9]*|0[xX][0-9a-fA-F]+|0[0-7]*) // float: ^-?((0|[1-9][0-9]*)?([.][0-9]*)?([eE][+-]?[0-9]+)?[fF]?) // // It also returns the number of parsed bytes for the given number, 0 if it is // not a number. func parseNumber(input []byte) number { kind := numDec var size int var neg bool s := input if len(s) == 0 { return number{} } // Optional - var sep int if s[0] == '-' { neg = true s = s[1:] size++ // Consume any whitespace or comments between the // negative sign and the rest of the number lenBefore := len(s) s = consume(s, 0) sep = lenBefore - len(s) size += sep if len(s) == 0 { return number{} } } switch { case s[0] == '0': if len(s) > 1 { switch { case s[1] == 'x' || s[1] == 'X': // Parse as hex number. kind = numHex n := 2 s = s[2:] for len(s) > 0 && (('0' <= s[0] && s[0] <= '9') || ('a' <= s[0] && s[0] <= 'f') || ('A' <= s[0] && s[0] <= 'F')) { s = s[1:] n++ } if n == 2 { return number{} } size += n case '0' <= s[1] && s[1] <= '7': // Parse as octal number. kind = numOct n := 2 s = s[2:] for len(s) > 0 && '0' <= s[0] && s[0] <= '7' { s = s[1:] n++ } size += n } if kind&(numHex|numOct) > 0 { if len(s) > 0 && !isDelim(s[0]) { return number{} } return number{kind: kind, neg: neg, size: size, sep: sep} } } s = s[1:] size++ case '1' <= s[0] && s[0] <= '9': n := 1 s = s[1:] for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } size += n case s[0] == '.': // Set kind to numFloat to signify the intent to parse as float. And // that it needs to have other digits after '.'. kind = numFloat default: return number{} } // . followed by 0 or more digits. if len(s) > 0 && s[0] == '.' { n := 1 s = s[1:] // If decimal point was before any digits, it should be followed by // other digits. if len(s) == 0 && kind == numFloat { return number{} } for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } size += n kind = numFloat } // e or E followed by an optional - or + and 1 or more digits. if len(s) >= 2 && (s[0] == 'e' || s[0] == 'E') { kind = numFloat s = s[1:] n := 1 if s[0] == '+' || s[0] == '-' { s = s[1:] n++ if len(s) == 0 { return number{} } } for len(s) > 0 && '0' <= s[0] && s[0] <= '9' { s = s[1:] n++ } size += n } // Optional suffix f or F for floats. if len(s) > 0 && (s[0] == 'f' || s[0] == 'F') { kind = numFloat s = s[1:] size++ } // Check that next byte is a delimiter or it is at the end. if len(s) > 0 && !isDelim(s[0]) { return number{} } return number{kind: kind, neg: neg, size: size, sep: sep} }
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/encoding/text/encode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/encode.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 text import ( "math" "math/bits" "strconv" "strings" "unicode/utf8" "google.golang.org/protobuf/internal/detrand" "google.golang.org/protobuf/internal/errors" ) // encType represents an encoding type. type encType uint8 const ( _ encType = (1 << iota) / 2 name scalar messageOpen messageClose ) // Encoder provides methods to write out textproto constructs and values. The user is // responsible for producing valid sequences of constructs and values. type Encoder struct { encoderState indent string delims [2]byte outputASCII bool } type encoderState struct { lastType encType indents []byte out []byte } // NewEncoder returns an Encoder. // // If indent is a non-empty string, it causes every entry in a List or Message // to be preceded by the indent and trailed by a newline. // // If delims is not the zero value, it controls the delimiter characters used // for messages (e.g., "{}" vs "<>"). // // If outputASCII is true, strings will be serialized in such a way that // multi-byte UTF-8 sequences are escaped. This property ensures that the // overall output is ASCII (as opposed to UTF-8). func NewEncoder(buf []byte, indent string, delims [2]byte, outputASCII bool) (*Encoder, error) { e := &Encoder{ encoderState: encoderState{out: buf}, } if len(indent) > 0 { if strings.Trim(indent, " \t") != "" { return nil, errors.New("indent may only be composed of space and tab characters") } e.indent = indent } switch delims { case [2]byte{0, 0}: e.delims = [2]byte{'{', '}'} case [2]byte{'{', '}'}, [2]byte{'<', '>'}: e.delims = delims default: return nil, errors.New("delimiters may only be \"{}\" or \"<>\"") } e.outputASCII = outputASCII return e, nil } // Bytes returns the content of the written bytes. func (e *Encoder) Bytes() []byte { return e.out } // StartMessage writes out the '{' or '<' symbol. func (e *Encoder) StartMessage() { e.prepareNext(messageOpen) e.out = append(e.out, e.delims[0]) } // EndMessage writes out the '}' or '>' symbol. func (e *Encoder) EndMessage() { e.prepareNext(messageClose) e.out = append(e.out, e.delims[1]) } // WriteName writes out the field name and the separator ':'. func (e *Encoder) WriteName(s string) { e.prepareNext(name) e.out = append(e.out, s...) e.out = append(e.out, ':') } // WriteBool writes out the given boolean value. func (e *Encoder) WriteBool(b bool) { if b { e.WriteLiteral("true") } else { e.WriteLiteral("false") } } // WriteString writes out the given string value. func (e *Encoder) WriteString(s string) { e.prepareNext(scalar) e.out = appendString(e.out, s, e.outputASCII) } func appendString(out []byte, in string, outputASCII bool) []byte { out = append(out, '"') i := indexNeedEscapeInString(in) in, out = in[i:], append(out, in[:i]...) for len(in) > 0 { switch r, n := utf8.DecodeRuneInString(in); { case r == utf8.RuneError && n == 1: // We do not report invalid UTF-8 because strings in the text format // are used to represent both the proto string and bytes type. r = rune(in[0]) fallthrough case r < ' ' || r == '"' || r == '\\' || r == 0x7f: out = append(out, '\\') switch r { case '"', '\\': out = append(out, byte(r)) case '\n': out = append(out, 'n') case '\r': out = append(out, 'r') case '\t': out = append(out, 't') default: out = append(out, 'x') out = append(out, "00"[1+(bits.Len32(uint32(r))-1)/4:]...) out = strconv.AppendUint(out, uint64(r), 16) } in = in[n:] case r >= utf8.RuneSelf && (outputASCII || r <= 0x009f): out = append(out, '\\') if r <= math.MaxUint16 { out = append(out, 'u') out = append(out, "0000"[1+(bits.Len32(uint32(r))-1)/4:]...) out = strconv.AppendUint(out, uint64(r), 16) } else { out = append(out, 'U') out = append(out, "00000000"[1+(bits.Len32(uint32(r))-1)/4:]...) out = strconv.AppendUint(out, uint64(r), 16) } in = in[n:] default: i := indexNeedEscapeInString(in[n:]) in, out = in[n+i:], append(out, in[:n+i]...) } } out = append(out, '"') return out } // indexNeedEscapeInString returns the index of the character that needs // escaping. If no characters need escaping, this returns the input length. func indexNeedEscapeInString(s string) int { for i := 0; i < len(s); i++ { if c := s[i]; c < ' ' || c == '"' || c == '\'' || c == '\\' || c >= 0x7f { return i } } return len(s) } // WriteFloat writes out the given float value for given bitSize. func (e *Encoder) WriteFloat(n float64, bitSize int) { e.prepareNext(scalar) e.out = appendFloat(e.out, n, bitSize) } func appendFloat(out []byte, n float64, bitSize int) []byte { switch { case math.IsNaN(n): return append(out, "nan"...) case math.IsInf(n, +1): return append(out, "inf"...) case math.IsInf(n, -1): return append(out, "-inf"...) default: return strconv.AppendFloat(out, n, 'g', -1, bitSize) } } // WriteInt writes out the given signed integer value. func (e *Encoder) WriteInt(n int64) { e.prepareNext(scalar) e.out = strconv.AppendInt(e.out, n, 10) } // WriteUint writes out the given unsigned integer value. func (e *Encoder) WriteUint(n uint64) { e.prepareNext(scalar) e.out = strconv.AppendUint(e.out, n, 10) } // WriteLiteral writes out the given string as a literal value without quotes. // This is used for writing enum literal strings. func (e *Encoder) WriteLiteral(s string) { e.prepareNext(scalar) e.out = append(e.out, s...) } // prepareNext adds possible space and indentation for the next value based // on last encType and indent option. It also updates e.lastType to next. func (e *Encoder) prepareNext(next encType) { defer func() { e.lastType = next }() // Single line. if len(e.indent) == 0 { // Add space after each field before the next one. if e.lastType&(scalar|messageClose) != 0 && next == name { e.out = append(e.out, ' ') // Add a random extra space to make output unstable. if detrand.Bool() { e.out = append(e.out, ' ') } } return } // Multi-line. switch { case e.lastType == name: e.out = append(e.out, ' ') // Add a random extra space after name: to make output unstable. if detrand.Bool() { e.out = append(e.out, ' ') } case e.lastType == messageOpen && next != messageClose: e.indents = append(e.indents, e.indent...) e.out = append(e.out, '\n') e.out = append(e.out, e.indents...) case e.lastType&(scalar|messageClose) != 0: if next == messageClose { e.indents = e.indents[:len(e.indents)-len(e.indent)] } e.out = append(e.out, '\n') e.out = append(e.out, e.indents...) } } // Snapshot returns the current snapshot for use in Reset. func (e *Encoder) Snapshot() encoderState { return e.encoderState } // Reset resets the Encoder to the given encoderState from a Snapshot. func (e *Encoder) Reset(es encoderState) { e.encoderState = es } // AppendString appends the escaped form of the input string to b. func AppendString(b []byte, s string) []byte { return appendString(b, s, 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/encoding/text/decode_token.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/decode_token.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 text import ( "bytes" "fmt" "math" "strconv" "strings" "google.golang.org/protobuf/internal/flags" ) // Kind represents a token kind expressible in the textproto format. type Kind uint8 // Kind values. const ( Invalid Kind = iota EOF Name // Name indicates the field name. Scalar // Scalar are scalar values, e.g. "string", 47, ENUM_LITERAL, true. MessageOpen MessageClose ListOpen ListClose // comma and semi-colon are only for parsing in between values and should not be exposed. comma semicolon // bof indicates beginning of file, which is the default token // kind at the beginning of parsing. bof = Invalid ) func (t Kind) String() string { switch t { case Invalid: return "<invalid>" case EOF: return "eof" case Scalar: return "scalar" case Name: return "name" case MessageOpen: return "{" case MessageClose: return "}" case ListOpen: return "[" case ListClose: return "]" case comma: return "," case semicolon: return ";" default: return fmt.Sprintf("<invalid:%v>", uint8(t)) } } // NameKind represents different types of field names. type NameKind uint8 // NameKind values. const ( IdentName NameKind = iota + 1 TypeName FieldNumber ) func (t NameKind) String() string { switch t { case IdentName: return "IdentName" case TypeName: return "TypeName" case FieldNumber: return "FieldNumber" default: return fmt.Sprintf("<invalid:%v>", uint8(t)) } } // Bit mask in Token.attrs to indicate if a Name token is followed by the // separator char ':'. The field name separator char is optional for message // field or repeated message field, but required for all other types. Decoder // simply indicates whether a Name token is followed by separator or not. It is // up to the prototext package to validate. const hasSeparator = 1 << 7 // Scalar value types. const ( numberValue = iota + 1 stringValue literalValue ) // Bit mask in Token.numAttrs to indicate that the number is a negative. const isNegative = 1 << 7 // Token provides a parsed token kind and value. Values are provided by the // different accessor methods. type Token struct { // Kind of the Token object. kind Kind // attrs contains metadata for the following Kinds: // Name: hasSeparator bit and one of NameKind. // Scalar: one of numberValue, stringValue, literalValue. attrs uint8 // numAttrs contains metadata for numberValue: // - highest bit is whether negative or positive. // - lower bits indicate one of numDec, numHex, numOct, numFloat. numAttrs uint8 // pos provides the position of the token in the original input. pos int // raw bytes of the serialized token. // This is a subslice into the original input. raw []byte // str contains parsed string for the following: // - stringValue of Scalar kind // - numberValue of Scalar kind // - TypeName of Name kind str string } // Kind returns the token kind. func (t Token) Kind() Kind { return t.kind } // RawString returns the read value in string. func (t Token) RawString() string { return string(t.raw) } // Pos returns the token position from the input. func (t Token) Pos() int { return t.pos } // NameKind returns IdentName, TypeName or FieldNumber. // It panics if type is not Name. func (t Token) NameKind() NameKind { if t.kind == Name { return NameKind(t.attrs &^ hasSeparator) } panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) } // HasSeparator returns true if the field name is followed by the separator char // ':', else false. It panics if type is not Name. func (t Token) HasSeparator() bool { if t.kind == Name { return t.attrs&hasSeparator != 0 } panic(fmt.Sprintf("Token is not a Name type: %s", t.kind)) } // IdentName returns the value for IdentName type. func (t Token) IdentName() string { if t.kind == Name && t.attrs&uint8(IdentName) != 0 { return string(t.raw) } panic(fmt.Sprintf("Token is not an IdentName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // TypeName returns the value for TypeName type. func (t Token) TypeName() string { if t.kind == Name && t.attrs&uint8(TypeName) != 0 { return t.str } panic(fmt.Sprintf("Token is not a TypeName: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // FieldNumber returns the value for FieldNumber type. It returns a // non-negative int32 value. Caller will still need to validate for the correct // field number range. func (t Token) FieldNumber() int32 { if t.kind != Name || t.attrs&uint8(FieldNumber) == 0 { panic(fmt.Sprintf("Token is not a FieldNumber: %s:%s", t.kind, NameKind(t.attrs&^hasSeparator))) } // Following should not return an error as it had already been called right // before this Token was constructed. num, _ := strconv.ParseInt(string(t.raw), 10, 32) return int32(num) } // String returns the string value for a Scalar type. func (t Token) String() (string, bool) { if t.kind != Scalar || t.attrs != stringValue { return "", false } return t.str, true } // Enum returns the literal value for a Scalar type for use as enum literals. func (t Token) Enum() (string, bool) { if t.kind != Scalar || t.attrs != literalValue || (len(t.raw) > 0 && t.raw[0] == '-') { return "", false } return string(t.raw), true } // Bool returns the bool value for a Scalar type. func (t Token) Bool() (bool, bool) { if t.kind != Scalar { return false, false } switch t.attrs { case literalValue: if b, ok := boolLits[string(t.raw)]; ok { return b, true } case numberValue: // Unsigned integer representation of 0 or 1 is permitted: 00, 0x0, 01, // 0x1, etc. n, err := strconv.ParseUint(t.str, 0, 64) if err == nil { switch n { case 0: return false, true case 1: return true, true } } } return false, false } // These exact boolean literals are the ones supported in C++. var boolLits = map[string]bool{ "t": true, "true": true, "True": true, "f": false, "false": false, "False": false, } // Uint64 returns the uint64 value for a Scalar type. func (t Token) Uint64() (uint64, bool) { if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&isNegative > 0 || t.numAttrs&numFloat > 0 { return 0, false } n, err := strconv.ParseUint(t.str, 0, 64) if err != nil { return 0, false } return n, true } // Uint32 returns the uint32 value for a Scalar type. func (t Token) Uint32() (uint32, bool) { if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&isNegative > 0 || t.numAttrs&numFloat > 0 { return 0, false } n, err := strconv.ParseUint(t.str, 0, 32) if err != nil { return 0, false } return uint32(n), true } // Int64 returns the int64 value for a Scalar type. func (t Token) Int64() (int64, bool) { if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&numFloat > 0 { return 0, false } if n, err := strconv.ParseInt(t.str, 0, 64); err == nil { return n, true } // C++ accepts large positive hex numbers as negative values. // This feature is here for proto1 backwards compatibility purposes. if flags.ProtoLegacy && (t.numAttrs == numHex) { if n, err := strconv.ParseUint(t.str, 0, 64); err == nil { return int64(n), true } } return 0, false } // Int32 returns the int32 value for a Scalar type. func (t Token) Int32() (int32, bool) { if t.kind != Scalar || t.attrs != numberValue || t.numAttrs&numFloat > 0 { return 0, false } if n, err := strconv.ParseInt(t.str, 0, 32); err == nil { return int32(n), true } // C++ accepts large positive hex numbers as negative values. // This feature is here for proto1 backwards compatibility purposes. if flags.ProtoLegacy && (t.numAttrs == numHex) { if n, err := strconv.ParseUint(t.str, 0, 32); err == nil { return int32(n), true } } return 0, false } // Float64 returns the float64 value for a Scalar type. func (t Token) Float64() (float64, bool) { if t.kind != Scalar { return 0, false } switch t.attrs { case literalValue: if f, ok := floatLits[strings.ToLower(string(t.raw))]; ok { return f, true } case numberValue: n, err := strconv.ParseFloat(t.str, 64) if err == nil { return n, true } nerr := err.(*strconv.NumError) if nerr.Err == strconv.ErrRange { return n, true } } return 0, false } // Float32 returns the float32 value for a Scalar type. func (t Token) Float32() (float32, bool) { if t.kind != Scalar { return 0, false } switch t.attrs { case literalValue: if f, ok := floatLits[strings.ToLower(string(t.raw))]; ok { return float32(f), true } case numberValue: n, err := strconv.ParseFloat(t.str, 64) if err == nil { // Overflows are treated as (-)infinity. return float32(n), true } nerr := err.(*strconv.NumError) if nerr.Err == strconv.ErrRange { return float32(n), true } } return 0, false } // These are the supported float literals which C++ permits case-insensitive // variants of these. var floatLits = map[string]float64{ "nan": math.NaN(), "inf": math.Inf(1), "infinity": math.Inf(1), "-inf": math.Inf(-1), "-infinity": math.Inf(-1), } // TokenEquals returns true if given Tokens are equal, else false. func TokenEquals(x, y Token) bool { return x.kind == y.kind && x.attrs == y.attrs && x.numAttrs == y.numAttrs && x.pos == y.pos && bytes.Equal(x.raw, y.raw) && x.str == y.str }
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/encoding/text/decode_string.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/decode_string.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 text import ( "bytes" "strconv" "strings" "unicode" "unicode/utf16" "unicode/utf8" "google.golang.org/protobuf/internal/strs" ) // parseStringValue parses string field token. // This differs from parseString since the text format allows // multiple back-to-back string literals where they are semantically treated // as a single large string with all values concatenated. // // E.g., `"foo" "bar" "baz"` => "foobarbaz" func (d *Decoder) parseStringValue() (Token, error) { // Note that the ending quote is sufficient to unambiguously mark the end // of a string. Thus, the text grammar does not require intervening // whitespace or control characters in-between strings. // Thus, the following is valid: // `"foo"'bar'"baz"` => "foobarbaz" in0 := d.in var ss []string for len(d.in) > 0 && (d.in[0] == '"' || d.in[0] == '\'') { s, err := d.parseString() if err != nil { return Token{}, err } ss = append(ss, s) } // d.in already points to the end of the value at this point. return Token{ kind: Scalar, attrs: stringValue, pos: len(d.orig) - len(in0), raw: in0[:len(in0)-len(d.in)], str: strings.Join(ss, ""), }, nil } // parseString parses a string value enclosed in " or '. func (d *Decoder) parseString() (string, error) { in := d.in if len(in) == 0 { return "", ErrUnexpectedEOF } quote := in[0] in = in[1:] i := indexNeedEscapeInBytes(in) in, out := in[i:], in[:i:i] // set cap to prevent mutations for len(in) > 0 { switch r, n := utf8.DecodeRune(in); { case r == utf8.RuneError && n == 1: return "", d.newSyntaxError("invalid UTF-8 detected") case r == 0 || r == '\n': return "", d.newSyntaxError("invalid character %q in string", r) case r == rune(quote): in = in[1:] d.consume(len(d.in) - len(in)) return string(out), nil case r == '\\': if len(in) < 2 { return "", ErrUnexpectedEOF } switch r := in[1]; r { case '"', '\'', '\\', '?': in, out = in[2:], append(out, r) case 'a': in, out = in[2:], append(out, '\a') case 'b': in, out = in[2:], append(out, '\b') case 'n': in, out = in[2:], append(out, '\n') case 'r': in, out = in[2:], append(out, '\r') case 't': in, out = in[2:], append(out, '\t') case 'v': in, out = in[2:], append(out, '\v') case 'f': in, out = in[2:], append(out, '\f') case '0', '1', '2', '3', '4', '5', '6', '7': // One, two, or three octal characters. n := len(in[1:]) - len(bytes.TrimLeft(in[1:], "01234567")) if n > 3 { n = 3 } v, err := strconv.ParseUint(string(in[1:1+n]), 8, 8) if err != nil { return "", d.newSyntaxError("invalid octal escape code %q in string", in[:1+n]) } in, out = in[1+n:], append(out, byte(v)) case 'x': // One or two hexadecimal characters. n := len(in[2:]) - len(bytes.TrimLeft(in[2:], "0123456789abcdefABCDEF")) if n > 2 { n = 2 } v, err := strconv.ParseUint(string(in[2:2+n]), 16, 8) if err != nil { return "", d.newSyntaxError("invalid hex escape code %q in string", in[:2+n]) } in, out = in[2+n:], append(out, byte(v)) case 'u', 'U': // Four or eight hexadecimal characters n := 6 if r == 'U' { n = 10 } if len(in) < n { return "", ErrUnexpectedEOF } v, err := strconv.ParseUint(string(in[2:n]), 16, 32) if utf8.MaxRune < v || err != nil { return "", d.newSyntaxError("invalid Unicode escape code %q in string", in[:n]) } in = in[n:] r := rune(v) if utf16.IsSurrogate(r) { if len(in) < 6 { return "", ErrUnexpectedEOF } v, err := strconv.ParseUint(string(in[2:6]), 16, 16) r = utf16.DecodeRune(r, rune(v)) if in[0] != '\\' || in[1] != 'u' || r == unicode.ReplacementChar || err != nil { return "", d.newSyntaxError("invalid Unicode escape code %q in string", in[:6]) } in = in[6:] } out = append(out, string(r)...) default: return "", d.newSyntaxError("invalid escape code %q in string", in[:2]) } default: i := indexNeedEscapeInBytes(in[n:]) in, out = in[n+i:], append(out, in[:n+i]...) } } return "", ErrUnexpectedEOF } // indexNeedEscapeInString returns the index of the character that needs // escaping. If no characters need escaping, this returns the input length. func indexNeedEscapeInBytes(b []byte) int { return indexNeedEscapeInString(strs.UnsafeString(b)) } // UnmarshalString returns an unescaped string given a textproto string value. // String value needs to contain single or double quotes. This is only used by // internal/encoding/defval package for unmarshaling bytes. func UnmarshalString(s string) (string, error) { d := NewDecoder([]byte(s)) return d.parseString() }
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/encoding/text/doc.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/doc.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 text implements the text format for protocol buffers. // This package has no semantic understanding for protocol buffers and is only // a parser and composer for the format. // // There is no formal specification for the protobuf text format, as such the // C++ implementation (see google::protobuf::TextFormat) is the reference // implementation of the text format. // // This package is neither a superset nor a subset of the C++ implementation. // This implementation permits a more liberal grammar in some cases to be // backwards compatible with the historical Go implementation. // Future parsings unique to Go should not be added. // Some grammars allowed by the C++ implementation are deliberately // not implemented here because they are considered a bug by the protobuf team // and should not be replicated. // // The Go implementation should implement a sufficient amount of the C++ // grammar such that the default text serialization by C++ can be parsed by Go. // However, just because the C++ parser accepts some input does not mean that // the Go implementation should as well. // // The text format is almost a superset of JSON except: // - message keys are not quoted strings, but identifiers // - the top-level value must be a message without the delimiters package text
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/encoding/text/decode.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/encoding/text/decode.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 text import ( "bytes" "fmt" "io" "strconv" "unicode/utf8" "google.golang.org/protobuf/internal/errors" ) // Decoder is a token-based textproto decoder. type Decoder struct { // lastCall is last method called, either readCall or peekCall. // Initial value is readCall. lastCall call // lastToken contains the last read token. lastToken Token // lastErr contains the last read error. lastErr error // openStack is a stack containing the byte characters for MessageOpen and // ListOpen kinds. The top of stack represents the message or the list that // the current token is nested in. An empty stack means the current token is // at the top level message. The characters '{' and '<' both represent the // MessageOpen kind. openStack []byte // orig is used in reporting line and column. orig []byte // in contains the unconsumed input. in []byte } // NewDecoder returns a Decoder to read the given []byte. func NewDecoder(b []byte) *Decoder { return &Decoder{orig: b, in: b} } // ErrUnexpectedEOF means that EOF was encountered in the middle of the input. var ErrUnexpectedEOF = errors.New("%v", io.ErrUnexpectedEOF) // call specifies which Decoder method was invoked. type call uint8 const ( readCall call = iota peekCall ) // Peek looks ahead and returns the next token and error without advancing a read. func (d *Decoder) Peek() (Token, error) { defer func() { d.lastCall = peekCall }() if d.lastCall == readCall { d.lastToken, d.lastErr = d.Read() } return d.lastToken, d.lastErr } // Read returns the next token. // It will return an error if there is no valid token. func (d *Decoder) Read() (Token, error) { defer func() { d.lastCall = readCall }() if d.lastCall == peekCall { return d.lastToken, d.lastErr } tok, err := d.parseNext(d.lastToken.kind) if err != nil { return Token{}, err } switch tok.kind { case comma, semicolon: tok, err = d.parseNext(tok.kind) if err != nil { return Token{}, err } } d.lastToken = tok return tok, nil } const ( mismatchedFmt = "mismatched close character %q" unexpectedFmt = "unexpected character %q" ) // parseNext parses the next Token based on given last kind. func (d *Decoder) parseNext(lastKind Kind) (Token, error) { // Trim leading spaces. d.consume(0) isEOF := false if len(d.in) == 0 { isEOF = true } switch lastKind { case EOF: return d.consumeToken(EOF, 0, 0), nil case bof: // Start of top level message. Next token can be EOF or Name. if isEOF { return d.consumeToken(EOF, 0, 0), nil } return d.parseFieldName() case Name: // Next token can be MessageOpen, ListOpen or Scalar. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case '{', '<': d.pushOpenStack(ch) return d.consumeToken(MessageOpen, 1, 0), nil case '[': d.pushOpenStack(ch) return d.consumeToken(ListOpen, 1, 0), nil default: return d.parseScalar() } case Scalar: openKind, closeCh := d.currentOpenKind() switch openKind { case bof: // Top level message. // Next token can be EOF, comma, semicolon or Name. if isEOF { return d.consumeToken(EOF, 0, 0), nil } switch d.in[0] { case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } case MessageOpen: // Next token can be MessageClose, comma, semicolon or Name. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(MessageClose, 1, 0), nil case otherCloseChar[closeCh]: return Token{}, d.newSyntaxError(mismatchedFmt, ch) case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } case ListOpen: // Next token can be ListClose or comma. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case ']': d.popOpenStack() return d.consumeToken(ListClose, 1, 0), nil case ',': return d.consumeToken(comma, 1, 0), nil default: return Token{}, d.newSyntaxError(unexpectedFmt, ch) } } case MessageOpen: // Next token can be MessageClose or Name. if isEOF { return Token{}, ErrUnexpectedEOF } _, closeCh := d.currentOpenKind() switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(MessageClose, 1, 0), nil case otherCloseChar[closeCh]: return Token{}, d.newSyntaxError(mismatchedFmt, ch) default: return d.parseFieldName() } case MessageClose: openKind, closeCh := d.currentOpenKind() switch openKind { case bof: // Top level message. // Next token can be EOF, comma, semicolon or Name. if isEOF { return d.consumeToken(EOF, 0, 0), nil } switch ch := d.in[0]; ch { case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } case MessageOpen: // Next token can be MessageClose, comma, semicolon or Name. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(MessageClose, 1, 0), nil case otherCloseChar[closeCh]: return Token{}, d.newSyntaxError(mismatchedFmt, ch) case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } case ListOpen: // Next token can be ListClose or comma if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(ListClose, 1, 0), nil case ',': return d.consumeToken(comma, 1, 0), nil default: return Token{}, d.newSyntaxError(unexpectedFmt, ch) } } case ListOpen: // Next token can be ListClose, MessageStart or Scalar. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case ']': d.popOpenStack() return d.consumeToken(ListClose, 1, 0), nil case '{', '<': d.pushOpenStack(ch) return d.consumeToken(MessageOpen, 1, 0), nil default: return d.parseScalar() } case ListClose: openKind, closeCh := d.currentOpenKind() switch openKind { case bof: // Top level message. // Next token can be EOF, comma, semicolon or Name. if isEOF { return d.consumeToken(EOF, 0, 0), nil } switch ch := d.in[0]; ch { case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } case MessageOpen: // Next token can be MessageClose, comma, semicolon or Name. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(MessageClose, 1, 0), nil case otherCloseChar[closeCh]: return Token{}, d.newSyntaxError(mismatchedFmt, ch) case ',': return d.consumeToken(comma, 1, 0), nil case ';': return d.consumeToken(semicolon, 1, 0), nil default: return d.parseFieldName() } default: // It is not possible to have this case. Let it panic below. } case comma, semicolon: openKind, closeCh := d.currentOpenKind() switch openKind { case bof: // Top level message. Next token can be EOF or Name. if isEOF { return d.consumeToken(EOF, 0, 0), nil } return d.parseFieldName() case MessageOpen: // Next token can be MessageClose or Name. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case closeCh: d.popOpenStack() return d.consumeToken(MessageClose, 1, 0), nil case otherCloseChar[closeCh]: return Token{}, d.newSyntaxError(mismatchedFmt, ch) default: return d.parseFieldName() } case ListOpen: if lastKind == semicolon { // It is not be possible to have this case as logic here // should not have produced a semicolon Token when inside a // list. Let it panic below. break } // Next token can be MessageOpen or Scalar. if isEOF { return Token{}, ErrUnexpectedEOF } switch ch := d.in[0]; ch { case '{', '<': d.pushOpenStack(ch) return d.consumeToken(MessageOpen, 1, 0), nil default: return d.parseScalar() } } } line, column := d.Position(len(d.orig) - len(d.in)) panic(fmt.Sprintf("Decoder.parseNext: bug at handling line %d:%d with lastKind=%v", line, column, lastKind)) } var otherCloseChar = map[byte]byte{ '}': '>', '>': '}', } // currentOpenKind indicates whether current position is inside a message, list // or top-level message by returning MessageOpen, ListOpen or bof respectively. // If the returned kind is either a MessageOpen or ListOpen, it also returns the // corresponding closing character. func (d *Decoder) currentOpenKind() (Kind, byte) { if len(d.openStack) == 0 { return bof, 0 } openCh := d.openStack[len(d.openStack)-1] switch openCh { case '{': return MessageOpen, '}' case '<': return MessageOpen, '>' case '[': return ListOpen, ']' } panic(fmt.Sprintf("Decoder: openStack contains invalid byte %c", openCh)) } func (d *Decoder) pushOpenStack(ch byte) { d.openStack = append(d.openStack, ch) } func (d *Decoder) popOpenStack() { d.openStack = d.openStack[:len(d.openStack)-1] } // parseFieldName parses field name and separator. func (d *Decoder) parseFieldName() (tok Token, err error) { defer func() { if err == nil && d.tryConsumeChar(':') { tok.attrs |= hasSeparator } }() // Extension or Any type URL. if d.in[0] == '[' { return d.parseTypeName() } // Identifier. if size := parseIdent(d.in, false); size > 0 { return d.consumeToken(Name, size, uint8(IdentName)), nil } // Field number. Identify if input is a valid number that is not negative // and is decimal integer within 32-bit range. if num := parseNumber(d.in); num.size > 0 { str := num.string(d.in) if !num.neg && num.kind == numDec { if _, err := strconv.ParseInt(str, 10, 32); err == nil { return d.consumeToken(Name, num.size, uint8(FieldNumber)), nil } } return Token{}, d.newSyntaxError("invalid field number: %s", str) } return Token{}, d.newSyntaxError("invalid field name: %s", errId(d.in)) } // parseTypeName parses Any type URL or extension field name. The name is // enclosed in [ and ] characters. The C++ parser does not handle many legal URL // strings. This implementation is more liberal and allows for the pattern // ^[-_a-zA-Z0-9]+([./][-_a-zA-Z0-9]+)*`). Whitespaces and comments are allowed // in between [ ], '.', '/' and the sub names. func (d *Decoder) parseTypeName() (Token, error) { startPos := len(d.orig) - len(d.in) // Use alias s to advance first in order to use d.in for error handling. // Caller already checks for [ as first character. s := consume(d.in[1:], 0) if len(s) == 0 { return Token{}, ErrUnexpectedEOF } var name []byte for len(s) > 0 && isTypeNameChar(s[0]) { name = append(name, s[0]) s = s[1:] } s = consume(s, 0) var closed bool for len(s) > 0 && !closed { switch { case s[0] == ']': s = s[1:] closed = true case s[0] == '/', s[0] == '.': if len(name) > 0 && (name[len(name)-1] == '/' || name[len(name)-1] == '.') { return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", d.orig[startPos:len(d.orig)-len(s)+1]) } name = append(name, s[0]) s = s[1:] s = consume(s, 0) for len(s) > 0 && isTypeNameChar(s[0]) { name = append(name, s[0]) s = s[1:] } s = consume(s, 0) default: return Token{}, d.newSyntaxError( "invalid type URL/extension field name: %s", d.orig[startPos:len(d.orig)-len(s)+1]) } } if !closed { return Token{}, ErrUnexpectedEOF } // First character cannot be '.'. Last character cannot be '.' or '/'. size := len(name) if size == 0 || name[0] == '.' || name[size-1] == '.' || name[size-1] == '/' { return Token{}, d.newSyntaxError("invalid type URL/extension field name: %s", d.orig[startPos:len(d.orig)-len(s)]) } d.in = s endPos := len(d.orig) - len(d.in) d.consume(0) return Token{ kind: Name, attrs: uint8(TypeName), pos: startPos, raw: d.orig[startPos:endPos], str: string(name), }, nil } func isTypeNameChar(b byte) bool { return (b == '-' || b == '_' || ('0' <= b && b <= '9') || ('a' <= b && b <= 'z') || ('A' <= b && b <= 'Z')) } func isWhiteSpace(b byte) bool { switch b { case ' ', '\n', '\r', '\t': return true default: return false } } // parseIdent parses an unquoted proto identifier and returns size. // If allowNeg is true, it allows '-' to be the first character in the // identifier. This is used when parsing literal values like -infinity, etc. // Regular expression matches an identifier: `^[_a-zA-Z][_a-zA-Z0-9]*` func parseIdent(input []byte, allowNeg bool) int { var size int s := input if len(s) == 0 { return 0 } if allowNeg && s[0] == '-' { s = s[1:] size++ if len(s) == 0 { return 0 } } switch { case s[0] == '_', 'a' <= s[0] && s[0] <= 'z', 'A' <= s[0] && s[0] <= 'Z': s = s[1:] size++ default: return 0 } for len(s) > 0 && (s[0] == '_' || 'a' <= s[0] && s[0] <= 'z' || 'A' <= s[0] && s[0] <= 'Z' || '0' <= s[0] && s[0] <= '9') { s = s[1:] size++ } if len(s) > 0 && !isDelim(s[0]) { return 0 } return size } // parseScalar parses for a string, literal or number value. func (d *Decoder) parseScalar() (Token, error) { if d.in[0] == '"' || d.in[0] == '\'' { return d.parseStringValue() } if tok, ok := d.parseLiteralValue(); ok { return tok, nil } if tok, ok := d.parseNumberValue(); ok { return tok, nil } return Token{}, d.newSyntaxError("invalid scalar value: %s", errId(d.in)) } // parseLiteralValue parses a literal value. A literal value is used for // bools, special floats and enums. This function simply identifies that the // field value is a literal. func (d *Decoder) parseLiteralValue() (Token, bool) { size := parseIdent(d.in, true) if size == 0 { return Token{}, false } return d.consumeToken(Scalar, size, literalValue), true } // consumeToken constructs a Token for given Kind from d.in and consumes given // size-length from it. func (d *Decoder) consumeToken(kind Kind, size int, attrs uint8) Token { // Important to compute raw and pos before consuming. tok := Token{ kind: kind, attrs: attrs, pos: len(d.orig) - len(d.in), raw: d.in[:size], } d.consume(size) return tok } // newSyntaxError returns a syntax error with line and column information for // current position. func (d *Decoder) newSyntaxError(f string, x ...any) error { e := errors.New(f, x...) line, column := d.Position(len(d.orig) - len(d.in)) return errors.New("syntax error (line %d:%d): %v", line, column, e) } // Position returns line and column number of given index of the original input. // It will panic if index is out of range. func (d *Decoder) Position(idx int) (line int, column int) { b := d.orig[:idx] line = bytes.Count(b, []byte("\n")) + 1 if i := bytes.LastIndexByte(b, '\n'); i >= 0 { b = b[i+1:] } column = utf8.RuneCount(b) + 1 // ignore multi-rune characters return line, column } func (d *Decoder) tryConsumeChar(c byte) bool { if len(d.in) > 0 && d.in[0] == c { d.consume(1) return true } return false } // consume consumes n bytes of input and any subsequent whitespace or comments. func (d *Decoder) consume(n int) { d.in = consume(d.in, n) return } // consume consumes n bytes of input and any subsequent whitespace or comments. func consume(b []byte, n int) []byte { b = b[n:] for len(b) > 0 { switch b[0] { case ' ', '\n', '\r', '\t': b = b[1:] case '#': if i := bytes.IndexByte(b, '\n'); i >= 0 { b = b[i+len("\n"):] } else { b = nil } default: return b } } return b } // errId extracts a byte sequence that looks like an invalid ID // (for the purposes of error reporting). func errId(seq []byte) []byte { const maxLen = 32 for i := 0; i < len(seq); { if i > maxLen { return append(seq[:i:i], "…"...) } r, size := utf8.DecodeRune(seq[i:]) if r > utf8.RuneSelf || (r != '/' && isDelim(byte(r))) { if i == 0 { // Either the first byte is invalid UTF-8 or a // delimiter, or the first rune is non-ASCII. // Return it as-is. i = size } return seq[:i:i] } i += size } // No delimiter found. return seq } // isDelim returns true if given byte is a delimiter character. func isDelim(c byte) bool { return !(c == '-' || c == '+' || c == '.' || c == '_' || ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('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/protolazy/lazy.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/protolazy/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 protolazy contains internal data structures for lazy message decoding. package protolazy import ( "fmt" "sort" "google.golang.org/protobuf/encoding/protowire" piface "google.golang.org/protobuf/runtime/protoiface" ) // IndexEntry is the structure for an index of the fields in a message of a // proto (not descending to sub-messages) type IndexEntry struct { FieldNum uint32 // first byte of this tag/field Start uint32 // first byte after a contiguous sequence of bytes for this tag/field, which could // include a single encoding of the field, or multiple encodings for the field End uint32 // True if this protobuf segment includes multiple encodings of the field MultipleContiguous bool } // XXX_lazyUnmarshalInfo has information about a particular lazily decoded message // // Deprecated: Do not use. This will be deleted in the near future. type XXX_lazyUnmarshalInfo struct { // Index of fields and their positions in the protobuf for this // message. Make index be a pointer to a slice so it can be updated // atomically. The index pointer is only set once (lazily when/if // the index is first needed), and must always be SET and LOADED // ATOMICALLY. index *[]IndexEntry // The protobuf associated with this lazily decoded message. It is // only set during proto.Unmarshal(). It doesn't need to be set and // loaded atomically, since any simultaneous set (Unmarshal) and read // (during a get) would already be a race in the app code. Protobuf []byte // The flags present when Unmarshal was originally called for this particular message unmarshalFlags piface.UnmarshalInputFlags } // The Buffer and SetBuffer methods let v2/internal/impl interact with // XXX_lazyUnmarshalInfo via an interface, to avoid an import cycle. // Buffer returns the lazy unmarshal buffer. // // Deprecated: Do not use. This will be deleted in the near future. func (lazy *XXX_lazyUnmarshalInfo) Buffer() []byte { return lazy.Protobuf } // SetBuffer sets the lazy unmarshal buffer. // // Deprecated: Do not use. This will be deleted in the near future. func (lazy *XXX_lazyUnmarshalInfo) SetBuffer(b []byte) { lazy.Protobuf = b } // SetUnmarshalFlags is called to set a copy of the original unmarshalInputFlags. // The flags should reflect how Unmarshal was called. func (lazy *XXX_lazyUnmarshalInfo) SetUnmarshalFlags(f piface.UnmarshalInputFlags) { lazy.unmarshalFlags = f } // UnmarshalFlags returns the original unmarshalInputFlags. func (lazy *XXX_lazyUnmarshalInfo) UnmarshalFlags() piface.UnmarshalInputFlags { return lazy.unmarshalFlags } // AllowedPartial returns true if the user originally unmarshalled this message with // AllowPartial set to true func (lazy *XXX_lazyUnmarshalInfo) AllowedPartial() bool { return (lazy.unmarshalFlags & piface.UnmarshalCheckRequired) == 0 } func protoFieldNumber(tag uint32) uint32 { return tag >> 3 } // buildIndex builds an index of the specified protobuf, return the index // array and an error. func buildIndex(buf []byte) ([]IndexEntry, error) { index := make([]IndexEntry, 0, 16) var lastProtoFieldNum uint32 var outOfOrder bool var r BufferReader = NewBufferReader(buf) for !r.Done() { var tag uint32 var err error var curPos = r.Pos // INLINED: tag, err = r.DecodeVarint32() { i := r.Pos buf := r.Buf if i >= len(buf) { return nil, errOutOfBounds } else if buf[i] < 0x80 { r.Pos++ tag = uint32(buf[i]) } else if r.Remaining() < 5 { var v uint64 v, err = r.DecodeVarintSlow() tag = uint32(v) } else { var v uint32 // we already checked the first byte tag = uint32(buf[i]) & 127 i++ v = uint32(buf[i]) i++ tag |= (v & 127) << 7 if v < 128 { goto done } v = uint32(buf[i]) i++ tag |= (v & 127) << 14 if v < 128 { goto done } v = uint32(buf[i]) i++ tag |= (v & 127) << 21 if v < 128 { goto done } v = uint32(buf[i]) i++ tag |= (v & 127) << 28 if v < 128 { goto done } return nil, errOutOfBounds done: r.Pos = i } } // DONE: tag, err = r.DecodeVarint32() fieldNum := protoFieldNumber(tag) if fieldNum < lastProtoFieldNum { outOfOrder = true } // Skip the current value -- will skip over an entire group as well. // INLINED: err = r.SkipValue(tag) wireType := tag & 0x7 switch protowire.Type(wireType) { case protowire.VarintType: // INLINED: err = r.SkipVarint() i := r.Pos if len(r.Buf)-i < 10 { // Use DecodeVarintSlow() to skip while // checking for buffer overflow, but ignore result _, err = r.DecodeVarintSlow() goto out2 } if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } i++ if r.Buf[i] < 0x80 { goto out } return nil, errOverflow out: r.Pos = i + 1 // DONE: err = r.SkipVarint() case protowire.Fixed64Type: err = r.SkipFixed64() case protowire.BytesType: var n uint32 n, err = r.DecodeVarint32() if err == nil { err = r.Skip(int(n)) } case protowire.StartGroupType: err = r.SkipGroup(tag) case protowire.Fixed32Type: err = r.SkipFixed32() default: err = fmt.Errorf("Unexpected wire type (%d)", wireType) } // DONE: err = r.SkipValue(tag) out2: if err != nil { return nil, err } if fieldNum != lastProtoFieldNum { index = append(index, IndexEntry{FieldNum: fieldNum, Start: uint32(curPos), End: uint32(r.Pos)}, ) } else { index[len(index)-1].End = uint32(r.Pos) index[len(index)-1].MultipleContiguous = true } lastProtoFieldNum = fieldNum } if outOfOrder { sort.Slice(index, func(i, j int) bool { return index[i].FieldNum < index[j].FieldNum || (index[i].FieldNum == index[j].FieldNum && index[i].Start < index[j].Start) }) } return index, nil } func (lazy *XXX_lazyUnmarshalInfo) SizeField(num uint32) (size int) { start, end, found, _, multipleEntries := lazy.FindFieldInProto(num) if multipleEntries != nil { for _, entry := range multipleEntries { size += int(entry.End - entry.Start) } return size } if !found { return 0 } return int(end - start) } func (lazy *XXX_lazyUnmarshalInfo) AppendField(b []byte, num uint32) ([]byte, bool) { start, end, found, _, multipleEntries := lazy.FindFieldInProto(num) if multipleEntries != nil { for _, entry := range multipleEntries { b = append(b, lazy.Protobuf[entry.Start:entry.End]...) } return b, true } if !found { return nil, false } b = append(b, lazy.Protobuf[start:end]...) return b, true } func (lazy *XXX_lazyUnmarshalInfo) SetIndex(index []IndexEntry) { atomicStoreIndex(&lazy.index, &index) } // FindFieldInProto looks for field fieldNum in lazyUnmarshalInfo information // (including protobuf), returns startOffset/endOffset/found. func (lazy *XXX_lazyUnmarshalInfo) FindFieldInProto(fieldNum uint32) (start, end uint32, found, multipleContiguous bool, multipleEntries []IndexEntry) { if lazy.Protobuf == nil { // There is no backing protobuf for this message -- it was made from a builder return 0, 0, false, false, nil } index := atomicLoadIndex(&lazy.index) if index == nil { r, err := buildIndex(lazy.Protobuf) if err != nil { panic(fmt.Sprintf("findFieldInfo: error building index when looking for field %d: %v", fieldNum, err)) } // lazy.index is a pointer to the slice returned by BuildIndex index = &r atomicStoreIndex(&lazy.index, index) } return lookupField(index, fieldNum) } // lookupField returns the offset at which the indicated field starts using // the index, offset immediately after field ends (including all instances of // a repeated field), and bools indicating if field was found and if there // are multiple encodings of the field in the byte range. // // To hande the uncommon case where there are repeated encodings for the same // field which are not consecutive in the protobuf (so we need to returns // multiple start/end offsets), we also return a slice multipleEntries. If // multipleEntries is non-nil, then multiple entries were found, and the // values in the slice should be used, rather than start/end/found. func lookupField(indexp *[]IndexEntry, fieldNum uint32) (start, end uint32, found bool, multipleContiguous bool, multipleEntries []IndexEntry) { // The pointer indexp to the index was already loaded atomically. // The slice is uniquely associated with the pointer, so it doesn't // need to be loaded atomically. index := *indexp for i, entry := range index { if fieldNum == entry.FieldNum { if i < len(index)-1 && entry.FieldNum == index[i+1].FieldNum { // Handle the uncommon case where there are // repeated entries for the same field which // are not contiguous in the protobuf. multiple := make([]IndexEntry, 1, 2) multiple[0] = IndexEntry{fieldNum, entry.Start, entry.End, entry.MultipleContiguous} i++ for i < len(index) && index[i].FieldNum == fieldNum { multiple = append(multiple, IndexEntry{fieldNum, index[i].Start, index[i].End, index[i].MultipleContiguous}) i++ } return 0, 0, false, false, multiple } return entry.Start, entry.End, true, entry.MultipleContiguous, nil } if fieldNum < entry.FieldNum { return 0, 0, false, false, nil } } return 0, 0, false, false, 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/protolazy/pointer_unsafe.go
cmd/vsphere-xcopy-volume-populator/vendor/google.golang.org/protobuf/internal/protolazy/pointer_unsafe.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 protolazy import ( "sync/atomic" "unsafe" ) func atomicLoadIndex(p **[]IndexEntry) *[]IndexEntry { return (*[]IndexEntry)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p)))) } func atomicStoreIndex(p **[]IndexEntry, v *[]IndexEntry) { atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v)) }
go
Apache-2.0
b3b4703e958c25d54c4d48138d9e80ae32fadac3
2026-01-07T09:44:30.792320Z
false